-
-
Notifications
You must be signed in to change notification settings - Fork 7
/
user.go
519 lines (452 loc) · 13.2 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
package user
import (
"encoding/json"
"errors"
"io"
"regexp"
"strings"
"time"
)
type User struct {
Id string `json:"userid,omitempty" bson:"userid,omitempty"` // map userid to id
Username string `json:"username,omitempty" bson:"username,omitempty"`
Emails []string `json:"emails,omitempty" bson:"emails,omitempty"`
Roles []string `json:"roles,omitempty" bson:"roles,omitempty"`
TermsAccepted string `json:"termsAccepted,omitempty" bson:"termsAccepted,omitempty"`
EmailVerified bool `json:"emailVerified" bson:"authenticated"` //tag is name `authenticated` for historical reasons
PwHash string `json:"-" bson:"pwhash,omitempty"`
Hash string `json:"-" bson:"userhash,omitempty"`
Private map[string]*IdHashPair `json:"-" bson:"private"`
CreatedTime string `json:"createdTime,omitempty" bson:"createdTime,omitempty"`
CreatedUserID string `json:"createdUserId,omitempty" bson:"createdUserId,omitempty"`
ModifiedTime string `json:"modifiedTime,omitempty" bson:"modifiedTime,omitempty"`
ModifiedUserID string `json:"modifiedUserId,omitempty" bson:"modifiedUserId,omitempty"`
DeletedTime string `json:"deletedTime,omitempty" bson:"deletedTime,omitempty"`
DeletedUserID string `json:"deletedUserId,omitempty" bson:"deletedUserId,omitempty"`
}
/*
* Incoming user details used to create or update a `User`
*/
type NewUserDetails struct {
Username *string
Emails []string
Password *string
Roles []string
}
type NewCustodialUserDetails struct {
Username *string
Emails []string
}
type UpdateUserDetails struct {
Username *string
Emails []string
Password *string
Roles []string
TermsAccepted *string
EmailVerified *bool
}
var (
User_error_details_missing = errors.New("User details are missing")
User_error_username_missing = errors.New("Username is missing")
User_error_username_invalid = errors.New("Username is invalid")
User_error_emails_missing = errors.New("Emails are missing")
User_error_emails_invalid = errors.New("Emails are invalid")
User_error_password_missing = errors.New("Password is missing")
User_error_password_invalid = errors.New("Password is invalid")
User_error_roles_invalid = errors.New("Roles are invalid")
User_error_terms_accepted_invalid = errors.New("Terms accepted is invalid")
User_error_email_verified_invalid = errors.New("Email verified is invalid")
)
func ExtractBool(data map[string]interface{}, key string) (*bool, bool) {
if raw, ok := data[key]; !ok {
return nil, true
} else if extractedBool, ok := raw.(bool); !ok {
return nil, false
} else {
return &extractedBool, true
}
}
func ExtractString(data map[string]interface{}, key string) (*string, bool) {
if raw, ok := data[key]; !ok {
return nil, true
} else if extractedString, ok := raw.(string); !ok {
return nil, false
} else {
return &extractedString, true
}
}
func ExtractArray(data map[string]interface{}, key string) ([]interface{}, bool) {
if raw, ok := data[key]; !ok {
return nil, true
} else if extractedArray, ok := raw.([]interface{}); !ok {
return nil, false
} else if len(extractedArray) == 0 {
return []interface{}{}, true
} else {
return extractedArray, true
}
}
func ExtractStringArray(data map[string]interface{}, key string) ([]string, bool) {
if rawArray, ok := ExtractArray(data, key); !ok {
return nil, false
} else if rawArray == nil {
return nil, true
} else {
extractedStringArray := make([]string, 0)
for _, raw := range rawArray {
if extractedString, ok := raw.(string); !ok {
return nil, false
} else {
extractedStringArray = append(extractedStringArray, extractedString)
}
}
return extractedStringArray, true
}
}
func ExtractStringMap(data map[string]interface{}, key string) (map[string]interface{}, bool) {
if raw, ok := data[key]; !ok {
return nil, true
} else if extractedMap, ok := raw.(map[string]interface{}); !ok {
return nil, false
} else if len(extractedMap) == 0 {
return map[string]interface{}{}, true
} else {
return extractedMap, true
}
}
func IsValidEmail(email string) bool {
ok, _ := regexp.MatchString(`\A(?i)([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z`, email)
return ok
}
func IsValidPassword(password string) bool {
ok, _ := regexp.MatchString(`\A\S{8,72}\z`, password)
return ok
}
func IsValidRole(role string) bool {
switch role {
case "clinic":
return true
default:
return false
}
}
func IsValidDate(date string) bool {
_, err := time.Parse("2006-01-02", date)
return err == nil
}
func IsValidTimestamp(timestamp string) bool {
_, err := time.Parse("2006-01-02T15:04:05-07:00", timestamp)
return err == nil
}
func (details *NewUserDetails) ExtractFromJSON(reader io.Reader) error {
if reader == nil {
return User_error_details_missing
}
var decoded map[string]interface{}
if err := json.NewDecoder(reader).Decode(&decoded); err != nil {
return err
}
var (
username *string
emails []string
password *string
roles []string
ok bool
)
if username, ok = ExtractString(decoded, "username"); !ok {
return User_error_username_invalid
}
if emails, ok = ExtractStringArray(decoded, "emails"); !ok {
return User_error_emails_invalid
}
if password, ok = ExtractString(decoded, "password"); !ok {
return User_error_password_invalid
}
if roles, ok = ExtractStringArray(decoded, "roles"); !ok {
return User_error_roles_invalid
}
details.Username = username
details.Emails = emails
details.Password = password
details.Roles = roles
return nil
}
func (details *NewUserDetails) Validate() error {
if details.Username == nil {
return User_error_username_missing
} else if !IsValidEmail(*details.Username) {
return User_error_username_invalid
}
if len(details.Emails) == 0 {
return User_error_emails_missing
} else {
for _, email := range details.Emails {
if !IsValidEmail(email) {
return User_error_emails_invalid
}
}
}
if details.Password == nil {
return User_error_password_missing
} else if !IsValidPassword(*details.Password) {
return User_error_password_invalid
}
if details.Roles != nil {
for _, role := range details.Roles {
if !IsValidRole(role) {
return User_error_roles_invalid
}
}
}
return nil
}
func ParseNewUserDetails(reader io.Reader) (*NewUserDetails, error) {
details := &NewUserDetails{}
if err := details.ExtractFromJSON(reader); err != nil {
return nil, err
} else {
return details, nil
}
}
func NewUser(details *NewUserDetails, salt string) (user *User, err error) {
if details == nil {
return nil, errors.New("New user details is nil")
} else if err := details.Validate(); err != nil {
return nil, err
}
user = &User{Username: *details.Username, Emails: details.Emails, Roles: details.Roles}
if user.Id, err = generateUniqueHash([]string{*details.Username, *details.Password}, 10); err != nil {
return nil, errors.New("User: error generating id")
}
if user.Hash, err = generateUniqueHash([]string{*details.Username, *details.Password, user.Id}, 24); err != nil {
return nil, errors.New("User: error generating hash")
}
if err = user.HashPassword(*details.Password, salt); err != nil {
return nil, errors.New("User: error generating password hash")
}
return user, nil
}
func (details *NewCustodialUserDetails) ExtractFromJSON(reader io.Reader) error {
if reader == nil {
return User_error_details_missing
}
var decoded map[string]interface{}
if err := json.NewDecoder(reader).Decode(&decoded); err != nil {
return err
}
var (
username *string
emails []string
ok bool
)
if username, ok = ExtractString(decoded, "username"); !ok {
return User_error_username_invalid
}
if emails, ok = ExtractStringArray(decoded, "emails"); !ok {
return User_error_emails_invalid
}
details.Username = username
details.Emails = emails
return nil
}
func (details *NewCustodialUserDetails) Validate() error {
if details.Username != nil {
if !IsValidEmail(*details.Username) {
return User_error_username_invalid
}
}
if details.Emails != nil {
for _, email := range details.Emails {
if !IsValidEmail(email) {
return User_error_emails_invalid
}
}
}
return nil
}
func ParseNewCustodialUserDetails(reader io.Reader) (*NewCustodialUserDetails, error) {
details := &NewCustodialUserDetails{}
if err := details.ExtractFromJSON(reader); err != nil {
return nil, err
} else {
return details, nil
}
}
func NewCustodialUser(details *NewCustodialUserDetails, salt string) (user *User, err error) {
if details == nil {
return nil, errors.New("New custodial user details is nil")
} else if err := details.Validate(); err != nil {
return nil, err
}
var username string
if details.Username != nil {
username = *details.Username
}
user = &User{Username: username, Emails: details.Emails}
if user.Id, err = generateUniqueHash([]string{username}, 10); err != nil {
return nil, errors.New("User: error generating id")
}
if user.Hash, err = generateUniqueHash([]string{username, user.Id}, 24); err != nil {
return nil, errors.New("User: error generating hash")
}
return user, nil
}
func (details *UpdateUserDetails) ExtractFromJSON(reader io.Reader) error {
if reader == nil {
return User_error_details_missing
}
var decoded map[string]interface{}
if err := json.NewDecoder(reader).Decode(&decoded); err != nil {
return err
}
var (
username *string
emails []string
password *string
roles []string
termsAccepted *string
emailVerified *bool
ok bool
)
decoded, ok = ExtractStringMap(decoded, "updates")
if !ok || decoded == nil {
return User_error_details_missing
}
if username, ok = ExtractString(decoded, "username"); !ok {
return User_error_username_invalid
}
if emails, ok = ExtractStringArray(decoded, "emails"); !ok {
return User_error_emails_invalid
}
if password, ok = ExtractString(decoded, "password"); !ok {
return User_error_password_invalid
}
if roles, ok = ExtractStringArray(decoded, "roles"); !ok {
return User_error_roles_invalid
}
if termsAccepted, ok = ExtractString(decoded, "termsAccepted"); !ok {
return User_error_terms_accepted_invalid
}
if emailVerified, ok = ExtractBool(decoded, "emailVerified"); !ok {
return User_error_email_verified_invalid
}
details.Username = username
details.Emails = emails
details.Password = password
details.Roles = roles
details.TermsAccepted = termsAccepted
details.EmailVerified = emailVerified
return nil
}
func (details *UpdateUserDetails) Validate() error {
if details.Username != nil {
if !IsValidEmail(*details.Username) {
return User_error_username_invalid
}
}
if details.Emails != nil {
for _, email := range details.Emails {
if !IsValidEmail(email) {
return User_error_emails_invalid
}
}
}
if details.Password != nil {
if !IsValidPassword(*details.Password) {
return User_error_password_invalid
}
}
if details.Roles != nil {
for _, role := range details.Roles {
if !IsValidRole(role) {
return User_error_roles_invalid
}
}
}
if details.TermsAccepted != nil {
if !IsValidTimestamp(*details.TermsAccepted) {
return User_error_terms_accepted_invalid
}
}
return nil
}
func ParseUpdateUserDetails(reader io.Reader) (*UpdateUserDetails, error) {
details := &UpdateUserDetails{}
if err := details.ExtractFromJSON(reader); err != nil {
return nil, err
} else {
return details, nil
}
}
func (u *User) IsDeleted() bool {
return u.DeletedTime != ""
}
func (u *User) Email() string {
return u.Username
}
func (u *User) HasRole(role string) bool {
for _, userRole := range u.Roles {
if userRole == role {
return true
}
}
return false
}
func (u *User) IsClinic() bool {
return u.HasRole("clinic")
}
func (u *User) HashPassword(pw, salt string) error {
if passwordHash, err := GeneratePasswordHash(u.Id, pw, salt); err != nil {
return err
} else {
u.PwHash = passwordHash
return nil
}
}
func (u *User) PasswordsMatch(pw, salt string) bool {
if u.PwHash == "" || pw == "" {
return false
} else if pwMatch, err := GeneratePasswordHash(u.Id, pw, salt); err != nil {
return false
} else {
return u.PwHash == pwMatch
}
}
func (u *User) IsEmailVerified(secret string) bool {
if secret != "" {
if strings.Contains(u.Username, secret) {
return true
}
for i := range u.Emails {
if strings.Contains(u.Emails[i], secret) {
return true
}
}
}
return u.EmailVerified
}
func (u *User) DeepClone() *User {
clonedUser := &User{
Id: u.Id,
Username: u.Username,
TermsAccepted: u.TermsAccepted,
EmailVerified: u.EmailVerified,
PwHash: u.PwHash,
Hash: u.Hash,
}
if u.Emails != nil {
clonedUser.Emails = make([]string, len(u.Emails))
copy(clonedUser.Emails, u.Emails)
}
if u.Roles != nil {
clonedUser.Roles = make([]string, len(u.Roles))
copy(clonedUser.Roles, u.Roles)
}
if u.Private != nil {
clonedUser.Private = make(map[string]*IdHashPair)
for k, v := range u.Private {
clonedUser.Private[k] = &IdHashPair{Id: v.Id, Hash: v.Hash}
}
}
return clonedUser
}