/
auth.go
1646 lines (1320 loc) · 41.4 KB
/
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
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
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package service
import (
"context"
"fmt"
"math"
rand2 "math/rand"
"regexp"
"strconv"
"time"
"github.com/cortezaproject/corteza-server/pkg/actionlog"
internalAuth "github.com/cortezaproject/corteza-server/pkg/auth"
"github.com/cortezaproject/corteza-server/pkg/errors"
"github.com/cortezaproject/corteza-server/pkg/eventbus"
"github.com/cortezaproject/corteza-server/pkg/filter"
"github.com/cortezaproject/corteza-server/pkg/handle"
"github.com/cortezaproject/corteza-server/pkg/payload"
"github.com/cortezaproject/corteza-server/pkg/rand"
"github.com/cortezaproject/corteza-server/store"
"github.com/cortezaproject/corteza-server/system/service/event"
"github.com/cortezaproject/corteza-server/system/types"
"github.com/dgryski/dgoogauth"
"github.com/markbates/goth"
"golang.org/x/crypto/bcrypt"
)
type (
auth struct {
actionlog actionlog.Recorder
ac authAccessController
eventbus eventDispatcher
store store.Storer
settings *types.AppSettings
notifications AuthNotificationService
opt AuthOptions
providerValidator func(string) error
}
AuthOptions struct {
LimitUsers int
}
authAccessController interface {
CanImpersonateUser(context.Context, *types.User) bool
CanUpdateUser(context.Context, *types.User) bool
}
)
const (
credentialsTypePassword = "password"
credentialsTypePersistentSession = "persistent-session"
credentialsTypeEmailAuthToken = "email-authentication-token"
credentialsTypeResetPasswordToken = "password-reset-token"
credentialsTypeResetPasswordTokenExchanged = "password-reset-token-exchanged"
credentialsTypeCreatePasswordToken = "password-create-token"
credentialsTypeMfaTotpSecret = "mfa-totp-secret"
credentialsTypeMFAEmailOTP = "mfa-email-otp"
credentialsTokenLength = 32
passwordMinLength = 8
passwordMaxLength = 256
tokenReqMaxCount = 5
tokenReqMaxWindow = time.Minute * 15
)
var (
reEmail = regexp.MustCompile("^[a-zA-Z0-9.!#$%&'*+\\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$")
oneTokenPerUser = map[string]bool{
credentialsTypeResetPasswordToken: true,
}
)
func defaultProviderValidator(provider string) error {
switch provider {
case "saml":
return nil
default:
_, err := goth.GetProvider(provider)
return err
}
}
func Auth(opt AuthOptions) *auth {
return &auth{
eventbus: eventbus.Service(),
ac: DefaultAccessControl,
settings: CurrentSettings,
notifications: DefaultAuthNotification,
actionlog: DefaultActionlog,
store: DefaultStore,
providerValidator: defaultProviderValidator,
opt: opt,
}
}
// External func performs login/signup procedures
//
// We fully trust external auth sources (see system/auth/external) to provide a valid & validates
// profile (goth.User) that we use for user discovery and/or creation
//
// Flow
// 1. check for existing credentials using profile provider & provider's user ID
// 1.1. find existing local -or- "shadow" user
// 1.2. if user exists and is valid, update credentials (last-used-at) and complete the procedure
//
// 2. check for existing users using email from the profile
// 2.1. validate existing user -or-
// 2.2. create user on-the-fly if it does not exist
// 2.3. create credentials for that social login
//
// External login/signup does not:
// - validate provider on profile, only uses it for matching credentials
func (svc auth) External(ctx context.Context, profile types.ExternalAuthUser) (u *types.User, err error) {
var (
authProvider = &types.AuthProvider{Provider: profile.Provider}
aam = &authActionProps{
email: profile.Email,
provider: profile.Provider,
user: u,
}
)
err = func() (err error) {
if !svc.settings.Auth.External.Enabled {
return AuthErrExternalDisabledByConfig(aam)
}
if err = svc.providerValidator(profile.Provider); err != nil {
return err
}
if !reEmail.MatchString(profile.Email) {
return AuthErrProfileWithoutValidEmail(aam)
}
var (
cc types.CredentialsSet
f = types.CredentialsFilter{Kind: profile.Provider, Credentials: profile.UserID}
)
if cc, _, err = store.SearchCredentials(ctx, svc.store, f); err == nil {
// Credentials found, load user
for _, c := range cc {
if !c.Valid() {
continue
}
// Add credentials ID for audit log
aam.setCredentials(c)
if u, err = store.LookupUserByID(ctx, svc.store, c.OwnerID); err != nil {
if errors.IsNotFound(err) {
// Orphaned credentials (no owner)
// try to auto-fix this by removing credentials and recreating user
if err = store.DeleteCredentialsByID(ctx, svc.store, c.ID); err != nil {
return
} else {
goto findByEmail
}
}
return
}
aam.setUser(u)
ctx = internalAuth.SetIdentityToContext(ctx, u)
if err = svc.procLogin(ctx, svc.store, u, c, authProvider); err != nil {
// Scenario: linked to an invalid user
if len(cc) > 1 {
// try with next credentials
u = nil
continue
}
return AuthErrCredentialsLinkedToInvalidUser(aam)
}
// Assuming we can trust that email has been verified by the provider
if !u.EmailConfirmed {
u.EmailConfirmed = true
if err = store.UpdateUser(ctx, svc.store, u); err != nil {
return
}
}
return svc.recordAction(ctx, aam, AuthActionUpdateCredentials, nil)
}
// If we could not find anything useful,
// we can search for user via email
// (using goto for consistency)
goto findByEmail
} else {
// A serious error occurred, bail out...
return
}
findByEmail:
// Reset audit meta data that might got set during credentials check
aam.setEmail(profile.Email).
setCredentials(nil).
setUser(nil)
// Find user via his email
if u, err = store.LookupUserByEmail(ctx, svc.store, profile.Email); errors.IsNotFound(err) {
// @todo check if it is ok to auto-create a user here
// In case we do not have this email, create a new user
u = &types.User{
Email: profile.Email,
Name: profile.Name,
Username: profile.NickName,
EmailConfirmed: true,
}
if !handle.IsValid(profile.NickName) {
u.Handle = profile.NickName
}
if err = svc.eventbus.WaitFor(ctx, event.AuthBeforeSignup(u, authProvider)); err != nil {
return err
}
if u.Handle == "" {
createUserHandle(ctx, svc.store, u)
}
if err = uniqueUserCheck(ctx, svc.store, u); err != nil {
return err
}
if err = svc.checkLimits(ctx); err != nil {
return err
}
u.ID = nextID()
u.CreatedAt = *now()
if err = store.CreateUser(ctx, svc.store, u); err != nil {
return err
}
aam.setUser(u)
ctx = internalAuth.SetIdentityToContext(ctx, u)
_ = svc.eventbus.WaitFor(ctx, event.AuthAfterSignup(u, authProvider))
if err = svc.recordAction(ctx, aam, AuthActionExternalSignup, nil); err != nil {
return err
}
// Auto-promote first user
if err = svc.autoPromote(ctx, u); err != nil {
return err
}
} else if err != nil {
return err
} else {
// User found
aam.setUser(u)
ctx = internalAuth.SetIdentityToContext(ctx, u)
if err = svc.procLogin(ctx, svc.store, u, nil, authProvider); err != nil {
return err
}
}
// If we got to this point, assume that user is authenticated
// but credentials need to be stored
c := &types.Credentials{
ID: nextID(),
CreatedAt: *now(),
Kind: profile.Provider,
OwnerID: u.ID,
Credentials: profile.UserID,
LastUsedAt: now(),
}
if err = store.CreateCredentials(ctx, svc.store, c); err != nil {
return err
}
aam.setCredentials(c)
svc.recordAction(ctx, aam, AuthActionCreateCredentials, nil)
// Assuming we can trust that email has been verified by the provider
if !u.EmailConfirmed {
u.EmailConfirmed = true
if err = store.UpdateUser(ctx, svc.store, u); err != nil {
return
}
}
return nil
}()
return u, svc.recordAction(ctx, aam, AuthActionAuthenticate, err)
}
// InternalSignUp protocol
//
// Forgiving but strict: valid existing users get notified
//
// We're accepting the whole user object here and copy all we need to the new user
func (svc auth) InternalSignUp(ctx context.Context, input *types.User, password string) (u *types.User, err error) {
var (
authProvider = &types.AuthProvider{Provider: credentialsTypePassword}
aam = &authActionProps{
email: input.Email,
credentials: &types.Credentials{Kind: credentialsTypePassword},
}
)
err = func() error {
if !svc.settings.Auth.Internal.Enabled || !svc.settings.Auth.Internal.Signup.Enabled {
return AuthErrInternalSignupDisabledByConfig(aam)
}
if input == nil || !reEmail.MatchString(input.Email) {
return AuthErrInvalidEmailFormat(aam)
}
if !handle.IsValid(input.Handle) {
return AuthErrInvalidHandle(aam)
}
if len(password) == 0 {
return AuthErrPasswordNotSecure(aam)
}
var eUser *types.User
eUser, err = store.LookupUserByEmail(ctx, svc.store, input.Email)
if err == nil && eUser != nil {
var (
c *types.Credentials
cc types.CredentialsSet
f = types.CredentialsFilter{OwnerID: eUser.ID, Kind: credentialsTypePassword}
)
if cc, _, err = store.SearchCredentials(ctx, svc.store, f); err != nil {
return err
}
if c = cc.CompareHashAndPassword(password); c == nil {
return AuthErrInvalidCredentials(aam)
}
aam.setCredentials(c)
u = eUser
ctx = internalAuth.SetIdentityToContext(ctx, u)
return svc.procLogin(ctx, svc.store, eUser, c, authProvider)
} else if !errors.IsNotFound(err) {
return err
}
// if !svc.settings.internalSignUpSendEmailOnExisting {
// return nil,errors.Wrap(err, "user with this email already exists")
// }
// User already exists, but we're nice and we'll send this user an
// email that will help him to login
// if !u.Valid() {
// return nil,errors.New("could not validate the user")
// }
//
// return nil,nil
var nUser = &types.User{
ID: nextID(),
CreatedAt: *now(),
Email: input.Email,
Name: input.Name,
Username: input.Username,
Handle: input.Handle,
// Do we need confirmed email?
EmailConfirmed: !svc.settings.Auth.Internal.Signup.EmailConfirmationRequired,
}
if err = svc.eventbus.WaitFor(ctx, event.AuthBeforeSignup(nUser, authProvider)); err != nil {
return err
}
if nUser.Handle == "" {
createUserHandle(ctx, svc.store, nUser)
}
if err = uniqueUserCheck(ctx, svc.store, nUser); err != nil {
return err
}
if err = svc.checkLimits(ctx); err != nil {
return err
}
// Whitelisted user data to copy
err = store.CreateUser(ctx, svc.store, nUser)
if err != nil {
return err
}
aam.setUser(nUser)
_ = svc.eventbus.WaitFor(ctx, event.AuthAfterSignup(nUser, authProvider))
if err = svc.autoPromote(ctx, nUser); err != nil {
return err
}
if err = svc.LoadRoleMemberships(ctx, nUser); err != nil {
return err
}
if len(password) > 0 {
err = svc.SetPassword(ctx, nUser.ID, password)
if err != nil {
return err
}
}
u = nUser
if !nUser.EmailConfirmed {
err = svc.SendEmailAddressConfirmationToken(ctx, nUser)
if err != nil {
return err
}
return svc.recordAction(ctx, aam, AuthActionSendEmailConfirmationToken, nil)
}
return nil
}()
return u, svc.recordAction(ctx, aam, AuthActionInternalSignup, err)
}
// InternalLogin verifies username/password combination in the internal credentials table
//
// Expects plain text password as an input
func (svc auth) InternalLogin(ctx context.Context, email string, password string) (u *types.User, err error) {
var (
authProvider = &types.AuthProvider{Provider: credentialsTypePassword}
aam = &authActionProps{
email: email,
credentials: &types.Credentials{Kind: credentialsTypePassword},
user: u,
}
)
err = func() error {
if !svc.settings.Auth.Internal.Enabled {
return AuthErrInternalLoginDisabledByConfig()
}
if !reEmail.MatchString(email) {
return AuthErrInvalidEmailFormat()
}
if len(password) == 0 {
return AuthErrInvalidCredentials()
}
var (
cc types.CredentialsSet
)
u, err = store.LookupUserByEmail(ctx, svc.store, email)
if errors.IsNotFound(err) {
return AuthErrInvalidCredentials(aam)
} else if err != nil {
return err
}
// Update audit meta with found user
ctx = internalAuth.SetIdentityToContext(ctx, u)
cc, _, err = store.SearchCredentials(ctx, svc.store, types.CredentialsFilter{OwnerID: u.ID, Kind: credentialsTypePassword})
if err != nil {
return err
}
c := cc.CompareHashAndPassword(password)
if c == nil {
return AuthErrInvalidCredentials(aam)
}
aam.setCredentials(c)
ctx = internalAuth.SetIdentityToContext(ctx, u)
return svc.procLogin(ctx, svc.store, u, c, authProvider)
}()
return u, svc.recordAction(ctx, aam, AuthActionAuthenticate, err)
}
// checkPassword returns true if given (encrypted) password matches any of the credentials
func (svc auth) checkPassword(password string, cc types.CredentialsSet) bool {
return cc.CompareHashAndPassword(password) != nil
}
// SetPassword sets new password for a user
//
// This function also records an action
func (svc auth) SetPassword(ctx context.Context, userID uint64, password string) (err error) {
var (
u *types.User
aam = &authActionProps{
user: u,
credentials: &types.Credentials{Kind: credentialsTypePassword},
}
)
err = func() error {
if !svc.settings.Auth.Internal.Enabled {
return AuthErrInternalLoginDisabledByConfig(aam)
}
if !svc.CheckPasswordStrength(password) {
return AuthErrPasswordNotSecure(aam)
}
u, err = store.LookupUserByID(ctx, svc.store, userID)
if errors.IsNotFound(err) {
return AuthErrPasswordChangeFailedForUnknownUser(aam)
}
aam.setUser(u)
ctx = internalAuth.SetIdentityToContext(ctx, u)
if err != svc.SetPasswordCredentials(ctx, userID, password) {
return err
}
return nil
}()
return svc.recordAction(ctx, aam, AuthActionChangePassword, err)
}
// Impersonate verifies if user can impersonate another user and returns that user
//
// For now, it's the caller's responsibility to generate the auth token
func (svc auth) Impersonate(ctx context.Context, userID uint64) (u *types.User, err error) {
var (
aam = &authActionProps{user: u}
)
err = func() error {
if u, err = store.LookupUserByID(ctx, svc.store, userID); err != nil {
return err
}
if !svc.ac.CanImpersonateUser(ctx, u) {
return AuthErrNotAllowedToImpersonate()
}
return err
}()
return u, svc.recordAction(ctx, aam, AuthActionImpersonate, err)
}
// ChangePassword validates old password and changes it with new
func (svc auth) ChangePassword(ctx context.Context, userID uint64, oldPassword, newPassword string) (err error) {
var (
u *types.User
cc types.CredentialsSet
aam = &authActionProps{
user: u,
credentials: &types.Credentials{Kind: credentialsTypePassword},
}
)
err = func() error {
if !svc.settings.Auth.Internal.Enabled {
return AuthErrInternalLoginDisabledByConfig(aam)
}
if len(oldPassword) == 0 {
return AuthErrPasswordNotSecure(aam)
}
if !svc.CheckPasswordStrength(newPassword) {
return AuthErrPasswordNotSecure(aam)
}
u, err = store.LookupUserByID(ctx, svc.store, userID)
if errors.IsNotFound(err) {
return AuthErrPasswordChangeFailedForUnknownUser(aam)
}
aam.setUser(u)
ctx = internalAuth.SetIdentityToContext(ctx, u)
cc, _, err = store.SearchCredentials(ctx, svc.store, types.CredentialsFilter{Kind: credentialsTypePassword, OwnerID: userID})
if err != nil {
return err
}
if !svc.checkPassword(oldPassword, cc) {
return AuthErrPasswodResetFailedOldPasswordCheckFailed(aam)
}
if err != svc.SetPasswordCredentials(ctx, userID, newPassword) {
return err
}
if err = svc.RemoveAccessTokens(ctx, u); err != nil {
return err
}
return nil
}()
return svc.recordAction(ctx, aam, AuthActionChangePassword, err)
}
func (svc auth) hashPassword(password string) (hash []byte, err error) {
return bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
}
func (svc auth) CheckPasswordStrength(password string) bool {
pwdL := len(password)
// Ignore defined password constraints
if !svc.settings.Auth.Internal.PasswordConstraints.PasswordSecurity {
return true
}
// Check the password length
minL := math.Max(float64(passwordMinLength), float64(svc.settings.Auth.Internal.PasswordConstraints.MinLength))
if pwdL < int(minL) || pwdL > passwordMaxLength {
return false
}
// Check special constraints
// - numeric characters
count := svc.settings.Auth.Internal.PasswordConstraints.MinNumCount
if count > 0 {
rr := regexp.MustCompile("[0-9]")
if uint(len(rr.FindAllStringIndex(password, -1))) < count {
return false
}
}
// - special characters
count = svc.settings.Auth.Internal.PasswordConstraints.MinSpecialCount
if count > 0 {
rr := regexp.MustCompile("[^0-9a-zA-Z]")
if uint(len(rr.FindAllStringIndex(password, -1))) < count {
return false
}
}
return true
}
// SetPasswordCredentials (soft) deletes old password entry and creates a new entry with new password on every change
//
// This way we can implement more strict password-change policies in the future
//
// This method is used by auth and user procedures to unify password hashing and updating
// credentials
func (svc auth) SetPasswordCredentials(ctx context.Context, userID uint64, password string) (err error) {
var (
hash []byte
)
if hash, err = svc.hashPassword(password); err != nil {
return
}
if err = svc.removePasswordCredentials(ctx, userID); err != nil {
return
}
// Add new credentials with new password
c := &types.Credentials{
ID: nextID(),
CreatedAt: *now(),
OwnerID: userID,
Kind: credentialsTypePassword,
Credentials: string(hash),
}
return store.CreateCredentials(ctx, svc.store, c)
}
// RemovePasswordCredentials (soft) deletes old password entry
func (svc auth) RemovePasswordCredentials(ctx context.Context, userID uint64) (err error) {
// Do a partial update and soft-delete all
return svc.removePasswordCredentials(ctx, userID)
}
// RemovePasswordCredentials (soft) deletes old password entry
func (svc auth) removePasswordCredentials(ctx context.Context, userID uint64) (err error) {
var (
cc types.CredentialsSet
f = types.CredentialsFilter{Kind: credentialsTypePassword, OwnerID: userID}
)
if cc, _, err = store.SearchCredentials(ctx, svc.store, f); err != nil {
return nil
}
// Mark all credentials as deleted
_ = cc.Walk(func(c *types.Credentials) error {
c.DeletedAt = now()
return nil
})
// Do a partial update and soft-delete all
return store.UpdateCredentials(ctx, svc.store, cc...)
}
// ValidateEmailConfirmationToken issues a validation token that can be used for
func (svc auth) ValidateEmailConfirmationToken(ctx context.Context, token string) (user *types.User, err error) {
return svc.loadFromTokenAndConfirmEmail(ctx, token, credentialsTypeEmailAuthToken)
}
// ValidatePasswordResetToken validates password reset token
func (svc auth) ValidatePasswordResetToken(ctx context.Context, token string) (user *types.User, err error) {
return svc.loadFromTokenAndConfirmEmail(ctx, token, credentialsTypeResetPasswordToken)
}
// ValidatePasswordCreateToken validates password create token
func (svc auth) ValidatePasswordCreateToken(ctx context.Context, token string) (user *types.User, err error) {
return svc.loadFromTokenAndConfirmEmail(ctx, token, credentialsTypeCreatePasswordToken)
}
// PasswordSet checks and returns true if user's password is set
// False is also returned in case user does not exist.
func (svc *auth) PasswordSet(ctx context.Context, email string) (is bool) {
//svc.settings.Auth.External.Enabled
u, err := store.LookupUserByEmail(ctx, svc.store, email)
if err != nil {
return
}
cc, _, err := store.SearchCredentials(ctx, svc.store, types.CredentialsFilter{
OwnerID: u.ID,
Kind: credentialsTypePassword,
})
if err != nil {
return
}
if len(cc) > 0 && svc.settings.Auth.Internal.Enabled {
return true
}
return
}
// loadFromTokenAndConfirmEmail loads token, confirms user's
func (svc auth) loadFromTokenAndConfirmEmail(ctx context.Context, token, tokenType string) (u *types.User, err error) {
var (
aam = &authActionProps{
user: u,
credentials: &types.Credentials{Kind: tokenType},
}
)
err = func() error {
if !svc.settings.Auth.Internal.Enabled {
return AuthErrInternalSignupDisabledByConfig(aam)
}
u, err = svc.loadUserFromToken(ctx, token, tokenType)
if err != nil {
return err
}
aam.setUser(u)
ctx = internalAuth.SetIdentityToContext(ctx, u)
if !u.EmailConfirmed {
// User's email is not confirmed but going through password reset flow
// we can confirm it
u.EmailConfirmed = true
u.UpdatedAt = now()
if err = store.UpdateUser(ctx, svc.store, u); err != nil {
return err
}
}
if err = svc.LoadRoleMemberships(ctx, u); err != nil {
return err
}
return nil
}()
return u, svc.recordAction(ctx, aam, AuthActionConfirmEmail, err)
}
// ExchangePasswordResetToken exchanges reset password token for a new one and returns it with user info
func (svc auth) ExchangePasswordResetToken(ctx context.Context, token string) (u *types.User, t string, err error) {
var (
aam = &authActionProps{
user: u,
credentials: &types.Credentials{Kind: credentialsTypeResetPasswordToken},
}
)
err = func() error {
if !svc.settings.Auth.Internal.Enabled || !svc.settings.Auth.Internal.PasswordReset.Enabled {
return AuthErrPasswordResetDisabledByConfig(aam)
}
u, err = svc.loadUserFromToken(ctx, token, credentialsTypeResetPasswordToken)
if err != nil {
return AuthErrInvalidToken(aam).Wrap(err)
}
aam.setUser(u)
ctx = internalAuth.SetIdentityToContext(ctx, u)
t, err = svc.createUserToken(ctx, u, credentialsTypeResetPasswordTokenExchanged)
if err != nil {
u = nil
t = ""
return AuthErrInvalidToken(aam).Wrap(err)
}
return nil
}()
return u, t, svc.recordAction(ctx, aam, AuthActionExchangePasswordResetToken, err)
}
func (svc auth) SendEmailAddressConfirmationToken(ctx context.Context, u *types.User) (err error) {
var (
token string
aam = &authActionProps{
user: u,
credentials: &types.Credentials{Kind: credentialsTypeEmailAuthToken},
}
)
if token, err = svc.createUserToken(ctx, u, credentialsTypeEmailAuthToken); err != nil {
return
}
if err = svc.notifications.EmailConfirmation(ctx, u.Email, token); err != nil {
return
}
return svc.recordAction(ctx, aam, AuthActionSendEmailConfirmationToken, err)
}
// SendPasswordResetToken sends password reset token to email
func (svc auth) SendPasswordResetToken(ctx context.Context, email string) (err error) {
var (
u *types.User
aam = &authActionProps{
user: u,
email: email,
}
)
err = func() error {
if !svc.settings.Auth.Internal.Enabled || !svc.settings.Auth.Internal.PasswordReset.Enabled {
return AuthErrPasswordResetDisabledByConfig(aam)
}
if u, err = store.LookupUserByEmail(ctx, svc.store, email); err != nil {
return err
}
ctx = internalAuth.SetIdentityToContext(ctx, u)
if err = svc.sendPasswordResetToken(ctx, u); err != nil {
return err
}
return nil
}()
return svc.recordAction(ctx, aam, AuthActionSendPasswordResetToken, err)
}
func (svc auth) sendPasswordResetToken(ctx context.Context, u *types.User) (err error) {
token, err := svc.createUserToken(ctx, u, credentialsTypeResetPasswordToken)
if err != nil {
return err
}
return svc.notifications.PasswordReset(ctx, u.Email, token)
}
// GeneratePasswordCreateToken generates password create token
func (svc auth) GeneratePasswordCreateToken(ctx context.Context, email string) (url string, err error) {
var (
u *types.User
aam = &authActionProps{
user: u,
email: email,
}
)
err = func() error {
if !svc.settings.Auth.Internal.Enabled || !svc.settings.Auth.Internal.PasswordCreate.Enabled {
return AuthErrPasswordCreateDisabledByConfig(aam)
}
if u, err = store.LookupUserByEmail(ctx, svc.store, email); err != nil {
return err
}
ctx = internalAuth.SetIdentityToContext(ctx, u)
if url, err = svc.sendPasswordCreateToken(ctx, u); err != nil {
return err
}
return nil
}()
return url, svc.recordAction(ctx, aam, AuthActionGeneratePasswordCreateToken, err)
}
func (svc auth) sendPasswordCreateToken(ctx context.Context, u *types.User) (url string, err error) {
token, err := svc.createUserToken(ctx, u, credentialsTypeCreatePasswordToken)
if err != nil {
return
}
return svc.notifications.PasswordCreate(token)
}
// procLogin fn performs standard validation, credentials-update tasks and triggers events
func (svc auth) procLogin(ctx context.Context, s store.Storer, u *types.User, c *types.Credentials, p *types.AuthProvider) (err error) {
if err = svc.eventbus.WaitFor(ctx, event.AuthBeforeLogin(u, p)); err != nil {
return err
}
// all checks (suspension, deleted, confirmed email) are checked AFTER
// before-login event to enable before-login hooks to alter user and make her
// valid for login
switch true {
case u.SuspendedAt != nil:
return AuthErrFailedForSuspendedUser()
case u.DeletedAt != nil:
return AuthErrFailedForDeletedUser()
case u.Kind == types.SystemUser:
return AuthErrFailedForSystemUser()
}
if err = svc.LoadRoleMemberships(ctx, u); err != nil {
return
}
{
var eapSec *types.ExternalAuthProviderSecurity
switch p.Provider {
case credentialsTypePassword:
// nothing to do with password provider
case "saml":
// we need to fetch SAML security settings from different part of settings
eapSec = &CurrentSettings.Auth.External.Saml.Security
default:
eap := CurrentSettings.Auth.External.Providers.FindByHandle(p.Provider)
if eap != nil {
eapSec = &eap.Security
}
}
if eapSec != nil {
// if authenticated with external auth provider
// there might be additional roles that need to be
// set to this security session
u.SetRoles(internalAuth.ApplyRoleSecurity(
payload.ParseUint64s(eapSec.PermittedRoles),
payload.ParseUint64s(eapSec.ProhibitedRoles),
payload.ParseUint64s(eapSec.ForcedRoles),