-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpassword.go
97 lines (82 loc) · 1.87 KB
/
password.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
package bcrypt
import (
"database/sql/driver"
"encoding/json"
"golang.org/x/crypto/bcrypt"
)
type (
Password struct {
HashedPassword
Password string `validate:"omitempty,gte=6,lte=72"`
}
)
func (p *Password) MustUpdate(password string, optionalCost ...int) {
if err := p.Update(password, optionalCost...); err != nil {
panic(err)
}
}
func (p *Password) Update(password string, optionalCost ...int) error {
if err := p.HashedPassword.Update(password, optionalCost...); err != nil {
return err
}
p.Password = password
return nil
}
func (p Password) MarshalJSON() ([]byte, error) {
return json.Marshal(p.Password)
}
func (p *Password) UnmarshalJSON(t []byte) error {
var value string
if err := json.Unmarshal(t, &value); err != nil {
return err
}
return p.Update(value)
}
func (p *Password) Scan(src interface{}) error {
p.Password = ""
return p.HashedPassword.Scan(src)
}
type (
HashedPassword struct {
Hashed string
}
)
func (p HashedPassword) String() string {
return p.Hashed
}
func (p *HashedPassword) MustUpdate(password string, optionalCost ...int) {
if err := p.Update(password, optionalCost...); err != nil {
panic(err)
}
}
func (p *HashedPassword) Update(password string, optionalCost ...int) error {
if password == "" {
p.Hashed = ""
return nil
}
cost := bcrypt.DefaultCost
if len(optionalCost) > 0 {
cost = optionalCost[0]
}
b, err := bcrypt.GenerateFromPassword([]byte(password), cost)
if err != nil {
return err
}
p.Hashed = string(b)
return nil
}
func (p HashedPassword) Equal(password string) bool {
if p.Hashed == "" {
return false
}
return bcrypt.CompareHashAndPassword([]byte(p.Hashed), []byte(password)) == nil
}
func (p *HashedPassword) Scan(src interface{}) error {
if value, ok := src.(string); ok {
p.Hashed = value
}
return nil
}
func (p HashedPassword) Value() (driver.Value, error) {
return p.Hashed, nil
}