This repository has been archived by the owner on Dec 31, 2020. It is now read-only.
/
user.go
296 lines (254 loc) · 9.25 KB
/
user.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
package impl
import (
"context"
"database/sql"
"errors"
"fmt"
"net/http"
"strings"
"github.com/go-openapi/runtime/middleware"
"github.com/go-openapi/strfmt"
"github.com/go-openapi/swag"
log "github.com/sirupsen/logrus"
"gorm.io/gorm"
"go.timothygu.me/downtomeet/server/db"
"go.timothygu.me/downtomeet/server/impl/responders"
"go.timothygu.me/downtomeet/server/models"
"go.timothygu.me/downtomeet/server/restapi/operations"
)
// GetUserMe implements the GET /user/me endpoint.
func (i *Implementation) GetUserMe(params operations.GetUserMeParams, _ interface{}) middleware.Responder {
ctx := params.HTTPRequest.Context()
logger := log.WithContext(ctx)
session := SessionFromContext(ctx)
idStr := session.Values[UserID]
if idStr == nil {
logger.Error("Session has no user ID")
return responders.InternalServerError{}
}
id, err := db.UserIDFromString(idStr.(string))
if err != nil {
logger.Error("Session has invalid user ID")
return responders.InternalServerError{}
}
tx := i.DB().WithContext(ctx)
var dbUser db.User
if err := tx.First(&dbUser, id).Error; err != nil {
logger.WithError(err).Error("Unable to find session's ID in DB")
return responders.InternalServerError{}
}
if err := tx.Model(&dbUser).Association("Tags").Find(&dbUser.Tags); err != nil {
logger.WithError(err).Error("Unable to find user tags")
return responders.InternalServerError{}
}
if err = tx.Model(&dbUser).Association("OwnedMeetups").Find(&dbUser.OwnedMeetups); err != nil {
logger.WithError(err).Error("Unable to find owned meetup information")
return responders.InternalServerError{}
}
if err = tx.Model(&dbUser).Association("Attending").Find(&dbUser.Attending); err != nil {
logger.WithError(err).Error("Unable to find attending meetup information")
return responders.InternalServerError{}
}
if err = tx.Model(&dbUser).Association("PendingApproval").Find(&dbUser.PendingApproval); err != nil {
logger.WithError(err).Error("Unable to find pending meetup information")
return responders.InternalServerError{}
}
return operations.NewGetUserMeOK().WithPayload(dbUserToModelUser(&dbUser))
}
// GetUserID implements the GET /user/:id endpoint.
func (i *Implementation) GetUserID(params operations.GetUserIDParams) middleware.Responder {
ctx := params.HTTPRequest.Context()
logger := log.WithContext(ctx)
id, err := db.UserIDFromString(params.ID)
if err != nil {
return operations.NewGetUserIDNotFound().WithPayload(&models.Error{
Code: http.StatusNotFound,
Message: "Specified user not found.",
})
}
tx := i.DB().WithContext(ctx)
var dbUser db.User
err = tx.First(&dbUser, id).Error
if errors.Is(err, gorm.ErrRecordNotFound) {
return operations.NewGetUserIDNotFound().WithPayload(&models.Error{
Code: http.StatusNotFound,
Message: "Specified user not found.",
})
} else if err != nil {
logger.WithError(err).Error("Could not access user DB")
return responders.InternalServerError{}
}
session := SessionFromContext(params.HTTPRequest.Context())
if session.Values[UserID] != dbUser.IDString() {
interests := tagsToNames(dbUser.Tags)
modelUser := &models.User{
ID: models.UserID(dbUser.IDString()),
Name: dbUser.Name,
ProfilePic: swag.StringValue(dbUser.ProfilePic),
JoinDate: strfmt.DateTime(dbUser.CreatedAt),
ContactInfo: dbUser.ContactInfo,
Interests: interests,
}
return operations.NewGetUserIDOK().WithPayload(modelUser)
}
if err := tx.Model(&dbUser).Association("Tags").Find(&dbUser.Tags); err != nil {
logger.WithError(err).Error("Unable to find user tags")
return responders.InternalServerError{}
}
if err = tx.Model(&dbUser).Association("OwnedMeetups").Find(&dbUser.OwnedMeetups); err != nil {
logger.WithError(err).Error("Unable to find owned meetup information")
return responders.InternalServerError{}
}
if err = tx.Model(&dbUser).Association("Attending").Find(&dbUser.Attending); err != nil {
logger.WithError(err).Error("Unable to find attending meetup information")
return responders.InternalServerError{}
}
if err = tx.Model(&dbUser).Association("PendingApproval").Find(&dbUser.PendingApproval); err != nil {
logger.WithError(err).Error("Unable to find pending meetup information")
return responders.InternalServerError{}
}
return operations.NewGetUserIDOK().WithPayload(dbUserToModelUser(&dbUser))
}
// PatchUserID implements the PATCH /user/:id endpoint.
func (i *Implementation) PatchUserID(params operations.PatchUserIDParams, _ interface{}) middleware.Responder {
ctx := params.HTTPRequest.Context()
logger := log.WithContext(ctx)
session := SessionFromContext(ctx)
if id := session.Values[UserID]; id != params.ID {
logger.Warn("User tried to PATCH someone else")
return operations.NewPatchUserIDForbidden().WithPayload(&models.Error{
Code: http.StatusForbidden,
Message: "Forbidden.",
})
}
tx := i.DB().WithContext(ctx)
var dbUser db.User
err := tx.First(&dbUser, params.ID).Error
if errors.Is(err, gorm.ErrRecordNotFound) {
return operations.NewPatchUserIDNotFound().WithPayload(&models.Error{
Code: http.StatusNotFound,
Message: "Specified user not found.",
})
} else if err != nil {
logger.WithError(err).Error("Failed to find user in DB")
return responders.InternalServerError{}
}
if err := i.updateDBUser(ctx, &dbUser, params.UpdatedUser); err != nil {
logger.WithError(err).Error("Failed to update user")
return responders.InternalServerError{}
}
return operations.NewPatchUserIDOK().WithPayload(dbUserToModelUser(&dbUser))
}
// GetUserLogout implements the GET /user/logout endpoint.
func (i *Implementation) GetUserLogout(params operations.GetUserLogoutParams) middleware.Responder {
session := SessionFromContext(params.HTTPRequest.Context())
session.Options.MaxAge = -1
return operations.NewGetUserLogoutNoContent()
}
func (i *Implementation) updateDBUser(ctx context.Context, dbUser *db.User, modelUser *models.User) error {
// Update tags first. Do it through SQL since GORM Association mode Replace
// doesn't work reliably when the "tags" table has a unique name constraint.
// https://gorm.io/docs/associations.html#Replace-Associations
tx := i.DB().WithContext(ctx)
var placeholders []string
var variables []interface{}
for _, tag := range modelUser.Interests {
placeholders = append(placeholders, "(CURRENT_TIMESTAMP, CURRENT_TIMESTAMP, ?)")
variables = append(variables, tag)
}
variables = append(variables, sql.Named("user_id", dbUser.ID))
var err error
if len(modelUser.Interests) > 0 {
// https://stackoverflow.com/a/42217872/1937836
err = tx.Raw(fmt.Sprintf(`
WITH
input_rows(created_at, updated_at, name) AS (VALUES %s),
ins AS ( -- insert any tags not yet in the DB
INSERT INTO tags (created_at, updated_at, name)
SELECT * FROM input_rows
ON CONFLICT (name) DO NOTHING
RETURNING created_at, updated_at, deleted_at, id, name
),
all_tags AS ( -- get IDs of tags already in the DB
SELECT * FROM ins
UNION ALL
SELECT t.created_at, t.updated_at, t.deleted_at, t.id, t.name FROM input_rows
JOIN tags t USING (name)
),
ignored1 AS ( -- delete stale tag-user associations
DELETE FROM tag_user tu
WHERE tu.user_id = @user_id AND tu.tag_id NOT IN (SELECT id FROM all_tags)
),
ignored2 AS ( -- insert new tag-user associations, if not already exist
INSERT INTO tag_user (tag_id, user_id)
SELECT id, @user_id FROM all_tags
ON CONFLICT (tag_id, user_id) DO NOTHING
)
SELECT * FROM all_tags
`, strings.Join(placeholders, ", ")), variables...).Scan(&dbUser.Tags).Error
} else {
err = tx.Model(dbUser).Association("Tags").Clear()
dbUser.Tags = nil
}
if err != nil {
return err
}
// Update other fields later.
dbUser.Name = modelUser.Name
dbUser.ContactInfo = modelUser.ContactInfo
if modelUser.Location != nil {
dbUser.Location = db.Coordinates{
Lat: modelUser.Location.Lat,
Lon: modelUser.Location.Lon,
}
} else {
dbUser.Location = db.Coordinates{}
}
return tx.
Model(dbUser).
Select("Name", "ContactInfo", "location_lat", "location_lon").
Updates(dbUser).Error
}
func dbUserToModelUser(dbUser *db.User) *models.User {
interests := tagsToNames(dbUser.Tags)
var location *models.Coordinates
if dbUser.Location.Lat != nil && dbUser.Location.Lon != nil {
location = &models.Coordinates{
Lat: dbUser.Location.Lat,
Lon: dbUser.Location.Lon,
}
}
var connections []string
if dbUser.FacebookID != nil {
connections = append(connections, "Facebook")
}
if dbUser.GoogleID != nil {
connections = append(connections, "Google")
}
return &models.User{
ID: models.UserID(fmt.Sprint(dbUser.ID)),
Name: dbUser.Name,
Email: dbUser.Email,
ProfilePic: swag.StringValue(dbUser.ProfilePic),
JoinDate: strfmt.DateTime(dbUser.CreatedAt),
Connections: connections,
ContactInfo: dbUser.ContactInfo,
Location: location,
Interests: interests,
Attending: meetupsToIDs(dbUser.Attending),
OwnedMeetups: meetupsToIDs(dbUser.OwnedMeetups),
PendingApproval: meetupsToIDs(dbUser.PendingApproval),
}
}
func meetupsToIDs(dbMeetups []*db.Meetup) (ids []models.MeetupID) {
for _, dbMeetup := range dbMeetups {
ids = append(ids, models.MeetupID(dbMeetup.IDString()))
}
return
}
func tagsToNames(dbTags []*db.Tag) (tags []string) {
for _, dbTag := range dbTags {
tags = append(tags, dbTag.Name)
}
return
}