/
user.go
249 lines (213 loc) · 7.59 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
package api
import (
"context"
"errors"
"net/http"
"time"
"github.com/gofrs/uuid"
"github.com/supabase/auth/internal/api/sms_provider"
"github.com/supabase/auth/internal/models"
"github.com/supabase/auth/internal/storage"
"github.com/supabase/auth/internal/utilities"
)
// UserUpdateParams parameters for updating a user
type UserUpdateParams struct {
Email string `json:"email"`
Password *string `json:"password"`
Nonce string `json:"nonce"`
Data map[string]interface{} `json:"data"`
AppData map[string]interface{} `json:"app_metadata,omitempty"`
Phone string `json:"phone"`
Channel string `json:"channel"`
CodeChallenge string `json:"code_challenge"`
CodeChallengeMethod string `json:"code_challenge_method"`
}
func (a *API) validateUserUpdateParams(ctx context.Context, p *UserUpdateParams) error {
config := a.config
var err error
if p.Email != "" {
p.Email, err = validateEmail(p.Email)
if err != nil {
return err
}
}
if p.Phone != "" {
if p.Phone, err = validatePhone(p.Phone); err != nil {
return err
}
if p.Channel == "" {
p.Channel = sms_provider.SMSProvider
}
if !sms_provider.IsValidMessageChannel(p.Channel, config.Sms.Provider) {
return badRequestError(InvalidChannelError)
}
}
if p.Password != nil {
if err := a.checkPasswordStrength(ctx, *p.Password); err != nil {
return err
}
}
return nil
}
// UserGet returns a user
func (a *API) UserGet(w http.ResponseWriter, r *http.Request) error {
ctx := r.Context()
claims := getClaims(ctx)
if claims == nil {
return badRequestError("Could not read claims")
}
aud := a.requestAud(ctx, r)
if aud != claims.Audience {
return badRequestError("Token audience doesn't match request audience")
}
user := getUser(ctx)
return sendJSON(w, http.StatusOK, user)
}
// UserUpdate updates fields on a user
func (a *API) UserUpdate(w http.ResponseWriter, r *http.Request) error {
ctx := r.Context()
db := a.db.WithContext(ctx)
config := a.config
aud := a.requestAud(ctx, r)
params := &UserUpdateParams{}
if err := retrieveRequestParams(r, params); err != nil {
return err
}
user := getUser(ctx)
session := getSession(ctx)
if err := a.validateUserUpdateParams(ctx, params); err != nil {
return err
}
if params.AppData != nil && !isAdmin(user, config) {
if !isAdmin(user, config) {
return unauthorizedError("Updating app_metadata requires admin privileges")
}
}
if user.IsAnonymous {
updatingForbiddenFields := false
updatingForbiddenFields = updatingForbiddenFields || (params.Password != nil && *params.Password != "")
if updatingForbiddenFields {
return unprocessableEntityError("Updating password of an anonymous user is not possible")
}
}
if user.IsSSOUser {
updatingForbiddenFields := false
updatingForbiddenFields = updatingForbiddenFields || (params.Password != nil && *params.Password != "")
updatingForbiddenFields = updatingForbiddenFields || (params.Email != "" && params.Email != user.GetEmail())
updatingForbiddenFields = updatingForbiddenFields || (params.Phone != "" && params.Phone != user.GetPhone())
updatingForbiddenFields = updatingForbiddenFields || (params.Nonce != "")
if updatingForbiddenFields {
return unprocessableEntityError("Updating email, phone, password of a SSO account only possible via SSO")
}
}
if params.Email != "" && user.GetEmail() != params.Email {
if duplicateUser, err := models.IsDuplicatedEmail(db, params.Email, aud, user); err != nil {
return internalServerError("Database error checking email").WithInternalError(err)
} else if duplicateUser != nil {
return unprocessableEntityError(DuplicateEmailMsg)
}
}
if params.Phone != "" && user.GetPhone() != params.Phone {
if exists, err := models.IsDuplicatedPhone(db, params.Phone, aud); err != nil {
return internalServerError("Database error checking phone").WithInternalError(err)
} else if exists {
return unprocessableEntityError(DuplicatePhoneMsg)
}
}
if params.Password != nil {
if config.Security.UpdatePasswordRequireReauthentication {
now := time.Now()
// we require reauthentication if the user hasn't signed in recently in the current session
if session == nil || now.After(session.CreatedAt.Add(24*time.Hour)) {
if len(params.Nonce) == 0 {
return badRequestError("Password update requires reauthentication")
}
if err := a.verifyReauthentication(params.Nonce, db, config, user); err != nil {
return err
}
}
}
password := *params.Password
if password != "" {
if user.EncryptedPassword != "" && user.Authenticate(ctx, password) {
return unprocessableEntityError("New password should be different from the old password.")
}
}
if err := user.SetPassword(ctx, password); err != nil {
return err
}
}
err := db.Transaction(func(tx *storage.Connection) error {
var terr error
if params.Password != nil {
var sessionID *uuid.UUID
if session != nil {
sessionID = &session.ID
}
if terr = user.UpdatePassword(tx, sessionID); terr != nil {
return internalServerError("Error during password storage").WithInternalError(terr)
}
if terr := models.NewAuditLogEntry(r, tx, user, models.UserUpdatePasswordAction, "", nil); terr != nil {
return terr
}
}
if params.Data != nil {
if terr = user.UpdateUserMetaData(tx, params.Data); terr != nil {
return internalServerError("Error updating user").WithInternalError(terr)
}
}
if params.AppData != nil {
if terr = user.UpdateAppMetaData(tx, params.AppData); terr != nil {
return internalServerError("Error updating user").WithInternalError(terr)
}
}
if params.Email != "" && params.Email != user.GetEmail() {
mailer := a.Mailer(ctx)
referrer := utilities.GetReferrer(r, config)
flowType := getFlowFromChallenge(params.CodeChallenge)
if isPKCEFlow(flowType) {
flowState, terr := generateFlowState(models.EmailChange.String(), models.EmailChange, params.CodeChallengeMethod, params.CodeChallenge, &user.ID)
if terr != nil {
return terr
}
if terr := tx.Create(flowState); terr != nil {
return terr
}
}
externalURL := getExternalHost(ctx)
if terr = a.sendEmailChange(tx, config, user, mailer, params.Email, referrer, externalURL, config.Mailer.OtpLength, flowType); terr != nil {
if errors.Is(terr, MaxFrequencyLimitError) {
return tooManyRequestsError("For security purposes, you can only request this once every 60 seconds")
}
return internalServerError("Error sending change email").WithInternalError(terr)
}
}
if params.Phone != "" && params.Phone != user.GetPhone() {
if config.Sms.Autoconfirm {
user.PhoneChange = params.Phone
if _, terr := a.smsVerify(r, tx, user, &VerifyParams{
Type: phoneChangeVerification,
Phone: params.Phone,
}); terr != nil {
return terr
}
} else {
smsProvider, terr := sms_provider.GetSmsProvider(*config)
if terr != nil {
return badRequestError("Error sending sms: %v", terr)
}
if _, terr := a.sendPhoneConfirmation(tx, user, params.Phone, phoneChangeVerification, smsProvider, params.Channel); terr != nil {
return internalServerError("Error sending phone change otp").WithInternalError(terr)
}
}
}
if terr = models.NewAuditLogEntry(r, tx, user, models.UserModifiedAction, "", nil); terr != nil {
return internalServerError("Error recording audit log entry").WithInternalError(terr)
}
return nil
})
if err != nil {
return err
}
return sendJSON(w, http.StatusOK, user)
}