-
Notifications
You must be signed in to change notification settings - Fork 657
Expand file tree
/
Copy pathadmin.go
More file actions
650 lines (561 loc) · 18.8 KB
/
admin.go
File metadata and controls
650 lines (561 loc) · 18.8 KB
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
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
package api
import (
"context"
"net/http"
"time"
"github.com/fatih/structs"
"github.com/go-chi/chi/v5"
"github.com/gofrs/uuid"
"github.com/pkg/errors"
"github.com/sethvargo/go-password/password"
"github.com/supabase/auth/internal/api/apierrors"
"github.com/supabase/auth/internal/api/provider"
"github.com/supabase/auth/internal/models"
"github.com/supabase/auth/internal/observability"
"github.com/supabase/auth/internal/storage"
"github.com/supabase/auth/internal/utilities"
"golang.org/x/crypto/bcrypt"
)
type AdminUserParams struct {
Id string `json:"id"`
Aud string `json:"aud"`
Role string `json:"role"`
Email string `json:"email"`
Phone string `json:"phone"`
Password *string `json:"password"`
PasswordHash string `json:"password_hash"`
EmailConfirm bool `json:"email_confirm"`
PhoneConfirm bool `json:"phone_confirm"`
UserMetaData map[string]interface{} `json:"user_metadata"`
AppMetaData map[string]interface{} `json:"app_metadata"`
BanDuration string `json:"ban_duration"`
}
type adminUserDeleteParams struct {
ShouldSoftDelete bool `json:"should_soft_delete"`
}
type adminUserUpdateFactorParams struct {
FriendlyName string `json:"friendly_name"`
Phone string `json:"phone"`
}
type AdminListUsersResponse struct {
Users []*models.User `json:"users"`
Aud string `json:"aud"`
}
func (a *API) loadUser(w http.ResponseWriter, r *http.Request) (context.Context, error) {
ctx := r.Context()
db := a.db.WithContext(ctx)
userID, err := uuid.FromString(chi.URLParam(r, "user_id"))
if err != nil {
return nil, apierrors.NewNotFoundError(apierrors.ErrorCodeValidationFailed, "user_id must be an UUID")
}
observability.LogEntrySetField(r, "user_id", userID)
u, err := models.FindUserByID(db, userID)
if err != nil {
if models.IsNotFoundError(err) {
return nil, apierrors.NewNotFoundError(apierrors.ErrorCodeUserNotFound, "User not found")
}
return nil, apierrors.NewInternalServerError("Database error loading user").WithInternalError(err)
}
return withUser(ctx, u), nil
}
// Use only after requireAuthentication, so that there is a valid user
func (a *API) loadFactor(w http.ResponseWriter, r *http.Request) (context.Context, error) {
ctx := r.Context()
db := a.db.WithContext(ctx)
user := getUser(ctx)
factorID, err := uuid.FromString(chi.URLParam(r, "factor_id"))
if err != nil {
return nil, apierrors.NewNotFoundError(apierrors.ErrorCodeValidationFailed, "factor_id must be an UUID")
}
observability.LogEntrySetField(r, "factor_id", factorID)
factor, err := user.FindOwnedFactorByID(db, factorID)
if err != nil {
if models.IsNotFoundError(err) {
return nil, apierrors.NewNotFoundError(apierrors.ErrorCodeMFAFactorNotFound, "Factor not found")
}
return nil, apierrors.NewInternalServerError("Database error loading factor").WithInternalError(err)
}
return withFactor(ctx, factor), nil
}
func (a *API) getAdminParams(r *http.Request) (*AdminUserParams, error) {
params := &AdminUserParams{}
if err := retrieveRequestParams(r, params); err != nil {
return nil, err
}
return params, nil
}
// adminUsers responds with a list of all users in a given audience
func (a *API) adminUsers(w http.ResponseWriter, r *http.Request) error {
ctx := r.Context()
db := a.db.WithContext(ctx)
aud := a.requestAud(ctx, r)
pageParams, err := paginate(r)
if err != nil {
return apierrors.NewBadRequestError(apierrors.ErrorCodeValidationFailed, "Bad Pagination Parameters: %v", err).WithInternalError(err)
}
sortParams, err := sort(r, map[string]bool{models.CreatedAt: true}, []models.SortField{{Name: models.CreatedAt, Dir: models.Descending}})
if err != nil {
return apierrors.NewBadRequestError(apierrors.ErrorCodeValidationFailed, "Bad Sort Parameters: %v", err)
}
filter := r.URL.Query().Get("filter")
users, err := models.FindUsersInAudience(db, aud, pageParams, sortParams, filter)
if err != nil {
return apierrors.NewInternalServerError("Database error finding users").WithInternalError(err)
}
addPaginationHeaders(w, r, pageParams)
return sendJSON(w, http.StatusOK, AdminListUsersResponse{
Users: users,
Aud: aud,
})
}
// adminUserGet returns information about a single user
func (a *API) adminUserGet(w http.ResponseWriter, r *http.Request) error {
user := getUser(r.Context())
return sendJSON(w, http.StatusOK, user)
}
// adminUserUpdate updates a single user object
func (a *API) adminUserUpdate(w http.ResponseWriter, r *http.Request) error {
ctx := r.Context()
db := a.db.WithContext(ctx)
config := a.config
user := getUser(ctx)
adminUser := getAdminUser(ctx)
params, err := a.getAdminParams(r)
if err != nil {
return err
}
if params.Email != "" {
params.Email, err = a.validateEmail(params.Email)
if err != nil {
return err
}
}
if params.Phone != "" {
params.Phone, err = validatePhone(params.Phone)
if err != nil {
return err
}
}
var banDuration *time.Duration
if params.BanDuration != "" {
duration := time.Duration(0)
if params.BanDuration != "none" {
duration, err = time.ParseDuration(params.BanDuration)
if err != nil {
return apierrors.NewBadRequestError(apierrors.ErrorCodeValidationFailed, "invalid format for ban duration: %v", err)
}
}
banDuration = &duration
}
if params.Password != nil {
password := *params.Password
if err := a.checkPasswordStrength(ctx, password); err != nil {
return err
}
if err := user.SetPassword(ctx, password, config.Security.DBEncryption.Encrypt, config.Security.DBEncryption.EncryptionKeyID, config.Security.DBEncryption.EncryptionKey); err != nil {
return err
}
}
err = db.Transaction(func(tx *storage.Connection) error {
if params.Role != "" {
if terr := user.SetRole(tx, params.Role); terr != nil {
return terr
}
}
if params.EmailConfirm {
if terr := user.Confirm(tx); terr != nil {
return terr
}
}
if params.PhoneConfirm {
if terr := user.ConfirmPhone(tx); terr != nil {
return terr
}
}
if params.Password != nil {
if terr := user.UpdatePassword(tx, nil); terr != nil {
return terr
}
}
var identities []models.Identity
if params.Email != "" {
if identity, terr := models.FindIdentityByIdAndProvider(tx, user.ID.String(), "email"); terr != nil && !models.IsNotFoundError(terr) {
return terr
} else if identity == nil {
// if the user doesn't have an existing email
// then updating the user's email should create a new email identity
i, terr := a.createNewIdentity(tx, user, "email", structs.Map(provider.Claims{
Subject: user.ID.String(),
Email: params.Email,
EmailVerified: params.EmailConfirm,
}))
if terr != nil {
return terr
}
identities = append(identities, *i)
} else {
// update the existing email identity
if terr := identity.UpdateIdentityData(tx, map[string]interface{}{
"email": params.Email,
"email_verified": params.EmailConfirm,
}); terr != nil {
return terr
}
}
if user.IsAnonymous && params.EmailConfirm {
user.IsAnonymous = false
if terr := tx.UpdateOnly(user, "is_anonymous"); terr != nil {
return terr
}
}
if terr := user.SetEmail(tx, params.Email); terr != nil {
return terr
}
}
if params.Phone != "" {
if identity, terr := models.FindIdentityByIdAndProvider(tx, user.ID.String(), "phone"); terr != nil && !models.IsNotFoundError(terr) {
return terr
} else if identity == nil {
// if the user doesn't have an existing phone
// then updating the user's phone should create a new phone identity
identity, terr := a.createNewIdentity(tx, user, "phone", structs.Map(provider.Claims{
Subject: user.ID.String(),
Phone: params.Phone,
PhoneVerified: params.PhoneConfirm,
}))
if terr != nil {
return terr
}
identities = append(identities, *identity)
} else {
// update the existing phone identity
if terr := identity.UpdateIdentityData(tx, map[string]interface{}{
"phone": params.Phone,
"phone_verified": params.PhoneConfirm,
}); terr != nil {
return terr
}
}
if user.IsAnonymous && params.PhoneConfirm {
user.IsAnonymous = false
if terr := tx.UpdateOnly(user, "is_anonymous"); terr != nil {
return terr
}
}
if terr := user.SetPhone(tx, params.Phone); terr != nil {
return terr
}
}
user.Identities = append(user.Identities, identities...)
if params.AppMetaData != nil {
if terr := user.UpdateAppMetaData(tx, params.AppMetaData); terr != nil {
return terr
}
}
if params.UserMetaData != nil {
if terr := user.UpdateUserMetaData(tx, params.UserMetaData); terr != nil {
return terr
}
}
if banDuration != nil {
if terr := user.Ban(tx, *banDuration); terr != nil {
return terr
}
}
if terr := models.NewAuditLogEntry(config.AuditLog, r, tx, adminUser, models.UserModifiedAction, map[string]interface{}{
"user_id": user.ID,
"user_email": user.Email,
"user_phone": user.Phone,
}); terr != nil {
return terr
}
return nil
})
if err != nil {
return apierrors.NewInternalServerError("Error updating user").WithInternalError(err)
}
return sendJSON(w, http.StatusOK, user)
}
// adminUserCreate creates a new user based on the provided data
func (a *API) adminUserCreate(w http.ResponseWriter, r *http.Request) error {
ctx := r.Context()
db := a.db.WithContext(ctx)
config := a.config
adminUser := getAdminUser(ctx)
params, err := a.getAdminParams(r)
if err != nil {
return err
}
aud := a.requestAud(ctx, r)
if params.Aud != "" {
aud = params.Aud
}
if params.Email == "" && params.Phone == "" {
return apierrors.NewBadRequestError(apierrors.ErrorCodeValidationFailed, "Cannot create a user without either an email or phone")
}
var providers []string
if params.Email != "" {
params.Email, err = a.validateEmail(params.Email)
if err != nil {
return err
}
if user, err := models.IsDuplicatedEmail(db, params.Email, aud, nil, config.Experimental.ProvidersWithOwnLinkingDomain); err != nil {
return apierrors.NewInternalServerError("Database error checking email").WithInternalError(err)
} else if user != nil {
return apierrors.NewUnprocessableEntityError(apierrors.ErrorCodeEmailExists, DuplicateEmailMsg)
}
providers = append(providers, "email")
}
if params.Phone != "" {
params.Phone, err = validatePhone(params.Phone)
if err != nil {
return err
}
if exists, err := models.IsDuplicatedPhone(db, params.Phone, aud); err != nil {
return apierrors.NewInternalServerError("Database error checking phone").WithInternalError(err)
} else if exists {
return apierrors.NewUnprocessableEntityError(apierrors.ErrorCodePhoneExists, "Phone number already registered by another user")
}
providers = append(providers, "phone")
}
if params.Password != nil && params.PasswordHash != "" {
return apierrors.NewBadRequestError(apierrors.ErrorCodeValidationFailed, "Only a password or a password hash should be provided")
}
if (params.Password == nil || *params.Password == "") && params.PasswordHash == "" {
password, err := password.Generate(64, 10, 0, false, true)
if err != nil {
return apierrors.NewInternalServerError("Error generating password").WithInternalError(err)
}
params.Password = &password
}
var user *models.User
if params.PasswordHash != "" {
user, err = models.NewUserWithPasswordHash(params.Phone, params.Email, params.PasswordHash, aud, params.UserMetaData)
} else {
user, err = models.NewUser(params.Phone, params.Email, *params.Password, aud, params.UserMetaData)
}
if err != nil {
if errors.Is(err, bcrypt.ErrPasswordTooLong) {
return apierrors.NewBadRequestError(apierrors.ErrorCodeValidationFailed, "%s", err.Error())
}
return apierrors.NewInternalServerError("Error creating user").WithInternalError(err)
}
if params.Id != "" {
customId, err := uuid.FromString(params.Id)
if err != nil {
return apierrors.NewBadRequestError(apierrors.ErrorCodeValidationFailed, "ID must conform to the uuid v4 format")
}
if customId == uuid.Nil {
return apierrors.NewBadRequestError(apierrors.ErrorCodeValidationFailed, "ID cannot be a nil uuid")
}
user.ID = customId
}
user.AppMetaData = map[string]interface{}{
// TODO: Deprecate "provider" field
// default to the first provider in the providers slice
"provider": providers[0],
"providers": providers,
}
var banDuration *time.Duration
if params.BanDuration != "" {
duration := time.Duration(0)
if params.BanDuration != "none" {
duration, err = time.ParseDuration(params.BanDuration)
if err != nil {
return apierrors.NewBadRequestError(apierrors.ErrorCodeValidationFailed, "invalid format for ban duration: %v", err)
}
}
banDuration = &duration
}
err = db.Transaction(func(tx *storage.Connection) error {
if terr := tx.Create(user); terr != nil {
return terr
}
var identities []models.Identity
if user.GetEmail() != "" {
identity, terr := a.createNewIdentity(tx, user, "email", structs.Map(provider.Claims{
Subject: user.ID.String(),
Email: user.GetEmail(),
}))
if terr != nil {
return terr
}
identities = append(identities, *identity)
}
if user.GetPhone() != "" {
identity, terr := a.createNewIdentity(tx, user, "phone", structs.Map(provider.Claims{
Subject: user.ID.String(),
Phone: user.GetPhone(),
}))
if terr != nil {
return terr
}
identities = append(identities, *identity)
}
user.Identities = identities
if terr := models.NewAuditLogEntry(config.AuditLog, r, tx, adminUser, models.UserSignedUpAction, map[string]interface{}{
"user_id": user.ID,
"user_email": user.Email,
"user_phone": user.Phone,
"provider": providers[0], // complying with the user.AppMetaData["provider"] field as above
}); terr != nil {
return terr
}
role := config.JWT.DefaultGroupName
if params.Role != "" {
role = params.Role
}
if terr := user.SetRole(tx, role); terr != nil {
return terr
}
if params.AppMetaData != nil {
if terr := user.UpdateAppMetaData(tx, params.AppMetaData); terr != nil {
return terr
}
}
if params.EmailConfirm {
if terr := user.Confirm(tx); terr != nil {
return terr
}
}
if params.PhoneConfirm {
if terr := user.ConfirmPhone(tx); terr != nil {
return terr
}
}
if banDuration != nil {
if terr := user.Ban(tx, *banDuration); terr != nil {
return terr
}
}
return nil
})
if err != nil {
return apierrors.NewInternalServerError("Database error creating new user").WithInternalError(err)
}
return sendJSON(w, http.StatusOK, user)
}
// adminUserDelete deletes a user
func (a *API) adminUserDelete(w http.ResponseWriter, r *http.Request) error {
ctx := r.Context()
user := getUser(ctx)
config := a.config
adminUser := getAdminUser(ctx)
db := a.db.WithContext(ctx)
// ShouldSoftDelete defaults to false
params := &adminUserDeleteParams{}
if body, _ := utilities.GetBodyBytes(r); len(body) != 0 {
// we only want to parse the body if it's not empty
// retrieveRequestParams will handle any errors with stream
if err := retrieveRequestParams(r, params); err != nil {
return err
}
}
err := db.Transaction(func(tx *storage.Connection) error {
if terr := models.NewAuditLogEntry(config.AuditLog, r, tx, adminUser, models.UserDeletedAction, map[string]interface{}{
"user_id": user.ID,
"user_email": user.Email,
"user_phone": user.Phone,
}); terr != nil {
return apierrors.NewInternalServerError("Error recording audit log entry").WithInternalError(terr)
}
if params.ShouldSoftDelete {
if user.DeletedAt != nil {
// user has been soft deleted already
return nil
}
if terr := user.SoftDeleteUser(tx); terr != nil {
return apierrors.NewInternalServerError("Error soft deleting user").WithInternalError(terr)
}
if terr := user.SoftDeleteUserIdentities(tx); terr != nil {
return apierrors.NewInternalServerError("Error soft deleting user identities").WithInternalError(terr)
}
// hard delete all associated factors
if terr := models.DeleteFactorsByUserId(tx, user.ID); terr != nil {
return apierrors.NewInternalServerError("Error deleting user's factors").WithInternalError(terr)
}
// hard delete all associated sessions
if terr := models.Logout(tx, user.ID); terr != nil {
return apierrors.NewInternalServerError("Error deleting user's sessions").WithInternalError(terr)
}
} else {
if terr := tx.Destroy(user); terr != nil {
return apierrors.NewInternalServerError("Database error deleting user").WithInternalError(terr)
}
}
return nil
})
if err != nil {
return err
}
return sendJSON(w, http.StatusOK, map[string]interface{}{})
}
func (a *API) adminUserDeleteFactor(w http.ResponseWriter, r *http.Request) error {
ctx := r.Context()
config := a.config
user := getUser(ctx)
factor := getFactor(ctx)
db := a.db.WithContext(ctx)
err := db.Transaction(func(tx *storage.Connection) error {
if terr := models.NewAuditLogEntry(config.AuditLog, r, tx, user, models.DeleteFactorAction, map[string]interface{}{
"user_id": user.ID,
"factor_id": factor.ID,
}); terr != nil {
return terr
}
if terr := tx.Destroy(factor); terr != nil {
return apierrors.NewInternalServerError("Database error deleting factor").WithInternalError(terr)
}
return nil
})
if err != nil {
return err
}
return sendJSON(w, http.StatusOK, factor)
}
func (a *API) adminUserGetFactors(w http.ResponseWriter, r *http.Request) error {
ctx := r.Context()
user := getUser(ctx)
return sendJSON(w, http.StatusOK, user.Factors)
}
// adminUserUpdate updates a single factor object
func (a *API) adminUserUpdateFactor(w http.ResponseWriter, r *http.Request) error {
ctx := r.Context()
config := a.config
factor := getFactor(ctx)
user := getUser(ctx)
adminUser := getAdminUser(ctx)
params := &adminUserUpdateFactorParams{}
db := a.db.WithContext(ctx)
if err := retrieveRequestParams(r, params); err != nil {
return err
}
err := db.Transaction(func(tx *storage.Connection) error {
if params.FriendlyName != "" {
if terr := factor.UpdateFriendlyName(tx, params.FriendlyName); terr != nil {
return terr
}
}
if params.Phone != "" && factor.IsPhoneFactor() {
phone, err := validatePhone(params.Phone)
if err != nil {
return apierrors.NewBadRequestError(apierrors.ErrorCodeValidationFailed, "Invalid phone number format (E.164 required)")
}
if terr := factor.UpdatePhone(tx, phone); terr != nil {
return terr
}
}
if terr := models.NewAuditLogEntry(config.AuditLog, r, tx, adminUser, models.UpdateFactorAction, map[string]interface{}{
"user_id": user.ID,
"factor_id": factor.ID,
"factor_type": factor.FactorType,
}); terr != nil {
return terr
}
return nil
})
if err != nil {
return err
}
return sendJSON(w, http.StatusOK, factor)
}