-
Notifications
You must be signed in to change notification settings - Fork 16
/
user_handler.go
326 lines (270 loc) · 10.4 KB
/
user_handler.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
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
package httphandler
import (
"errors"
"fmt"
"net/http"
"sort"
"github.com/stellar/go/support/http/httpdecode"
"github.com/stellar/go/support/log"
"github.com/stellar/go/support/render/httpjson"
"github.com/stellar/stellar-disbursement-platform-backend/internal/data"
"github.com/stellar/stellar-disbursement-platform-backend/internal/message"
"github.com/stellar/stellar-disbursement-platform-backend/internal/serve/httperror"
"github.com/stellar/stellar-disbursement-platform-backend/internal/serve/middleware"
"github.com/stellar/stellar-disbursement-platform-backend/internal/serve/validators"
"github.com/stellar/stellar-disbursement-platform-backend/internal/services"
"github.com/stellar/stellar-disbursement-platform-backend/stellar-auth/pkg/auth"
"github.com/stellar/stellar-disbursement-platform-backend/stellar-multitenant/pkg/tenant"
)
type UserHandler struct {
AuthManager auth.AuthManager
MessengerClient message.MessengerClient
Models *data.Models
}
type UserActivationRequest struct {
UserID string `json:"user_id"`
IsActive *bool `json:"is_active"`
}
type UserSorterByEmail []auth.User
func (a UserSorterByEmail) Len() int { return len(a) }
func (a UserSorterByEmail) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a UserSorterByEmail) Less(i, j int) bool { return a[i].Email < a[j].Email }
type UserSorterByIsActive []auth.User
func (a UserSorterByIsActive) Len() int { return len(a) }
func (a UserSorterByIsActive) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a UserSorterByIsActive) Less(i, j int) bool { return a[i].IsActive }
func (uar UserActivationRequest) validate() *httperror.HTTPError {
validator := validators.NewValidator()
validator.Check(uar.UserID != "", "user_id", "user_id is required")
validator.Check(uar.IsActive != nil, "is_active", "is_active is required")
if validator.HasErrors() {
return httperror.BadRequest("Request invalid", nil, validator.Errors)
}
return nil
}
type CreateUserRequest struct {
FirstName string `json:"first_name"`
LastName string `json:"last_name"`
Email string `json:"email"`
Roles []data.UserRole `json:"roles"`
}
func (cur CreateUserRequest) validate() *httperror.HTTPError {
validator := validators.NewValidator()
validator.Check(cur.FirstName != "", "fist_name", "fist_name is required")
validator.Check(cur.LastName != "", "last_name", "last_name is required")
validator.Check(cur.Email != "", "email", "email is required")
validateRoles(validator, cur.Roles)
if validator.HasErrors() {
return httperror.BadRequest("Request invalid", nil, validator.Errors)
}
return nil
}
type UpdateRolesRequest struct {
UserID string `json:"user_id"`
Roles []data.UserRole `json:"roles"`
}
func (upr UpdateRolesRequest) validate() *httperror.HTTPError {
validator := validators.NewValidator()
validator.Check(upr.UserID != "", "user_id", "user_id is required")
validateRoles(validator, upr.Roles)
if validator.HasErrors() {
return httperror.BadRequest("Request invalid", nil, validator.Errors)
}
return nil
}
func validateRoles(validator *validators.Validator, roles []data.UserRole) {
// NOTE: in the MVP, users should have only one role.
validator.Check(len(roles) == 1, "roles", "the number of roles required is exactly one")
// Validating the role of the request is a valid value
if _, ok := validator.Errors["roles"]; !ok {
role := roles[0]
validator.Check(role.IsValid(), "roles", fmt.Sprintf("unexpected value for roles[0]=%s. Expect one of these values: %s", role, data.GetAllRoles()))
}
}
func (h UserHandler) UserActivation(rw http.ResponseWriter, req *http.Request) {
ctx := req.Context()
token, ok := ctx.Value(middleware.TokenContextKey).(string)
if !ok {
log.Ctx(ctx).Warn("token not found when updating user activation")
httperror.Unauthorized("", nil, nil).Render(rw)
return
}
var reqBody UserActivationRequest
if err := httpdecode.DecodeJSON(req, &reqBody); err != nil {
err = fmt.Errorf("decoding the request body: %w", err)
log.Ctx(ctx).Error(err)
httperror.BadRequest("", err, nil).Render(rw)
return
}
if err := reqBody.validate(); err != nil {
err.Render(rw)
return
}
// Check if the users are trying to update their own activation
userID, err := h.AuthManager.GetUserID(ctx, token)
if err != nil {
if errors.Is(err, auth.ErrInvalidToken) {
httperror.Unauthorized("", err, nil).Render(rw)
return
}
err = fmt.Errorf("getting user from token: %w", err)
httperror.InternalError(ctx, "", err, nil).Render(rw)
return
}
if userID == reqBody.UserID {
httperror.BadRequest("", nil, map[string]interface{}{"user_id": "cannot update your own activation"}).Render(rw)
return
}
var activationErr error
if *reqBody.IsActive {
log.Ctx(ctx).Infof("[ActivateUserAccount] - User ID %s activating user with account ID %s", userID, reqBody.UserID)
activationErr = h.AuthManager.ActivateUser(ctx, token, reqBody.UserID)
} else {
log.Ctx(ctx).Infof("[DeactivateUserAccount] - User ID %s deactivating user with account ID %s", userID, reqBody.UserID)
activationErr = h.AuthManager.DeactivateUser(ctx, token, reqBody.UserID)
}
if activationErr != nil {
if errors.Is(activationErr, auth.ErrInvalidToken) {
httperror.Unauthorized("", activationErr, nil).Render(rw)
} else if errors.Is(activationErr, auth.ErrNoRowsAffected) {
httperror.BadRequest("", activationErr, map[string]interface{}{"user_id": "user_id is invalid"}).Render(rw)
} else {
httperror.InternalError(ctx, "", activationErr, nil).Render(rw)
}
return
}
httpjson.RenderStatus(rw, http.StatusOK, map[string]string{"message": "user activation was updated successfully"}, httpjson.JSON)
}
func (h UserHandler) CreateUser(rw http.ResponseWriter, req *http.Request) {
ctx := req.Context()
tnt, err := tenant.GetTenantFromContext(ctx)
if err != nil {
err = fmt.Errorf("getting tenant from context: %w", err)
httperror.Unauthorized("", err, nil).Render(rw)
return
}
token, ok := ctx.Value(middleware.TokenContextKey).(string)
if !ok {
log.Ctx(ctx).Warn("token not found when updating user activation")
httperror.Unauthorized("", nil, nil).Render(rw)
return
}
var reqBody CreateUserRequest
if err = httpdecode.DecodeJSON(req, &reqBody); err != nil {
err = fmt.Errorf("decoding the request body: %w", err)
log.Ctx(ctx).Error(err)
httperror.BadRequest("", err, nil).Render(rw)
return
}
if err := reqBody.validate(); err != nil {
err.Render(rw)
return
}
authenticatedUserID, err := h.AuthManager.GetUserID(ctx, token)
if err != nil {
err = fmt.Errorf("getting request authenticated user ID: %w", err)
log.Ctx(ctx).Error(err)
httperror.Unauthorized("", err, nil).Render(rw)
return
}
newUser := auth.User{
FirstName: reqBody.FirstName,
LastName: reqBody.LastName,
Email: reqBody.Email,
Roles: data.FromUserRoleArrayToStringArray(reqBody.Roles),
}
s := services.NewCreateUserService(h.Models, h.Models.DBConnectionPool, h.AuthManager, h.MessengerClient)
u, err := s.CreateUser(ctx, newUser, *tnt.SDPUIBaseURL)
if err != nil {
if errors.Is(err, auth.ErrUserEmailAlreadyExists) {
httperror.BadRequest(auth.ErrUserEmailAlreadyExists.Error(), err, nil).Render(rw)
return
}
httperror.InternalError(ctx, "Cannot create user", err, nil).Render(rw)
return
}
log.Ctx(ctx).Infof("[CreateUserAccount] - User ID %s created user with account ID %s", authenticatedUserID, u.ID)
httpjson.RenderStatus(rw, http.StatusCreated, u, httpjson.JSON)
}
func (h UserHandler) UpdateUserRoles(rw http.ResponseWriter, req *http.Request) {
ctx := req.Context()
token, ok := ctx.Value(middleware.TokenContextKey).(string)
if !ok {
log.Ctx(ctx).Warn("token not found when updating user roles")
httperror.Unauthorized("", nil, nil).Render(rw)
return
}
var reqBody UpdateRolesRequest
if err := httpdecode.DecodeJSON(req, &reqBody); err != nil {
err = fmt.Errorf("decoding the request body: %w", err)
log.Ctx(ctx).Error(err)
httperror.BadRequest("", err, nil).Render(rw)
return
}
if err := reqBody.validate(); err != nil {
err.Render(rw)
return
}
authenticatedUserID, err := h.AuthManager.GetUserID(ctx, token)
if err != nil {
err = fmt.Errorf("getting request authenticated user ID: %w", err)
log.Ctx(ctx).Error(err)
httperror.Unauthorized("", err, nil).Render(rw)
return
}
updateUserRolesErr := h.AuthManager.UpdateUserRoles(ctx, token, reqBody.UserID, data.FromUserRoleArrayToStringArray(reqBody.Roles))
if updateUserRolesErr != nil {
if errors.Is(updateUserRolesErr, auth.ErrInvalidToken) {
httperror.Unauthorized("", updateUserRolesErr, nil).Render(rw)
return
}
if errors.Is(updateUserRolesErr, auth.ErrNoRowsAffected) {
httperror.BadRequest("", updateUserRolesErr, map[string]interface{}{"user_id": "user_id is invalid"}).Render(rw)
return
}
httperror.InternalError(ctx, "Cannot update user activation", updateUserRolesErr, nil).Render(rw)
return
}
log.Ctx(ctx).Infof("[UpdateUserRoles] - User ID %s updated user with account ID %s roles to %v", authenticatedUserID, reqBody.UserID, reqBody.Roles)
httpjson.RenderStatus(rw, http.StatusOK, map[string]string{"message": "user roles were updated successfully"}, httpjson.JSON)
}
func (h UserHandler) GetAllUsers(rw http.ResponseWriter, req *http.Request) {
validator := validators.NewUserQueryValidator()
queryParams := validator.ParseParametersFromRequest(req)
if validator.HasErrors() {
httperror.BadRequest("request invalid", nil, validator.Errors).Render(rw)
return
}
ctx := req.Context()
token, ok := ctx.Value(middleware.TokenContextKey).(string)
if !ok {
log.Ctx(ctx).Warn("token not found when getting all users")
httperror.Unauthorized("", nil, nil).Render(rw)
return
}
users, err := h.AuthManager.GetAllUsers(ctx, token)
if err != nil {
if errors.Is(err, auth.ErrInvalidToken) {
httperror.Unauthorized("", err, nil).Render(rw)
return
}
httperror.InternalError(ctx, "Cannot get all users", err, nil).Render(rw)
return
}
// Order users
sortingFn := sort.Sort
if queryParams.SortOrder == data.SortOrderDESC {
sortingFn = func(data sort.Interface) {
sort.Sort(sort.Reverse(data))
}
}
switch queryParams.SortBy {
case data.SortFieldEmail:
sortingFn(UserSorterByEmail(users))
case data.SortFieldIsActive:
sortingFn(UserSorterByIsActive(users))
default:
log.Ctx(ctx).Warnf("unexpected sort field in GetAllUsers: %s", queryParams.SortBy)
}
httpjson.RenderStatus(rw, http.StatusOK, users, httpjson.JSON)
}