-
Notifications
You must be signed in to change notification settings - Fork 0
/
http_auth.go
574 lines (496 loc) · 14.3 KB
/
http_auth.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
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
package http
import (
"context"
"encoding/json"
"fmt"
"net/http"
"reflect"
"time"
"github.com/dgrijalva/jwt-go"
"github.com/go-playground/validator/v10"
"github.com/google/uuid"
"github.com/gorilla/mux"
"github.com/pkg/errors"
"github.com/unnamedxaer/gymm-api/entities"
"github.com/unnamedxaer/gymm-api/usecases"
"github.com/unnamedxaer/gymm-api/validation"
)
type Claims struct {
ID string `json:"id"`
// IssuedAt is here to make the tokens unique by different payload
IssuedAt int64 `json:"createdAt"`
*entities.RefreshToken `json:"r"`
jwt.StandardClaims
}
const cookieJwtTokenName = "__HOST-token"
// Login validates input and login the user
func (app *App) Login(w http.ResponseWriter, req *http.Request) {
var ui *usecases.UserInput
err := json.NewDecoder(req.Body).Decode(&ui)
if err != nil {
logDebugError(app.l, req, err)
resErrText := getErrOfMalformedInput(
&ui, []string{"ID", "CreatedAt", "Username"})
responseWithErrorTxt(w, http.StatusBadRequest, resErrText)
return
}
ctx := req.Context()
user, err := app.authUsecases.Login(ctx, ui)
if err != nil && errors.Is(err, &usecases.IncorrectCredentialsError{}) {
logDebugError(app.l, req, err)
responseWithInternalError(w)
return
}
output := map[string]interface{}{
"user": user,
}
if user == nil {
output["error"] = "incorrect credentials"
clearCookieJWTAuthToken(w)
responseWithJSON(w, http.StatusOK, output)
return
}
device := req.UserAgent() // @todo: improve, mb send some info from client
err = app.login(ctx, w, user.ID, device, req.Method, req.RequestURI)
if err != nil {
logDebugError(app.l, req, err)
clearCookieJWTAuthToken(w)
responseWithInternalError(w)
return
}
responseWithJSON(w, http.StatusOK, output)
}
// Register validates input, creates new user and login the user
func (app *App) Register(w http.ResponseWriter, req *http.Request) {
var u usecases.UserInput
err := json.NewDecoder(req.Body).Decode(&u)
if err != nil {
logDebugError(app.l, req, err)
resErrText := getErrOfMalformedInput(&u, []string{"ID", "CreatedAt"})
responseWithError(w, http.StatusUnprocessableEntity, errors.New(resErrText))
return
}
defer req.Body.Close()
trimWhitespacesOnUserInput(&u)
err = validateUserInput(app.Validate, &u)
if err != nil {
logDebugError(app.l, req, err)
if svErr, ok := err.(*validation.StructValidError); ok {
responseWithJSON(w, http.StatusNotAcceptable, svErr.ValidationErrors())
return
}
responseWithError(w, http.StatusInternalServerError, err)
return
}
ctx := req.Context()
user, err := app.userUsecases.CreateUser(ctx, &u)
if err != nil {
logDebugError(app.l, req, err)
if errors.Is(err, usecases.NewErrorEmailAddressInUse()) {
responseWithErrorTxt(w, http.StatusConflict, "email address already in use")
return
}
responseWithError(w, http.StatusInternalServerError, err)
return
}
// login user
output := map[string]interface{}{
"user": user,
}
err = app.login(ctx, w, user.ID, req.UserAgent(), req.Method, req.RequestURI)
if err != nil {
logDebugError(app.l, req, err)
clearCookieJWTAuthToken(w)
responseWithInternalError(w)
return
}
responseWithJSON(w, http.StatusCreated, output)
}
// Logout logouts the user, removes token from cookies & storage
func (app *App) Logout(w http.ResponseWriter, req *http.Request) {
cookie, err := req.Cookie(cookieJwtTokenName)
var n int64
if cookie != nil {
ctx := req.Context()
n, err = app.authUsecases.DeleteJWT(
ctx,
&entities.UserToken{
Token: cookie.Value,
})
}
if err != nil {
logDebugError(app.l, req, err)
} else if n == 0 {
logDebugError(app.l, req, fmt.Errorf(
"JWT was not deleted for cookie.value: %s", cookie.Value))
}
clearCookieJWTAuthToken(w)
w.WriteHeader(http.StatusOK)
}
// GetSessions returns all user sessions
func (app *App) GetSessions(w http.ResponseWriter, req *http.Request) {
ctx := req.Context()
userID, ok := ctx.Value(contextKeyUserID).(string)
if !ok {
responseWithUnauthorized(w)
return
}
jwts, err := app.authUsecases.GetUserJWTs(ctx, userID, entities.All)
if err != nil {
logDebugError(app.l, req, err)
clearCookieJWTAuthToken(w)
responseWithInternalError(w)
return
}
responseWithJSON(w, http.StatusOK, &jwts)
}
// LogoutSession logouts the user, from the device/browser
func (app *App) LogoutSession(w http.ResponseWriter, req *http.Request) {
ctx := req.Context()
userID, ok := ctx.Value(contextKeyUserID).(string)
if !ok {
responseWithUnauthorized(w)
return
}
ut := entities.UserToken{}
err := json.NewDecoder(req.Body).Decode(&ut)
if err != nil {
logDebugError(app.l, req, err)
responseWithError(w, http.StatusBadRequest, err)
return
}
if ut.UserID != "" && ut.UserID != userID {
responseWithUnauthorized(w)
return
}
ut.UserID = userID
cookie, _ := req.Cookie(cookieJwtTokenName)
if cookie != nil {
// determine if user want to delete current token
// and logout his in that case
if ut.Token != "" {
if ut.Token == cookie.Value {
clearCookieJWTAuthToken(w)
}
} else {
storedTokens, err := app.authUsecases.GetUserJWTs(
ctx, userID, entities.NotExpired)
if err != nil {
logDebugError(app.l, req, err)
}
for _, t := range storedTokens {
if t.Token == cookie.Value {
clearCookieJWTAuthToken(w)
break
}
}
}
}
n, err := app.authUsecases.DeleteJWT(ctx, &ut)
if err != nil {
logDebugError(app.l, req, err)
var e *usecases.InvalidIDError
if errors.As(err, &e) {
responseWithError(w, http.StatusBadRequest, e)
return
}
responseWithInternalError(w)
return
}
if n == 0 {
responseWithJSON(
w,
http.StatusOK,
map[string]string{"warning": "no records were deleted"})
return
}
w.WriteHeader(http.StatusOK)
}
// LogoutSession logouts the user, from the device/browser
func (app *App) LogoutAllSessions(w http.ResponseWriter, req *http.Request) {
ctx := req.Context()
userID, ok := ctx.Value(contextKeyUserID).(string)
if !ok {
responseWithUnauthorized(w)
return
}
n, err := app.authUsecases.DeleteRefreshTokenAndAllTokens(ctx, userID)
if err != nil {
logDebugError(app.l, req, err)
var e *usecases.InvalidIDError
if errors.As(err, &e) {
responseWithError(w, http.StatusBadRequest, e)
return
}
responseWithInternalError(w)
return
}
clearCookieJWTAuthToken(w)
if n == 0 {
responseWithJSON(
w, http.StatusOK, map[string]string{"warning": "no records were deleted"})
return
}
w.WriteHeader(http.StatusOK)
}
func (app *App) ChangePassword(w http.ResponseWriter, req *http.Request) {
ctx := req.Context()
userID, ok := ctx.Value(contextKeyUserID).(string)
if !ok {
responseWithUnauthorized(w)
return
}
body := make(map[string]string, 2)
err := json.NewDecoder(req.Body).Decode(&body)
if err != nil {
logDebugError(app.l, req, err)
responseWithError(w, http.StatusBadRequest, err)
return
}
rv := reflect.TypeOf(usecases.UserInput{})
srf, ok := rv.FieldByName("Password")
if !ok {
responseWithInternalError(w)
return
}
validationRules := srf.Tag.Get("validate")
fieldName := "password"
err = app.Validate.Var(body[fieldName], validationRules)
if err != nil {
logDebugError(app.l, req, err)
// @refactor: see exercise validation
formattedErrors := make(map[string]string, 1)
validateErrs, ok := err.(validator.ValidationErrors)
if !ok {
formattedErrors[fieldName] = err.Error()
}
for _, err := range validateErrs {
formattedErrors[fieldName] += getErrorTranslation4User(&err, fieldName)
}
vErrs := validation.NewStructValidError(formattedErrors)
responseWithJSON(w, http.StatusBadRequest, vErrs.Format())
return
}
err = app.authUsecases.ChangePassword(ctx, userID, body["oldPassword"], body["password"])
if err != nil {
logDebugError(app.l, req, err)
if errors.Is(err, usecases.IncorrectCredentialsError{}) {
responseWithError(w, http.StatusUnauthorized, err)
return
}
// @todo: handle other error types
responseWithError(w, http.StatusInternalServerError, err)
return
}
w.WriteHeader(http.StatusOK)
}
func (app *App) AddResetPasswordRequest(w http.ResponseWriter, req *http.Request) {
input := usecases.UserInput{}
err := json.NewDecoder(req.Body).Decode(&input)
if err != nil {
logDebugError(app.l, req, err)
errTxt := getErrOfMalformedInput(&input, []string{
"Username", "Password", "CreatedAt",
})
responseWithErrorTxt(w, http.StatusBadRequest, errTxt)
return
}
rv := reflect.TypeOf(input)
srf, ok := rv.FieldByName("EmailAddress")
if !ok {
responseWithInternalError(w)
return
}
validationRules := srf.Tag.Get("validate")
fieldName := "emailAddress"
err = app.Validate.Var(input.EmailAddress, validationRules)
if err != nil {
logDebugError(app.l, req, err)
// @refactor: see exercise validation
formattedErrors := make(map[string]string, 1)
validateErrs, ok := err.(validator.ValidationErrors)
if !ok {
formattedErrors[fieldName] = err.Error()
}
for _, err := range validateErrs {
formattedErrors[fieldName] += getErrorTranslation4User(&err, fieldName)
}
vErrs := validation.NewStructValidError(formattedErrors)
responseWithJSON(w, http.StatusBadRequest, vErrs.Format())
return
}
ctx := req.Context()
_, err = app.authUsecases.AddResetPasswordRequest(ctx, app.mailer, input.EmailAddress)
if err != nil {
logDebugError(app.l, req, err)
responseWithError(w, http.StatusBadRequest, err)
return
}
w.WriteHeader(http.StatusAccepted)
}
func (app *App) UpdatePasswordOnResetRequest(w http.ResponseWriter, req *http.Request) {
// clean it in case another account was logged in
// to not mess it up.
clearCookieJWTAuthToken(w)
reqID, ok := mux.Vars(req)["requestID"]
if !ok {
err := errors.New("missign request id query parameter")
logDebugError(app.l, req, err)
responseWithError(w, http.StatusBadRequest, err)
return
}
input := usecases.UserInput{}
err := json.NewDecoder(req.Body).Decode(&input)
if err != nil {
logDebugError(app.l, req, err)
errTxt := getErrOfMalformedInput(&input, []string{
"Username", "EmailAddress", "CreatedAt",
})
responseWithErrorTxt(w, http.StatusBadRequest, errTxt)
return
}
rv := reflect.TypeOf(input)
srf, ok := rv.FieldByName("Password")
if !ok {
responseWithInternalError(w)
return
}
validationRules := srf.Tag.Get("validate")
fieldName := "password"
err = app.Validate.Var(input.Password, validationRules)
if err != nil {
logDebugError(app.l, req, err)
// @refactor: see exercise validation
formattedErrors := make(map[string]string, 1)
validateErrs, ok := err.(validator.ValidationErrors)
if !ok {
// @thought: probably should return code 500 here
formattedErrors[fieldName] = err.Error()
}
for _, err := range validateErrs {
formattedErrors[fieldName] += getErrorTranslation4User(&err, fieldName)
}
vErrs := validation.NewStructValidError(formattedErrors)
responseWithJSON(w, http.StatusBadRequest, vErrs.Format())
return
}
ctx := req.Context()
err = app.authUsecases.UpdatePasswordForResetRequest(ctx, reqID, input.Password)
if err != nil {
logDebugError(app.l, req, err)
var rnfErr *usecases.RecordNotExistsError
if errors.As(err, &rnfErr) {
responseWithUnauthorized(w, formatUnauthorizedError("reset password request"))
return
}
responseWithError(w, http.StatusInternalServerError, err)
return
}
w.WriteHeader(http.StatusOK)
}
func (app *App) Refresh(w http.ResponseWriter, req *http.Request) {
w.WriteHeader(http.StatusOK)
}
// login make user authenticated by
// creating tokens and setting them in user response as a cookie
// tokens are also stored in db
func (app *App) login(
ctx context.Context,
w http.ResponseWriter,
userID, device, method, reqURI string) error {
rt, err := app.authUsecases.GetRefreshToken(ctx, userID)
if err != nil {
app.l.Debug().Msgf("[%s %s]: error: %v", method, reqURI, err)
// the retrive of the refresh token has failed for some reason,
// but we can try to create new refresh token.
}
if rt == nil || time.Until(rt.ExpiresAt) <= 0 {
rt, err = createRefreshToken(
ctx, userID, app.authUsecases.SaveRefreshToken)
if err != nil {
return err
}
}
token, err := createJWTAuth(
ctx, userID, device, rt, app.jwtKey, app.authUsecases.SaveJWT)
if err != nil {
return err
}
setCookieJWTAuthToken(w, token.Token, token.ExpiresAt)
return nil
}
// sets a cookie with jwt
func setCookieJWTAuthToken(w http.ResponseWriter, token string, expTime time.Time) {
http.SetCookie(w, &http.Cookie{
Name: cookieJwtTokenName,
Value: token,
// Expires: expTime,
HttpOnly: true,
SameSite: http.SameSiteStrictMode,
// Secure: true,
Path: "/",
})
}
// sets -1 to the cookie max age to force its removal
func clearCookieJWTAuthToken(w http.ResponseWriter) {
http.SetCookie(w, &http.Cookie{
Name: cookieJwtTokenName,
MaxAge: -1, // remove cookie
})
}
// generate new jwt for given user and saves it in storage
func createJWTAuth(
ctx context.Context,
userID string,
device string,
rt *entities.RefreshToken,
jwtKey []byte,
saveFunc func(
ctx context.Context,
userID string,
device string,
token string,
expiresAt time.Time) (*entities.UserToken, error)) (*entities.UserToken, error) {
now := time.Now().UTC()
expirationTime := now.Add(time.Second * 60 * 5) // @todo: configurable time
claims := Claims{
ID: userID,
RefreshToken: rt,
IssuedAt: now.UnixNano(),
StandardClaims: jwt.StandardClaims{
ExpiresAt: expirationTime.Unix(),
IssuedAt: now.Unix(),
},
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, &claims)
tokenStr, err := token.SignedString(jwtKey)
if err != nil {
return nil, err
}
return saveFunc(ctx, userID, device, tokenStr, expirationTime)
}
// generate new refresh token for given user and saves it in storage
func createRefreshToken(
ctx context.Context,
userID string,
saveFunc func(
ctx context.Context,
userID string,
token string,
expiresAt time.Time) (*entities.RefreshToken, error)) (*entities.RefreshToken, error) {
refreshVal, err := uuid.NewRandom()
if err != nil {
return nil, err
}
return saveFunc(ctx, userID, refreshVal.String(), time.Now().AddDate(1, 0, 0))
}
// it returns nil error if token is valid
func validateRefreshToken(rt *entities.RefreshToken, clientRefToken string) error {
if rt == nil || time.Until(rt.ExpiresAt) <= 0 {
return errors.New("token & refresh token expired")
}
if rt.Token != clientRefToken {
return errors.New("invalid refresh token")
}
return nil
}