-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathauthStore.go
872 lines (749 loc) · 28.5 KB
/
authStore.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
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
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
package auth
import (
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"os"
"os/exec"
"regexp"
"strings"
"time"
jwt "github.com/dgrijalva/jwt-go"
"github.com/pkg/errors"
)
var emailCookieName = "Email"
var sessionCookieName = "Session"
var rememberMeCookieName = "RememberMe"
var emailRegex = regexp.MustCompile(`^(?i)[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$`)
const emailExpireMins int = 60 * 24 * 365 // 1 year
const emailExpireDuration time.Duration = time.Duration(emailExpireMins) * time.Minute
const passwordResetEmailExpireMins int = 60 * 48 // 2 days
const passwordResetEmailExpireDuration time.Duration = time.Duration(passwordResetEmailExpireMins) * time.Minute
const sessionRenewDuration time.Duration = 5 * time.Minute
const sessionExpireDuration time.Duration = time.Hour
const rememberMeRenewDuration time.Duration = time.Hour
const rememberMeExpireDuration time.Duration = time.Hour * 24 * 30 // 30 days
const passwordValidationMessage string = "Password must be at least 7 characters"
var errInvalidCSRF = errors.New("Invalid CSRF token")
var errMissingCSRF = errors.New("Missing CSRF token")
// AuthStorer interface provides the necessary functionality to get and store authentication information
type AuthStorer interface {
GetSession(w http.ResponseWriter, r *http.Request) (*LoginSession, error)
GetBasicAuth(w http.ResponseWriter, r *http.Request) (*LoginSession, error)
OAuthLogin(w http.ResponseWriter, r *http.Request) (string, error)
Login(w http.ResponseWriter, r *http.Request) (*LoginSession, error)
Register(w http.ResponseWriter, r *http.Request, params EmailSendParams, password string) error
RequestPasswordReset(w http.ResponseWriter, r *http.Request, params EmailSendParams) error
Logout(w http.ResponseWriter, r *http.Request) error
CreateProfile(w http.ResponseWriter, r *http.Request) (*LoginSession, error)
VerifyEmail(w http.ResponseWriter, r *http.Request, params EmailSendParams) (string, *User, error)
VerifyPasswordReset(w http.ResponseWriter, r *http.Request, emailVerificationCode string) (string, *User, error)
CreateSecondaryEmail(w http.ResponseWriter, r *http.Request, templateName, emailSubject string) error
SetPrimaryEmail(w http.ResponseWriter, r *http.Request, templateName, emailSubject string) error
UpdatePassword(w http.ResponseWriter, r *http.Request) (*LoginSession, error)
UpdateInfo(userID string, info map[string]interface{}) error
}
type emailCookie struct {
EmailVerificationCode string
ExpireTimeUTC time.Time
}
type sessionCookie struct {
SessionID string
RenewTimeUTC time.Time
ExpireTimeUTC time.Time
}
type rememberMeCookie struct {
Selector string
Token string
RenewTimeUTC time.Time
ExpireTimeUTC time.Time
}
type authStore struct {
b Backender
mailer Mailer
cookieStore CookieStorer
}
// NewAuthStore is used to create an AuthStorer for most authentication needs
func NewAuthStore(b Backender, mailer Mailer, customPrefix, cookieDomain string, cookieKey []byte, secureOnly bool) AuthStorer {
emailCookieName = customPrefix + "Email"
sessionCookieName = customPrefix + "Session"
rememberMeCookieName = customPrefix + "RememberMe"
return &authStore{b, mailer, newCookieStore(cookieKey, cookieDomain, secureOnly)}
}
func (s *authStore) GetSession(w http.ResponseWriter, r *http.Request) (*LoginSession, error) {
b := s.b.Clone()
defer b.Close()
return s.getSession(w, r, b)
}
func (s *authStore) getSession(w http.ResponseWriter, r *http.Request, b Backender) (*LoginSession, error) {
csrfToken := r.Header.Get("X-CSRF-Token")
if csrfToken == "" {
return nil, errMissingCSRF
}
cookie, err := s.getSessionCookie(w, r)
if err != nil || cookie.SessionID == "" { // impossible to get the session if there is no cookie
return nil, newAuthError("Session cookie not found", err)
}
sessionHash, err := decodeStringToHash(cookie.SessionID)
if err != nil {
return nil, newAuthError("Unable to decode session cookie", err)
}
session, err := b.GetSession(sessionHash)
if err != nil {
if err == errSessionNotFound {
s.deleteSessionCookie(w)
}
return nil, newLoggedError("Failed to verify session", err)
}
if session.RenewTimeUTC.Before(time.Now().UTC()) || session.ExpireTimeUTC.Before(time.Now().UTC()) {
if err := s.renewSession(w, r, b, cookie.SessionID, session); err != nil {
return nil, err
}
}
if session.CSRFToken != csrfToken {
return nil, errInvalidCSRF
}
return session, nil
}
func (s *authStore) GetBasicAuth(w http.ResponseWriter, r *http.Request) (*LoginSession, error) {
b := s.b.Clone()
defer b.Close()
return s.getBasicAuth(w, r, b)
}
func (s *authStore) getBasicAuth(w http.ResponseWriter, r *http.Request, b Backender) (*LoginSession, error) {
session, err := s.getSession(w, r, b)
if err == nil {
return session, nil
}
if email, password, ok := r.BasicAuth(); ok {
session, err := s.login(w, r, b, email, password, false)
if err != nil {
return nil, err
}
return session, nil
}
return nil, newAuthError("Problem decoding credentials from basic auth", nil)
}
func (s *authStore) getRememberMe(w http.ResponseWriter, r *http.Request, b Backender) (*rememberMeSession, error) {
cookie, err := s.getRememberMeCookie(w, r)
if err != nil || cookie.Selector == "" { // impossible to get the remember Me if there is no cookie
return nil, newAuthError("RememberMe cookie not found", err)
}
if cookie.ExpireTimeUTC.Before(time.Now().UTC()) {
s.deleteRememberMeCookie(w)
return nil, newAuthError("RememberMe cookie has expired", nil)
}
rememberMe, err := b.GetRememberMe(cookie.Selector)
if err != nil {
if err == errRememberMeNotFound {
s.deleteRememberMeCookie(w)
}
return nil, newLoggedError("Unable to find matching RememberMe in DB", err)
}
if err := encodedHashEquals(cookie.Token, rememberMe.TokenHash); err != nil {
s.deleteRememberMeCookie(w)
return nil, newLoggedError("RememberMe cookie doesn't match backend token", err)
}
if rememberMe.RenewTimeUTC.Before(time.Now().UTC()) {
renewTimeUTC := time.Now().UTC().Add(rememberMeRenewDuration)
err = b.UpdateRememberMe(cookie.Selector, renewTimeUTC)
if err != nil {
if err == errRememberMeNotFound {
s.deleteRememberMeCookie(w)
}
return nil, newLoggedError("Unable to renew RememberMe", err)
}
rememberMe.RenewTimeUTC = renewTimeUTC
}
return rememberMe, nil
}
func (s *authStore) renewSession(w http.ResponseWriter, r *http.Request, b Backender, sessionID string, session *LoginSession) error {
// expired so check for valid rememberMe for renewal
if session.ExpireTimeUTC.Before(time.Now().UTC()) {
r, err := s.getRememberMe(w, r, b)
if err != nil {
return newAuthError("Unable to renew session", err)
}
session.ExpireTimeUTC = time.Now().UTC().Add(sessionExpireDuration) // renew for sessionExpireDuration like we just typed in password again
if session.ExpireTimeUTC.After(r.ExpireTimeUTC) { // don't exceed rememberMe expiration time
session.ExpireTimeUTC = r.ExpireTimeUTC
}
}
session.RenewTimeUTC = time.Now().UTC().Add(sessionRenewDuration)
if session.RenewTimeUTC.After(session.ExpireTimeUTC) {
session.RenewTimeUTC = session.ExpireTimeUTC
}
err := b.UpdateSession(session.SessionHash, session.RenewTimeUTC, session.ExpireTimeUTC)
if err != nil {
return newLoggedError("Problem updating session", err)
}
return s.saveSessionCookie(w, sessionID, session.RenewTimeUTC, session.ExpireTimeUTC)
}
/******************************** Logout ***********************************************/
func (s *authStore) Logout(w http.ResponseWriter, r *http.Request) error {
b := s.b.Clone()
defer b.Close()
session, err := s.getSession(w, r, b)
s.deleteSessionCookie(w)
if err != nil {
return err
}
return b.DeleteSession(session.SessionHash)
}
/******************************** Login ***********************************************/
func (s *authStore) Login(w http.ResponseWriter, r *http.Request) (*LoginSession, error) {
credentials, err := getCredentials(r)
if err != nil {
return nil, newAuthError("Unable to get credentials", err)
}
b := s.b.Clone()
defer b.Close()
return s.login(w, r, b, credentials.Email, credentials.Password, credentials.RememberMe)
}
func (s *authStore) login(w http.ResponseWriter, r *http.Request, b Backender, email, password string, rememberMe bool) (*LoginSession, error) {
if !isValidEmail(email) {
return nil, newAuthError("Please enter a valid email address.", nil)
}
if !isValidPassword(password) {
return nil, newAuthError(passwordValidationMessage, nil)
}
// add in check for DDOS attack. Slow down or lock out checks for same account
// or same IP with multiple failed attempts
login, err := b.LoginAndGetUser(email, password)
if err != nil {
return nil, newLoggedError("Invalid username or password", err)
}
if !login.IsEmailVerified {
return nil, newAuthError("Your email has not been verified.", nil)
}
return s.createSession(w, r, b, login.UserID, email, login.Info, rememberMe)
}
func (s *authStore) OAuthLogin(w http.ResponseWriter, r *http.Request) (string, error) {
email, info, err := getOAuthCredentials(r)
if err != nil {
return "", err
}
b := s.b.Clone()
defer b.Close()
return s.oauthLogin(w, r, b, email, info)
}
func (s *authStore) oauthLogin(w http.ResponseWriter, r *http.Request, b Backender, email string, info map[string]interface{}) (string, error) {
user, err := b.GetUser(email)
if user == nil || err != nil {
user, err = b.AddUserFull(email, "", info)
if err != nil {
return "", newLoggedError("Unable to create login", err)
}
}
session, err := s.createSession(w, r, b, user.UserID, email, info, false)
if err != nil {
return "", err
}
return session.CSRFToken, nil
}
func getOAuthCredentials(r *http.Request) (string, map[string]interface{}, error) {
var email, email2 string
info := make(map[string]interface{})
authHeader := r.Header.Get("Authorization")
if authHeader == "" {
return "", nil, fmt.Errorf("No authorization found")
}
authHeaderParts := strings.Split(authHeader, " ")
if len(authHeaderParts) != 2 || strings.ToLower(authHeaderParts[0]) != "bearer" {
return "", nil, fmt.Errorf("Authorization header format must be Bearer {token}")
}
// need to actually parse here and handle error
token, _ := jwt.Parse(authHeaderParts[1], func(token *jwt.Token) (interface{}, error) {
//if _, ok := token.Method.(*jwt.SigningMethodRSA); !ok {
// return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
//}
// supposed to validate the signature according to Microsoft. This is not trivial
// https://docs.microsoft.com/en-us/azure/active-directory/develop/active-directory-v2-tokens#validating-tokens
// hmacSampleSecret is a []byte containing your secret, e.g. []byte("my_secret_key")
return []byte("my_secret_key"), nil
})
claims, ok := token.Claims.(jwt.MapClaims)
if ok {
info["fullname"] = fmt.Sprintf("%v", claims["name"])
email = fmt.Sprintf("%v", claims["unique_name"])
fmt.Println("unique_name:", email)
email2 = fmt.Sprintf("%v", claims["email"])
fmt.Println("email:", email2)
if email == "" || info["fullname"] == "" {
return "", nil, fmt.Errorf("expected email and fullname")
}
}
return email, info, nil
}
func (s *authStore) createSession(w http.ResponseWriter, r *http.Request, b Backender, userID, email string, info map[string]interface{}, rememberMe bool) (*LoginSession, error) {
var err error
var selector, token, tokenHash string
if rememberMe {
selector, token, tokenHash, err = generateSelectorTokenAndHash()
if err != nil {
return nil, newLoggedError("Unable to generate RememberMe", err)
}
}
sessionID, sessionHash, err := generateStringAndHash()
if err != nil {
return nil, newLoggedError("Problem generating sessionId", nil)
}
csrfToken, err := generateRandomString()
if err != nil {
return nil, newLoggedError("Problem generating csrf token", nil)
}
session, err := b.CreateSession(userID, email, info, sessionHash, csrfToken, time.Now().UTC().Add(sessionRenewDuration), time.Now().UTC().Add(sessionExpireDuration))
if err != nil {
return nil, newLoggedError("Unable to create new session", err)
}
var remember *rememberMeSession
if rememberMe {
remember, err = b.CreateRememberMe(userID, email, selector, tokenHash, time.Now().UTC().Add(rememberMeRenewDuration), time.Now().UTC().Add(rememberMeExpireDuration))
if err != nil {
return nil, newLoggedError("Unable to create rememberMe session", err)
}
}
sessionCookie, err := s.getSessionCookie(w, r)
if err == nil && sessionCookie.SessionID != "" {
oldSessionHash, err := decodeStringToHash(sessionCookie.SessionID)
if err == nil {
b.DeleteSession(oldSessionHash)
}
}
rememberCookie, err := s.getRememberMeCookie(w, r)
if err == nil && rememberCookie.Selector != "" {
b.DeleteRememberMe(rememberCookie.Selector)
s.deleteRememberMeCookie(w)
}
if rememberMe {
err := s.saveRememberMeCookie(w, selector, token, remember.RenewTimeUTC, remember.ExpireTimeUTC)
if err != nil {
return nil, newAuthError("Unable to save rememberMe cookie", err)
}
}
err = s.saveSessionCookie(w, sessionID, session.RenewTimeUTC, session.ExpireTimeUTC)
if err != nil {
return nil, err
}
return session, nil
}
func isValidPassword(password string) bool {
return len(password) >= 7
}
// EmailSendParams contains information necessary to send an email to the user
type EmailSendParams struct {
VerificationCode string
Email string
BaseURL string
Info map[string]interface{}
TemplateSuccess string
SubjectSuccess string
TemplateFailure string
SubjectFailure string
}
func (s *authStore) RequestPasswordReset(w http.ResponseWriter, r *http.Request, sendParams EmailSendParams) error {
b := s.b.Clone()
defer b.Close()
return s.requestPasswordReset(r, b, sendParams)
}
func (s *authStore) requestPasswordReset(r *http.Request, b Backender, params EmailSendParams) error {
if !isValidEmail(params.Email) {
return newAuthError("Invalid email", nil)
}
u, err := b.GetUser(params.Email)
if err != nil {
if err := s.mailer.SendMessage(params.Email, params.TemplateFailure, params.SubjectFailure, params); err != nil {
return newLoggedError("An email has been sent to the user with instructions on how to reset their password", err)
}
return nil // user does not exist, send success message anyway to prevent fishing for user data. Email owner will be notified of attempt
}
for key, value := range params.Info {
u.Info[key] = value
}
verifyCode, err := s.addEmailSession(b, u.UserID, params.Email, u.Info)
if err != nil {
return newLoggedError("An email has been sent to the user with instructions on how to reset their password", err)
}
params.VerificationCode = verifyCode[:len(verifyCode)-1] // drop the "=" at the end of the code since it makes it look like a querystring
if err := s.mailer.SendMessage(params.Email, params.TemplateSuccess, params.SubjectSuccess, params); err != nil {
return newLoggedError("An email has been sent to the user with instructions on how to reset their password", err)
}
return nil
}
func (s *authStore) Register(w http.ResponseWriter, r *http.Request, params EmailSendParams, password string) error {
b := s.b.Clone()
defer b.Close()
return s.register(r, b, params, password)
}
func (s *authStore) register(r *http.Request, b Backender, params EmailSendParams, password string) error {
userID, err := getRegisterUserID(b, params, password)
if err != nil {
return err
}
verifyCode, err := s.addEmailSession(b, userID, params.Email, params.Info)
if err != nil {
return newLoggedError("Unable to save user", err)
}
params.VerificationCode = verifyCode[:len(verifyCode)-1] // drop the "=" at the end of the code since it makes it look like a querystring
if err := s.mailer.SendMessage(params.Email, params.TemplateSuccess, params.SubjectSuccess, params); err != nil {
return newLoggedError("Unable to send verification email", err)
}
return nil
}
func getRegisterUserID(b Backender, params EmailSendParams, password string) (string, error) {
if !isValidEmail(params.Email) {
return "", newAuthError("Invalid email", nil)
}
user, _ := b.GetUser(params.Email)
if user != nil {
if user.IsEmailVerified {
return "", newAuthError("User already registered", nil)
}
return user.UserID, nil
}
if password != "" {
if !isValidPassword(password) {
return "", newAuthError(passwordValidationMessage, nil)
}
user, err := b.AddUserFull(params.Email, password, params.Info)
if err != nil {
return "", newLoggedError("Failed to add user", err)
}
return user.UserID, nil
}
return "", nil
}
func (s *authStore) addEmailSession(b Backender, userID, email string, info map[string]interface{}) (string, error) {
verifyCode, verifyHash, err := generateStringAndHash()
if err != nil {
return "", newLoggedError("Problem generating email confirmation code", err)
}
csrfToken, err := generateRandomString()
if err != nil {
return "", newLoggedError("Problem generating csrf token", err)
}
err = b.CreateEmailSession(userID, email, info, verifyHash, csrfToken)
if err != nil {
return "", newLoggedError("Problem adding user to database", err)
}
return verifyCode, nil
}
func (s *authStore) CreateProfile(w http.ResponseWriter, r *http.Request) (*LoginSession, error) {
profile, err := getProfile(r)
if err != nil {
return nil, newAuthError("Unable to get profile information from form", err)
}
csrfToken := r.Header.Get("X-CSRF-Token")
if csrfToken == "" {
return nil, errMissingCSRF
}
b := s.b.Clone()
defer b.Close()
return s.createProfile(w, r, b, csrfToken, profile)
}
func (s *authStore) createProfile(w http.ResponseWriter, r *http.Request, b Backender, csrfToken string, userProfile *profile) (*LoginSession, error) {
if !isValidPassword(userProfile.Password) {
return nil, newAuthError(passwordValidationMessage, nil)
}
emailCookie, err := s.getEmailCookie(w, r)
if err != nil || emailCookie.EmailVerificationCode == "" {
return nil, newLoggedError("Unable to get email verification cookie", err)
}
emailVerifyHash, err := decodeStringToHash(emailCookie.EmailVerificationCode) // base64 decode and hash
if err != nil {
return nil, newLoggedError("Invalid email verification cookie", err)
}
session, err := b.GetEmailSession(emailVerifyHash)
if err != nil {
return nil, newLoggedError("Invalid email verification", err)
}
if session.CSRFToken != csrfToken {
return nil, errInvalidCSRF
}
mergedInfo := session.Info
for key, value := range userProfile.Info {
mergedInfo[key] = value
}
err = b.UpdateUser(session.UserID, userProfile.Password, mergedInfo)
if err != nil {
return nil, newLoggedError("Unable to update user", err)
}
err = b.DeleteEmailSession(session.EmailVerifyHash)
if err != nil {
return nil, newLoggedError("Error while creating profile", err)
}
ls, err := s.createSession(w, r, b, session.UserID, session.Email, mergedInfo, false)
if err != nil {
return nil, err
}
s.deleteEmailCookie(w)
return ls, nil
}
// move to sessionStore
func (s *authStore) VerifyEmail(w http.ResponseWriter, r *http.Request, params EmailSendParams) (string, *User, error) {
b := s.b.Clone()
defer b.Close()
return s.verifyEmail(w, r, b, params)
}
func (s *authStore) verifyEmail(w http.ResponseWriter, r *http.Request, b Backender, params EmailSendParams) (string, *User, error) {
emailVerificationCode := params.VerificationCode
if !strings.HasSuffix(emailVerificationCode, "=") { // add back the "=" then decode
emailVerificationCode = emailVerificationCode + "="
}
emailVerifyHash, err := decodeStringToHash(emailVerificationCode)
if err != nil {
return "", nil, newLoggedError("Invalid verification code", err)
}
session, err := b.GetEmailSession(emailVerifyHash)
if err != nil {
return "", nil, newLoggedError("Failed to verify email", err)
}
userID, err := s.markAsVerified(w, b, session, emailVerificationCode)
if err != nil {
return "", nil, err
}
info := session.Info
for key, value := range params.Info {
info[key] = value
}
params.Info = info
err = s.mailer.SendMessage(session.Email, params.TemplateSuccess, params.SubjectSuccess, params)
if err != nil {
return "", nil, newLoggedError("Failed to send welcome email", err)
}
return session.CSRFToken, &User{UserID: userID, Email: session.Email, Info: session.Info}, nil
}
func (s *authStore) markAsVerified(w http.ResponseWriter, b Backender, session *emailSession, emailVerificationCode string) (string, error) {
if session.UserID != "" {
err := b.VerifyEmail(session.Email)
if err != nil {
return "", newLoggedError("Failed to verify email", err)
}
b.DeleteEmailSession(session.EmailVerifyHash)
s.deleteEmailCookie(w)
return session.UserID, nil
}
userID, err := b.AddVerifiedUser(session.Email, session.Info)
if err != nil {
return "", newLoggedError("Failed to create user", err)
}
err = b.UpdateEmailSession(session.EmailVerifyHash, userID)
if err != nil {
return "", newLoggedError("Failed to update email session", err)
}
err = s.saveEmailCookie(w, emailVerificationCode, time.Now().UTC().Add(emailExpireDuration))
if err != nil {
return "", newLoggedError("Failed to save email cookie", err)
}
return userID, nil
}
func (s *authStore) VerifyPasswordReset(w http.ResponseWriter, r *http.Request, emailVerificationCode string) (string, *User, error) {
b := s.b.Clone()
defer b.Close()
return s.verifyPasswordReset(w, r, b, emailVerificationCode)
}
func (s *authStore) verifyPasswordReset(w http.ResponseWriter, r *http.Request, b Backender, emailVerificationCode string) (string, *User, error) {
if !strings.HasSuffix(emailVerificationCode, "=") { // add back the "=" then decode
emailVerificationCode = emailVerificationCode + "="
}
emailVerifyHash, err := decodeStringToHash(emailVerificationCode)
if err != nil {
return "", nil, newLoggedError("Invalid verification code", err)
}
session, err := b.GetEmailSession(emailVerifyHash)
if err != nil {
return "", nil, newLoggedError("Failed to verify email", err)
}
err = s.saveEmailCookie(w, emailVerificationCode, time.Now().UTC().Add(passwordResetEmailExpireDuration))
if err != nil {
return "", nil, newLoggedError("Failed to save email cookie", err)
}
return session.CSRFToken, &User{Email: session.Email, Info: session.Info}, nil
}
func (s *authStore) CreateSecondaryEmail(w http.ResponseWriter, r *http.Request, templateName, emailSubject string) error {
// steps to set new primary email address:
// 1. create new secondary email (this step)
// 2. send verification email
// 3. user verifies email
// 4. user sets email to primary email
return nil
}
func (s *authStore) SetPrimaryEmail(w http.ResponseWriter, r *http.Request, templateName, emailSubject string) error {
// be sure to require current email and password (i.e. require login) to change primary email
// invalidate old sessions?
return nil
}
func (s *authStore) UpdatePassword(w http.ResponseWriter, r *http.Request) (*LoginSession, error) {
profile, err := getProfile(r)
if err != nil {
return nil, newAuthError("Unable to get profile information from form", err)
}
csrfToken := r.Header.Get("X-CSRF-Token")
if csrfToken == "" {
return nil, errMissingCSRF
}
b := s.b.Clone()
defer b.Close()
return s.updatePassword(w, r, b, csrfToken, profile.Password)
}
func (s *authStore) updatePassword(w http.ResponseWriter, r *http.Request, b Backender, csrfToken, password string) (*LoginSession, error) {
emailCookie, err := s.getEmailCookie(w, r)
if err != nil || emailCookie.EmailVerificationCode == "" {
return nil, newLoggedError("Unable to get email verification cookie", err)
}
emailVerifyHash, err := decodeStringToHash(emailCookie.EmailVerificationCode) // base64 decode and hash
if err != nil {
return nil, newLoggedError("Invalid email verification cookie", err)
}
session, err := b.GetEmailSession(emailVerifyHash)
if err != nil {
return nil, newLoggedError("Invalid email verification", err)
}
if session.CSRFToken != csrfToken {
return nil, errInvalidCSRF
}
err = b.DeleteEmailSession(session.EmailVerifyHash)
if err != nil {
return nil, newLoggedError("Error while updating password", err)
}
err = b.DeleteSessions(session.Email)
if err != nil {
return nil, newLoggedError("Error while deleting login sessions", err)
}
err = b.DeleteRememberMes(session.Email)
if err != nil {
return nil, newLoggedError("Error while deleting remember me sessions", err)
}
err = b.UpdateUser(session.UserID, password, session.Info)
if err != nil {
return nil, newLoggedError("Unable to update password", err)
}
ls, err := s.createSession(w, r, b, session.UserID, session.Email, nil, false)
if err != nil {
return nil, err
}
s.deleteEmailCookie(w)
if ls.Info == nil {
ls.Info = make(map[string]interface{})
}
ls.Info["destinationURL"] = GetInfoString(session.Info, "destinationURL")
return ls, nil
}
func (s *authStore) UpdateInfo(userID string, info map[string]interface{}) error {
b := s.b.Clone()
defer b.Close()
return b.UpdateInfo(userID, info)
}
func (s *authStore) getEmailCookie(w http.ResponseWriter, r *http.Request) (*emailCookie, error) {
email := &emailCookie{}
return email, s.cookieStore.Get(w, r, emailCookieName, email)
}
func (s *authStore) getSessionCookie(w http.ResponseWriter, r *http.Request) (*sessionCookie, error) {
session := &sessionCookie{}
return session, s.cookieStore.Get(w, r, sessionCookieName, session)
}
func (s *authStore) getRememberMeCookie(w http.ResponseWriter, r *http.Request) (*rememberMeCookie, error) {
rememberMe := &rememberMeCookie{}
return rememberMe, s.cookieStore.Get(w, r, rememberMeCookieName, rememberMe)
}
func (s *authStore) deleteEmailCookie(w http.ResponseWriter) {
s.cookieStore.Delete(w, emailCookieName)
}
func (s *authStore) deleteSessionCookie(w http.ResponseWriter) {
s.cookieStore.Delete(w, sessionCookieName)
}
func (s *authStore) deleteRememberMeCookie(w http.ResponseWriter) {
s.cookieStore.Delete(w, rememberMeCookieName)
}
func (s *authStore) saveEmailCookie(w http.ResponseWriter, emailVerificationCode string, expireTimeUTC time.Time) error {
cookie := emailCookie{EmailVerificationCode: emailVerificationCode, ExpireTimeUTC: expireTimeUTC}
return s.cookieStore.PutWithExpire(w, emailCookieName, emailExpireMins, &cookie)
}
func (s *authStore) saveSessionCookie(w http.ResponseWriter, sessionID string, renewTimeUTC, expireTimeUTC time.Time) error {
cookie := sessionCookie{SessionID: sessionID, RenewTimeUTC: renewTimeUTC, ExpireTimeUTC: expireTimeUTC}
err := s.cookieStore.Put(w, sessionCookieName, &cookie)
if err != nil {
return newAuthError("Error saving session cookie", err)
}
return nil
}
func (s *authStore) saveRememberMeCookie(w http.ResponseWriter, selector, token string, renewTimeUTC, expireTimeUTC time.Time) error {
cookie := rememberMeCookie{Selector: selector, Token: token, RenewTimeUTC: renewTimeUTC, ExpireTimeUTC: expireTimeUTC}
return s.cookieStore.Put(w, rememberMeCookieName, &cookie)
}
type credentials struct {
Email string
Password string
RememberMe bool
}
func getCredentials(r *http.Request) (*credentials, error) {
credentials := &credentials{}
return credentials, getJSON(r, credentials)
}
func generateThumbnail(filename string) (string, error) {
newName, err := generateRandomString()
if err != nil {
return "", newLoggedError("Unable to create new filename", err)
}
var args = []string{
"-s", "150",
"-o", newName,
filename,
}
var cmd *exec.Cmd
path, _ := exec.LookPath("vipsthumbnail")
cmd = exec.Command(path, args...)
err = cmd.Run()
if err != nil {
return "", newLoggedError("Error running vipsthumbnail", err)
}
return newName, nil
}
type profile struct {
Password string
Info map[string]interface{}
}
func getProfile(r *http.Request) (*profile, error) {
profile := &profile{Info: make(map[string]interface{})}
r.ParseMultipartForm(32 << 20) // 32 MB file
file, handler, err := r.FormFile("file")
if err == nil { // received the file, so save it
defer file.Close()
f, err := os.OpenFile(handler.Filename, os.O_WRONLY|os.O_CREATE, 0666)
if err != nil {
return nil, err
}
defer f.Close()
io.Copy(f, file)
profile.Info["filename"] = handler.Filename
}
for key := range r.Form { // save form values
if key == "password" {
profile.Password = r.FormValue(key)
} else {
profile.Info[key] = r.FormValue(key)
}
}
return profile, nil
}
func getJSON(r *http.Request, result interface{}) error {
defer r.Body.Close()
body, err := ioutil.ReadAll(r.Body)
if err != nil {
return err
}
return json.Unmarshal(body, result)
}
func isValidEmail(email string) bool {
return len(email) <= 254 && len(email) >= 6 && emailRegex.MatchString(email) == true
}
func substringAfter(source, find string) string {
fromIndex := strings.Index(source, find)
if fromIndex == -1 {
return source
}
fromIndex += len(find)
return source[fromIndex:]
}