/
user.go
66 lines (52 loc) · 1.36 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
package models
import (
"errors"
"regexp"
"time"
"golang.org/x/crypto/bcrypt"
)
type (
User struct {
ID int64 `json:"id"`
Email string `json:"email" gorm:"unique_index"`
Password string `json:"-"`
Admin bool `json:"-"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
PostedUser struct {
Email string `json:"email"`
Password string `json:"password"`
}
UserClaims struct {
ID int64
Email string
Admin bool
}
)
var (
errPasswordLength = errors.New("Password must be at least 6 characters")
errEmail = errors.New("That is not a valid email")
validEmail = regexp.MustCompile(`^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$`)
)
func (u *PostedUser) HashPassword() error {
bytes, err := bcrypt.GenerateFromPassword([]byte(u.Password), bcrypt.DefaultCost)
if err != nil {
return err
}
u.Password = string(bytes)
return nil
}
func (u *PostedUser) Validate() error {
if u.Email == "" || !validEmail.MatchString(u.Email) {
return errEmail
}
if len(u.Password) < 6 {
return errPasswordLength
}
return nil
}
func (u *User) CheckPassword(password string) bool {
err := bcrypt.CompareHashAndPassword([]byte(u.Password), []byte(password))
return err == nil
}