/
user.go
2481 lines (2156 loc) · 67.7 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
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
// Copyright (c) 2017-2019 The Fonero developers
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.
package main
import (
"bytes"
"encoding/hex"
"fmt"
"os"
"regexp"
"sort"
"strconv"
"strings"
"time"
"github.com/btcsuite/golangcrypto/bcrypt"
"github.com/fonero-project/politeia/politeiad/api/v1/identity"
cms "github.com/fonero-project/politeia/politeiawww/api/cms/v1"
www "github.com/fonero-project/politeia/politeiawww/api/www/v1"
"github.com/fonero-project/politeia/politeiawww/user"
"github.com/fonero-project/politeia/util"
"github.com/google/uuid"
)
const (
LoginAttemptsToLockUser = 5
// Route to reset password at GUI
ResetPasswordGuiRoute = "/password" // XXX what is this doing here?
emailRegex = `^[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])?)*$"
)
var (
validUsername = regexp.MustCompile(createUsernameRegex())
validEmail = regexp.MustCompile(emailRegex)
// MinimumLoginWaitTime is the minimum amount of time to wait before the
// server sends a response to the client for the login route. This is done
// to prevent an attacker from executing a timing attack to determine whether
// the ErrorStatusInvalidEmailOrPassword response is specific to a bad email
// or bad password.
MinimumLoginWaitTime = 500 * time.Millisecond
)
type loginReplyWithError struct {
reply *www.LoginReply
err error
}
// createUsernameRegex generates a regex based on the policy supplied valid
// characters in a user name.
func createUsernameRegex() string {
var buf bytes.Buffer
buf.WriteString("^[")
for _, supportedChar := range www.PolicyUsernameSupportedChars {
if len(supportedChar) > 1 {
buf.WriteString(supportedChar)
} else {
buf.WriteString(`\` + supportedChar)
}
}
buf.WriteString("]{")
buf.WriteString(strconv.Itoa(www.PolicyMinUsernameLength) + ",")
buf.WriteString(strconv.Itoa(www.PolicyMaxUsernameLength) + "}$")
return buf.String()
}
// convertWWWUserFromDatabaseUser converts a user User to a www User.
func convertWWWUserFromDatabaseUser(user *user.User) www.User {
return www.User{
ID: user.ID.String(),
Admin: user.Admin,
Email: user.Email,
Username: user.Username,
NewUserPaywallAddress: user.NewUserPaywallAddress,
NewUserPaywallAmount: user.NewUserPaywallAmount,
NewUserPaywallTx: user.NewUserPaywallTx,
NewUserPaywallTxNotBefore: user.NewUserPaywallTxNotBefore,
NewUserPaywallPollExpiry: user.NewUserPaywallPollExpiry,
NewUserVerificationToken: user.NewUserVerificationToken,
NewUserVerificationExpiry: user.NewUserVerificationExpiry,
UpdateKeyVerificationToken: user.UpdateKeyVerificationToken,
UpdateKeyVerificationExpiry: user.UpdateKeyVerificationExpiry,
ResetPasswordVerificationToken: user.ResetPasswordVerificationToken,
ResetPasswordVerificationExpiry: user.ResetPasswordVerificationExpiry,
LastLoginTime: user.LastLoginTime,
FailedLoginAttempts: user.FailedLoginAttempts,
Deactivated: user.Deactivated,
Locked: checkUserIsLocked(user.FailedLoginAttempts),
Identities: convertWWWIdentitiesFromDatabaseIdentities(user.Identities),
ProposalCredits: ProposalCreditBalance(user),
EmailNotifications: user.EmailNotifications,
}
}
// convertWWWIdentitiesFromDatabaseIdentities converts a user Identity to a www
// Identity.
func convertWWWIdentitiesFromDatabaseIdentities(identities []user.Identity) []www.UserIdentity {
userIdentities := make([]www.UserIdentity, 0, len(identities))
for _, v := range identities {
userIdentities = append(userIdentities,
convertWWWIdentityFromDatabaseIdentity(v))
}
return userIdentities
}
// convertWWWIdentityFromDatabaseIdentity converts a user Identity to a www
// Identity.
func convertWWWIdentityFromDatabaseIdentity(id user.Identity) www.UserIdentity {
return www.UserIdentity{
Pubkey: id.String(),
Active: id.IsActive(),
}
}
// filterUserPublicFields creates a filtered copy of a www User that only
// contains public information.
func filterUserPublicFields(user www.User) www.User {
return www.User{
ID: user.ID,
Admin: user.Admin,
Username: user.Username,
Identities: user.Identities,
}
}
// formatUsername normalizes a username to lowercase without leading and
// trailing spaces.
func formatUsername(username string) string {
return strings.ToLower(strings.TrimSpace(username))
}
// validateUsername verifies that a username adheres to required policy.
func validateUsername(username string) error {
if username != formatUsername(username) {
log.Tracef("validateUsername: not normalized: %s %s",
username, formatUsername(username))
return www.UserError{
ErrorCode: www.ErrorStatusMalformedUsername,
}
}
if len(username) < www.PolicyMinUsernameLength ||
len(username) > www.PolicyMaxUsernameLength {
log.Tracef("validateUsername: not within bounds: %s",
username)
return www.UserError{
ErrorCode: www.ErrorStatusMalformedUsername,
}
}
if !validUsername.MatchString(username) {
log.Tracef("validateUsername: not valid: %s %s",
username, validUsername.String())
return www.UserError{
ErrorCode: www.ErrorStatusMalformedUsername,
}
}
return nil
}
// validatePassword verifies that a password adheres to required policy.
func validatePassword(password string) error {
if len(password) < www.PolicyMinPasswordLength {
return www.UserError{
ErrorCode: www.ErrorStatusMalformedPassword,
}
}
return nil
}
// validatePassword verifies that a pubkey is valid and not set to all zeros.
func validatePubkey(publicKey string) ([]byte, error) {
pk, err := hex.DecodeString(publicKey)
if err != nil {
log.Debugf("validatePubkey: decode hex string "+
"failed for '%v': %v", publicKey, err)
return nil, www.UserError{
ErrorCode: www.ErrorStatusInvalidPublicKey,
}
}
var emptyPK [identity.PublicKeySize]byte
switch {
case len(pk) != len(emptyPK):
log.Debugf("validatePubkey: invalid size: %v",
publicKey)
return nil, www.UserError{
ErrorCode: www.ErrorStatusInvalidPublicKey,
}
case bytes.Equal(pk, emptyPK[:]):
log.Debugf("validatePubkey: pubkey is empty: %v",
publicKey)
return nil, www.UserError{
ErrorCode: www.ErrorStatusInvalidPublicKey,
}
}
return pk, nil
}
// checkPublicKeyAndSignature validates the public key and signature.
func checkPublicKeyAndSignature(u *user.User, publicKey string, signature string, elements ...string) error {
id, err := checkPublicKey(u, publicKey)
if err != nil {
return err
}
return checkSignature(id, signature, elements...)
}
// checkPublicKey compares the supplied public key against the one stored in
// the user database. It will return the active identity if there are no
// errors.
func checkPublicKey(u *user.User, pk string) ([]byte, error) {
if u.PublicKey() != pk {
return nil, www.UserError{
ErrorCode: www.ErrorStatusInvalidSigningKey,
}
}
return u.ActiveIdentity().Key[:], nil
}
// initUserPubkeys initializes the userPubkeys map with all the pubkey-userid
// associations that are found in the database.
//
// This function must be called WITHOUT the lock held.
func (p *politeiawww) initUserPubkeys() error {
p.Lock()
defer p.Unlock()
return p.db.AllUsers(func(u *user.User) {
userId := u.ID.String()
for _, v := range u.Identities {
key := hex.EncodeToString(v.Key[:])
p.userPubkeys[key] = userId
}
})
}
// setUserPubkeyAssociaton associates a public key with a user id in
// the userPubkeys cache.
//
// This function must be called WITHOUT the lock held.
func (p *politeiawww) setUserPubkeyAssociaton(u *user.User, publicKey string) {
p.Lock()
defer p.Unlock()
p.userPubkeys[publicKey] = u.ID.String()
}
// removeUserPubkeyAssociaton removes a public key from the
// userPubkeys cache.
//
// This function must be called WITHOUT the lock held.
func (p *politeiawww) removeUserPubkeyAssociaton(u *user.User, publicKey string) {
p.Lock()
defer p.Unlock()
delete(p.userPubkeys, publicKey)
}
// initUserEmails initializes the userEmails cache by iterating through all the
// users in the database and adding a email-userID mapping for them.
//
// This function must be called WITHOUT the lock held.
func (p *politeiawww) initUserEmails() error {
p.Lock()
defer p.Unlock()
return p.db.AllUsers(func(u *user.User) {
p.userEmails[u.Email] = u.ID
})
}
// setUserEmails sets a email-userID mapping in the user emails cache.
//
// This function must be called WITHOUT the lock held.
func (p *politeiawww) setUserEmails(email string, id uuid.UUID) {
p.Lock()
defer p.Unlock()
p.userEmails[email] = id
}
// userIDByEmail returns a userID given their email address.
//
// This function must be called WITHOUT the lock held.
func (p *politeiawww) userIDByEmail(email string) (uuid.UUID, bool) {
p.RLock()
defer p.RUnlock()
id, ok := p.userEmails[email]
return id, ok
}
// userByEmail returns a User object given their email address.
//
// This function must be called WITHOUT the lock held.
func (p *politeiawww) userByEmail(email string) (*user.User, error) {
id, ok := p.userIDByEmail(email)
if !ok {
log.Debugf("userByEmail: email lookup failed for '%v'", email)
return nil, user.ErrUserNotFound
}
return p.db.UserGetById(id)
}
// checkSignature validates an incoming signature against the specified user's
// pubkey.
func checkSignature(id []byte, signature string, elements ...string) error {
sig, err := util.ConvertSignature(signature)
if err != nil {
return www.UserError{
ErrorCode: www.ErrorStatusInvalidSignature,
}
}
pk, err := identity.PublicIdentityFromBytes(id[:])
if err != nil {
return err
}
var msg string
for _, v := range elements {
msg += v
}
if !pk.VerifyMessage([]byte(msg), sig) {
return www.UserError{
ErrorCode: www.ErrorStatusInvalidSignature,
}
}
return nil
}
// generateVerificationTokenAndExpiry creates a new verification token that
// expires in www.VerificationExpiryHours hours.
func generateVerificationTokenAndExpiry() ([]byte, int64, error) {
token, err := util.Random(www.VerificationTokenSize)
if err != nil {
return nil, 0, err
}
duration := time.Duration(www.VerificationExpiryHours) * time.Hour
expiry := time.Now().Add(duration).Unix()
return token, expiry, nil
}
// checkUserIsLocked checks if a user is locked after too many login attempts
func checkUserIsLocked(failedLoginAttempts uint64) bool {
return failedLoginAttempts >= LoginAttemptsToLockUser
}
// setNewUserVerificationAndIdentity adds an identity to a user.
func setNewUserVerificationAndIdentity(u *user.User, token []byte, expiry int64, includeResend bool, pk []byte) {
u.NewUserVerificationToken = token
u.NewUserVerificationExpiry = expiry
if includeResend {
// This field is used to support requesting another
// registration email quickly, without having to wait the full
// email-spam-prevention period.
u.ResendNewUserVerificationExpiry = expiry
}
u.Identities = []user.Identity{{
Activated: time.Now().Unix(),
}}
copy(u.Identities[0].Key[:], pk)
}
// hashPassword hashes the given password string with the default bcrypt cost
// or the minimum cost if the test flag is set to speed up running tests.
func (p *politeiawww) hashPassword(password string) ([]byte, error) {
if p.test {
return bcrypt.GenerateFromPassword([]byte(password),
bcrypt.MinCost)
}
return bcrypt.GenerateFromPassword([]byte(password),
bcrypt.DefaultCost)
}
// getUserIDByPubKey return uuid that corresponds to the provided public key.
func (p *politeiawww) getUserIDByPubKey(pubkey string) (string, bool) {
p.RLock()
defer p.RUnlock()
userID, ok := p.userPubkeys[pubkey]
return userID, ok
}
// getUserByIDStr converts userIDStr to a uuid and returns the corresponding
// user if it exists.
func (p *politeiawww) getUserByIDStr(userIDStr string) (*user.User, error) {
userID, err := uuid.Parse(userIDStr)
if err != nil {
return nil, www.UserError{
ErrorCode: www.ErrorStatusInvalidUUID,
}
}
usr, err := p.db.UserGetById(userID)
if err != nil {
if err == user.ErrUserNotFound {
return nil, www.UserError{
ErrorCode: www.ErrorStatusUserNotFound,
}
}
return nil, err
}
return usr, nil
}
// getUsernameById returns the username given its id. If the id is invalid,
// it returns an empty string.
func (p *politeiawww) getUsernameById(userIdStr string) string {
userId, err := uuid.Parse(userIdStr)
if err != nil {
return ""
}
u, err := p.db.UserGetById(userId)
if err != nil {
return ""
}
return u.Username
}
// validatePubkeyIsUnique ensures that the provided public key is unique.
// XXX this function does too much. Why are we sending in a pointer to
// XXX user.User?
func (p *politeiawww) validatePubkeyIsUnique(publicKey string, u *user.User) error {
p.RLock()
userIDStr, ok := p.userPubkeys[publicKey]
p.RUnlock()
if !ok {
return nil
}
userID, err := uuid.Parse(userIDStr)
if err != nil {
return err
}
if u != nil && u.ID == userID {
return nil
}
return www.UserError{
ErrorCode: www.ErrorStatusDuplicatePublicKey,
}
}
// processUserDetails return the requested user's details. Some fields can be
// omitted or blank depending on the requester's access level.
func (p *politeiawww) processUserDetails(ud *www.UserDetails, isCurrentUser bool, isAdmin bool) (*www.UserDetailsReply, error) {
// Fetch the database user.
user, err := p.getUserByIDStr(ud.UserID)
if err != nil {
return nil, err
}
// Convert the database user into a proper response.
var udr www.UserDetailsReply
wwwUser := convertWWWUserFromDatabaseUser(user)
// Filter returned fields in case the user isn't the admin or the current user
if !isAdmin && !isCurrentUser {
udr.User = filterUserPublicFields(wwwUser)
} else {
udr.User = wwwUser
}
return &udr, nil
}
// processEditUser edits a user's preferences.
func (p *politeiawww) processEditUser(eu *www.EditUser, user *user.User) (*www.EditUserReply, error) {
if eu.EmailNotifications != nil {
user.EmailNotifications = *eu.EmailNotifications
}
// Update the user in the database.
err := p.db.UserUpdate(*user)
if err != nil {
return nil, err
}
return &www.EditUserReply{}, nil
}
// processUserCommentsLikes returns all of the user's comment likes for the
// passed in proposal.
func (p *politeiawww) processUserCommentsLikes(user *user.User, token string) (*www.UserCommentsLikesReply, error) {
log.Tracef("processUserCommentsLikes: %v %v", user.ID, token)
// Fetch all like comments for the proposal
dlc, err := p.foneroPropCommentLikes(token)
if err != nil {
return nil, fmt.Errorf("foneroPropLikeComments: %v", err)
}
// Sanity check. Like comments should already be sorted in
// chronological order.
sort.SliceStable(dlc, func(i, j int) bool {
return dlc[i].Timestamp < dlc[j].Timestamp
})
p.RLock()
defer p.RUnlock()
// Filter out like comments that are from the user
lc := make([]www.LikeComment, 0, len(dlc))
for _, v := range dlc {
userID, ok := p.userPubkeys[v.PublicKey]
if !ok {
log.Errorf("getUserCommentLikes: userID lookup failed for "+
"token:%v commentID:%v pubkey:%v", v.Token, v.CommentID,
v.PublicKey)
continue
}
if user.ID.String() == userID {
lc = append(lc, convertLikeCommentFromFonero(v))
}
}
// Compute the resulting like comment action for each comment.
// The resulting action depends on the order of the like
// comment actions.
//
// Example: when a user upvotes a comment twice, the second
// upvote cancels out the first upvote and the resulting
// comment score is 0.
//
// Example: when a user upvotes a comment and then downvotes
// the same comment, the downvote takes precedent and the
// resulting comment score is -1.
actions := make(map[string]string) // [commentID]action
for _, v := range lc {
prevAction := actions[v.CommentID]
switch {
case v.Action == prevAction:
// New action is the same as the previous action so
// we undo the previous action.
actions[v.CommentID] = ""
case v.Action != prevAction:
// New action is different than the previous action
// so the new action takes precedent.
actions[v.CommentID] = v.Action
}
}
cl := make([]www.CommentLike, 0, len(lc))
for k, v := range actions {
// Skip actions that have been taken away
if v == "" {
continue
}
cl = append(cl, www.CommentLike{
Token: token,
CommentID: k,
Action: v,
})
}
return &www.UserCommentsLikesReply{
CommentsLikes: cl,
}, nil
}
// login attempts to login a a user.
func (p *politeiawww) login(l *www.Login) loginReplyWithError {
// Get user from db.
u, err := p.userByEmail(l.Email)
if err != nil {
if err == user.ErrUserNotFound {
log.Debugf("Login failure for %v: user not found in database",
l.Email)
return loginReplyWithError{
reply: nil,
err: www.UserError{
ErrorCode: www.ErrorStatusInvalidEmailOrPassword,
},
}
}
return loginReplyWithError{
reply: nil,
err: err,
}
}
// Check the user's password.
err = bcrypt.CompareHashAndPassword(u.HashedPassword,
[]byte(l.Password))
if err != nil {
if !checkUserIsLocked(u.FailedLoginAttempts) {
u.FailedLoginAttempts++
err := p.db.UserUpdate(*u)
if err != nil {
return loginReplyWithError{
reply: nil,
err: err,
}
}
// Check if the user is locked again so we can send an
// email.
if checkUserIsLocked(u.FailedLoginAttempts) && !p.test {
// This is conditional on the email server
// being setup.
err := p.emailUserLocked(u.Email)
if err != nil {
return loginReplyWithError{
reply: nil,
err: err,
}
}
}
}
log.Debugf("Login failure for %v: incorrect password",
l.Email)
return loginReplyWithError{
reply: nil,
err: www.UserError{
ErrorCode: www.ErrorStatusInvalidEmailOrPassword,
},
}
}
// Check that the user is verified.
if u.NewUserVerificationToken != nil {
log.Debugf("Login failure for %v: user not yet verified",
l.Email)
return loginReplyWithError{
reply: nil,
err: www.UserError{
ErrorCode: www.ErrorStatusEmailNotVerified,
},
}
}
// Check if the user account is deactivated.
if u.Deactivated {
log.Debugf("Login failure for %v: user deactivated", l.Email)
return loginReplyWithError{
reply: nil,
err: www.UserError{
ErrorCode: www.ErrorStatusUserDeactivated,
},
}
}
// Check if user is locked due to too many login attempts
if checkUserIsLocked(u.FailedLoginAttempts) {
log.Debugf("Login failure for %v: user locked",
l.Email)
return loginReplyWithError{
reply: nil,
err: www.UserError{
ErrorCode: www.ErrorStatusUserLocked,
},
}
}
lastLoginTime := u.LastLoginTime
u.FailedLoginAttempts = 0
u.LastLoginTime = time.Now().Unix()
err = p.db.UserUpdate(*u)
if err != nil {
return loginReplyWithError{
reply: nil,
err: err,
}
}
reply, err := p.createLoginReply(u, lastLoginTime)
return loginReplyWithError{
reply: reply,
err: err,
}
}
// emailResetPassword handles the reset password command.
func (p *politeiawww) emailResetPassword(u *user.User, rp www.ResetPassword, rpr *www.ResetPasswordReply) error {
if u.ResetPasswordVerificationToken != nil {
if u.ResetPasswordVerificationExpiry > time.Now().Unix() {
// The verification token is present and hasn't
// expired, so do nothing.
return nil
}
}
// The verification token isn't present or is present but expired.
// Generate a new verification token and expiry.
token, expiry, err := generateVerificationTokenAndExpiry()
if err != nil {
return err
}
// Add the updated user information to the db.
u.ResetPasswordVerificationToken = token
u.ResetPasswordVerificationExpiry = expiry
err = p.db.UserUpdate(*u)
if err != nil {
return err
}
if !p.test {
// This is conditional on the email server being setup.
err := p.emailResetPasswordVerificationLink(rp.Email,
hex.EncodeToString(token))
if err != nil {
return err
}
}
// Only set the token if email verification is disabled.
if p.smtp.disabled {
rpr.VerificationToken = hex.EncodeToString(token)
}
return nil
}
// verifyResetPassword verifies the reset password command.
func (p *politeiawww) verifyResetPassword(u *user.User, rp www.ResetPassword, rpr *www.ResetPasswordReply) error {
// Decode the verification token.
token, err := hex.DecodeString(rp.VerificationToken)
if err != nil {
log.Debugf("VerifyResetPassword failure for %v: verification "+
"token could not be decoded: %v", rp.Email, err)
return www.UserError{
ErrorCode: www.ErrorStatusVerificationTokenInvalid,
}
}
// Check that the verification token matches.
if !bytes.Equal(token, u.ResetPasswordVerificationToken) {
log.Debugf("VerifyResetPassword failure for %v: verification "+
"token doesn't match, expected %v", rp.Email,
u.ResetPasswordVerificationToken)
return www.UserError{
ErrorCode: www.ErrorStatusVerificationTokenInvalid,
}
}
// Check that the token hasn't expired.
if u.ResetPasswordVerificationExpiry < time.Now().Unix() {
log.Debugf("VerifyResetPassword failure for %v: verification "+
"token is expired", rp.Email)
return www.UserError{
ErrorCode: www.ErrorStatusVerificationTokenExpired,
}
}
// Validate the new password.
err = validatePassword(rp.NewPassword)
if err != nil {
return err
}
// Hash the new password.
hashedPassword, err := p.hashPassword(rp.NewPassword)
if err != nil {
return err
}
// Clear out the verification token fields, set the new password in the
// db, and unlock account
u.ResetPasswordVerificationToken = nil
u.ResetPasswordVerificationExpiry = 0
u.HashedPassword = hashedPassword
u.FailedLoginAttempts = 0
return p.db.UserUpdate(*u)
}
// createLoginReply creates a login reply.
func (p *politeiawww) createLoginReply(u *user.User, lastLoginTime int64) (*www.LoginReply, error) {
reply := www.LoginReply{
IsAdmin: u.Admin,
UserID: u.ID.String(),
Email: u.Email,
Username: u.Username,
PublicKey: u.PublicKey(),
PaywallTxID: u.NewUserPaywallTx,
ProposalCredits: ProposalCreditBalance(u),
LastLoginTime: lastLoginTime,
}
if !p.HasUserPaid(u) {
err := p.GenerateNewUserPaywall(u)
if err != nil {
return nil, err
}
reply.PaywallAddress = u.NewUserPaywallAddress
reply.PaywallAmount = u.NewUserPaywallAmount
reply.PaywallTxNotBefore = u.NewUserPaywallTxNotBefore
}
return &reply, nil
}
// processNewUser creates a new user in the db if it doesn't already
// exist and sets a verification token and expiry; the token must be
// verified before it expires. If the user already exists in the db
// and its token is expired, it generates a new one.
//
// Note that this function always returns a NewUserReply. The caller shall
// verify error and determine how to return this information upstream.
func (p *politeiawww) processNewUser(u www.NewUser) (*www.NewUserReply, error) {
var (
reply www.NewUserReply
token []byte
expiry int64
)
existingUser, err := p.userByEmail(u.Email)
switch err {
case nil:
// User exists
// Check if the user is already verified.
if existingUser.NewUserVerificationToken == nil {
log.Debugf("processNewUser: user is already verified")
return &reply, nil
}
// Check if the verification token is expired. If the token is
// not expired then we simply return. If the token is expired
// then we treat this request as a standard NewUser request. A
// new token is emailed to the user and the database is updated.
// The user is allowed to use a new pubkey if they want to update
// their identity.
if existingUser.NewUserVerificationExpiry > time.Now().Unix() {
log.Debugf("processNewUser: user is unverified and " +
"verification token has not yet expired")
return &reply, nil
}
case user.ErrUserNotFound:
// Doesn't exist, create new user.
default:
// All other errors
return nil, err
}
// Ensure we got a proper pubkey.
pk, err := validatePubkey(u.PublicKey)
if err != nil {
return nil, err
}
// Format and validate the username.
username := formatUsername(u.Username)
err = validateUsername(username)
if err != nil {
return nil, err
}
// Validate the password.
err = validatePassword(u.Password)
if err != nil {
return nil, err
}
// Validate email.
if !validEmail.MatchString(u.Email) {
log.Debugf("processNewUser: invalid email '%v'", u.Email)
return nil, www.UserError{
ErrorCode: www.ErrorStatusMalformedEmail,
}
}
// Validate that the pubkey isn't already taken.
err = p.validatePubkeyIsUnique(u.PublicKey, existingUser)
if err != nil {
return nil, err
}
// Ensure username is unique
if existingUser == nil {
_, err = p.db.UserGetByUsername(u.Username)
switch err {
case nil:
// Duplicate username
return nil, www.UserError{
ErrorCode: www.ErrorStatusDuplicateUsername,
}
case user.ErrUserNotFound:
// Username doesn't exist; continue
default:
return nil, err
}
}
// Hash the user's password.
hashedPassword, err := p.hashPassword(u.Password)
if err != nil {
return nil, err
}
// Generate the verification token and expiry.
token, expiry, err = generateVerificationTokenAndExpiry()
if err != nil {
return nil, err
}
// Create a new database user with the provided information.
newUser := user.User{
Email: strings.ToLower(u.Email),
Username: username,
HashedPassword: hashedPassword,
Admin: false,
}
setNewUserVerificationAndIdentity(&newUser, token, expiry, false, pk)
if !p.test {
// Try to email the verification link first; if it fails, then
// the new user won't be created.
//
// This is conditional on the email server being setup.
err := p.emailNewUserVerificationLink(u.Email, hex.EncodeToString(token), u.Username)
if err != nil {
log.Errorf("Email new user verification link failed %v, %v", u.Email, err)
return &reply, nil
}
}
// Check if the user already exists.
if existingUser != nil {
existingPublicKey := hex.EncodeToString(existingUser.Identities[0].Key[:])
p.removeUserPubkeyAssociaton(existingUser, existingPublicKey)
// Update the user in the db.
newUser.ID = existingUser.ID
err = p.db.UserUpdate(newUser)
if err != nil {
return nil, err
}
} else {
// Save the new user in the db.
err = p.db.UserNew(newUser)
if err != nil {
return nil, err
}
// Update user emails cache. The user ID needs to be
// looked up first.
u, err := p.db.UserGetByUsername(newUser.Username)
if err != nil {
return nil, fmt.Errorf("userByUsername '%v': %v",
newUser.Username, err)
}
p.setUserEmails(u.Email, u.ID)
}
// Get user that we just inserted so we can use their numerical user
// ID (N) to derive the Nth paywall address from the paywall extended
// public key.
//
// Even if existingUser is non-nil, this will bring it up-to-date
// with the new information inserted via newUser.
existingUser, err = p.userByEmail(newUser.Email)
if err != nil {
return nil, fmt.Errorf("unable to retrieve account info for %v: %v",
newUser.Email, err)
}
// Associate the user id with the new public key.
p.setUserPubkeyAssociaton(existingUser, u.PublicKey)
// Derive paywall information for this user if the paywall is enabled.
err = p.GenerateNewUserPaywall(existingUser)
if err != nil {
return nil, err
}
// Only set the token if email verification is disabled.
if p.smtp.disabled {
reply.VerificationToken = hex.EncodeToString(token)
}
log.Debugf("New user created: %v", u.Username)
return &reply, nil
}
// processVerifyNewUser verifies the token generated for a recently created
// user. It ensures that the token matches with the input and that the token
// hasn't expired. On success it returns database user record.
func (p *politeiawww) processVerifyNewUser(usr www.VerifyNewUser) (*user.User, error) {
// Check that the user already exists.
u, err := p.userByEmail(usr.Email)