/
user.go
251 lines (208 loc) · 5.68 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
package store
import (
"encoding/json"
"errors"
"fmt"
"log"
"math/rand"
"time"
"golang.org/x/crypto/bcrypt"
)
type Permission int
const (
Read Permission = iota
Wholesaler
Admin
)
var (
chars = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
pwBody = `Dear %s,
Please click on the following link to reset your %s password.
https://%s/login/reset/%s
%s
`
)
type Token struct {
Email string `json:"email"`
Expires time.Time `json:"expiers"`
}
type Address struct {
Address string `schema:"address" json:"address,omitempty"`
Address2 string `schema:"address2" json:"address2,omitempty"`
Zip string `schema:"zip" json:"zip,omitempty"`
City string `schema:"city" json:"city,omitempty"`
State string `schema:"state" json:"state,omitempty"`
Country string `schema:"country" json:"country,omitempty"`
}
type User struct {
Email string `schema:"email" json:"email"`
//Wholesale stuff
StoreName string `schema:"store_name" json:"store_name,omitempty"`
DiscountCodeID int `schema:"discount_code_id" json:"discount_code_id,omitempty"`
DiscountCode string `schema:"discount_code" json:"discount_code,omitempty"`
Website string `schema:"website" json:"website,omitempty"`
FirstName string `schema:"first_name" json:"first_name,omitempty"`
LastName string `schema:"last_name" json:"last_name,omitempty"`
Address Address `schema:"address" json:"address,omitempty"`
ShippingAddress Address `schema:"shipping_address" json:"shipping_address,omitempty"`
Permission Permission `json:"permission"`
Password string `schema:"password" json:"-"`
Password2 string `schema:"confirm-password" json:"-"`
HashedPassword []byte `json:"hashed_password,omitempty"`
//They clicked on the verification email link
Verified bool `json:"verified"`
//Admin approval as a real wholesaler
Confirmed bool `json:"confirmed,omitempty"`
}
func GetUsers() ([]User, error) {
var users []User
return users, db.GetAll(Query{Buckets: [][]byte{[]byte("users")}}, func(key, val []byte) error {
var u User
if err := json.Unmarshal(val, &u); err != nil {
return err
}
u.HashedPassword = []byte{}
users = append(users, u)
return nil
})
}
func (u *User) Fetch() error {
return db.Get([]Query{{Key: []byte(u.Email), Buckets: [][]byte{[]byte("users")}}}, func(key, val []byte) error {
return json.Unmarshal(val, &u)
})
}
func (u *User) Save(moreRows ...Query) error {
if len(u.HashedPassword) == 0 { //a new user
if err := u.savePassword(); err != nil {
return err
}
}
d, err := json.Marshal(u)
if err != nil {
return err
}
rows := []Query{{Key: []byte(u.Email), Val: d, Buckets: [][]byte{[]byte("users")}}}
rows = append(rows, moreRows...)
return db.Put(rows)
}
func (u *User) UpdatePassword() error {
if err := u.savePassword(); err != nil {
return err
}
return u.Save()
}
func (u *User) savePassword() error {
if len(u.Password) < 8 {
return errors.New("password is too short (must be at least 8 characters long)")
}
if u.Password != u.Password2 {
return errors.New("passwords don't match")
}
u.hashPassword()
return nil
}
func (u *User) Delete() error {
return db.Delete([]Query{{Buckets: [][]byte{[]byte("users")}, Key: []byte(u.Email)}})
}
func (u *User) CheckPassword() (bool, error) {
pw := u.Password
if len(u.HashedPassword) == 0 {
if err := u.Fetch(); err != nil {
return false, err
}
}
return bcrypt.CompareHashAndPassword(u.HashedPassword, []byte(pw)) == nil, nil
}
func (u *User) hashPassword() error {
var err error
u.HashedPassword, err = bcrypt.GenerateFromPassword(
[]byte(u.Password),
bcrypt.DefaultCost,
)
u.Password = ""
u.Password2 = ""
return err
}
func (u *User) GenerateToken() (string, Query, error) {
token := randStr(32)
t := Token{
Email: u.Email,
Expires: time.Now().Add(24 * 7 * time.Hour),
}
d, err := json.Marshal(t)
return token, NewQuery(Key(token), Val(d), Buckets("verifications")), err
}
func randStr(n int) string {
b := make([]rune, n)
for i := range b {
b[i] = chars[rand.Intn(len(chars))]
}
return string(b)
}
func VerifyWholesaler(token string) (User, error) {
var u User
var email string
q := []Query{NewQuery(Key(token), Buckets("verifications"))}
err := db.Get(q, func(key, val []byte) error {
var t Token
err := json.Unmarshal(val, &t)
if err != nil {
return err
}
if time.Now().Sub(t.Expires) > 0 {
return fmt.Errorf("expired token for %s", t.Email)
}
email = t.Email
return nil
})
if err != nil {
return u, err
}
err = db.Get([]Query{NewQuery(Key(email), Buckets("users"))}, func(key, val []byte) error {
return json.Unmarshal(val, &u)
})
if err != nil {
return u, err
}
err = db.Delete(q)
if err != nil {
return u, err
}
u.Verified = true
return u, u.Save()
}
func SavePasswordReset(email string) (string, error) {
u := User{Email: email}
if err := u.Fetch(); err != nil {
log.Printf("couldn't fetch user for password reset, email: %s, err: %v\n", email, err)
return "", nil
}
k := randStr(64)
t := Token{
Email: email,
Expires: time.Now().Add(24 * time.Hour),
}
d, _ := json.Marshal(t)
return k, db.Put([]Query{NewQuery(Key(k), Val(d), Buckets("tokens"))})
}
func GetUserFromResetToken(key string, expire bool) (User, error) {
var u User
var t Token
q := []Query{NewQuery(Key(key), Buckets("tokens"))}
err := db.Get(q, func(k, v []byte) error {
return json.Unmarshal(v, &t)
})
if err != nil {
return u, err
}
if time.Now().Sub(t.Expires) > 0 {
return u, fmt.Errorf("expired token for %s", t.Email)
}
if expire {
if err := db.Delete(q); err != nil {
return u, err
}
}
u.Email = t.Email
return u, u.Fetch()
}