/
user_model.go
85 lines (66 loc) · 1.74 KB
/
user_model.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
package model
import (
"regexp"
"strings"
"github.com/pkg/errors"
"golang.org/x/crypto/bcrypt"
)
type User struct {
ID UserID
Email Email
Password string
Unit string
}
type (
UserID string
Email string
)
var (
emailValidator = regexp.MustCompile(`^.+@.+$`)
digitValidator = regexp.MustCompile(`\d`)
letterValidator = regexp.MustCompile(`[a-zA-Z]`)
)
const minimumPasswordLength = 8
func NewUser(id UserID, email Email, pw, unit string) (*User, error) {
if err := passwordSpecSatisfied(pw); err != nil {
return nil, errors.Wrapf(err, "invalid password")
}
hash, err := bcrypt.GenerateFromPassword([]byte(pw), bcrypt.DefaultCost)
if err != nil {
return nil, errors.Wrapf(err, "failed to encrypt password")
}
u := &User{
ID: id,
Email: email,
Password: string(hash),
Unit: unit,
}
if err := userSpecSatisfied(*u); err != nil {
return nil, errors.Wrapf(err, "fail to satisfy User spec")
}
return u, nil
}
func passwordSpecSatisfied(pw string) error {
if !digitValidator.MatchString(pw) || !letterValidator.MatchString(pw) {
return errors.Errorf("password must contains at least one digit and letter")
}
if len(pw) < minimumPasswordLength {
return errors.Errorf("password must contains at least eight characters")
}
return nil
}
func userSpecSatisfied(u User) error {
if !emailValidator.MatchString(string(u.Email)) {
return errors.Errorf("invalid email pattern")
}
if strings.TrimSpace(u.Unit) == "" {
return errors.Errorf("invalid unit input")
}
return nil
}
func (u *User) ValidatePassword(password string) error {
if err := bcrypt.CompareHashAndPassword([]byte(u.Password), []byte(password)); err != nil {
return errors.Wrapf(err, "fail to authenticate password")
}
return nil
}