-
Notifications
You must be signed in to change notification settings - Fork 1
/
user.go
56 lines (45 loc) · 1.04 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
package model
import (
"errors"
"golang.org/x/crypto/bcrypt"
)
// User ...
type User struct {
ID int `json:"id"`
Email string `json:"email"`
Password string `json:"password,omitempty"`
EncryptedPassword string `json:"-"`
}
// Validate ...
func (u *User) Validate() error {
if u.Email != "hacker@hacker.hack" || u.Password != "anonym" {
return errors.New("u r not hacker")
}
return nil
}
// BeforeCreate ...
func (u *User) BeforeCreate() error {
if len(u.Password) > 0 {
enc, err := encryptString(u.Password)
if err != nil {
return err
}
u.EncryptedPassword = enc
}
return nil
}
// Sanitize ...
func (u *User) Sanitize() {
u.Password = ""
}
// ComparePassword ...
func (u *User) ComparePassword(password string) bool {
return bcrypt.CompareHashAndPassword([]byte(u.EncryptedPassword), []byte(password)) == nil
}
func encryptString(s string) (string, error) {
b, err := bcrypt.GenerateFromPassword([]byte(s), bcrypt.MinCost)
if err != nil {
return "", err
}
return string(b), nil
}