This repository has been archived by the owner on Jul 7, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
user.go
264 lines (214 loc) · 8.53 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
252
253
254
255
256
257
258
259
260
261
262
263
264
package models
import (
"errors"
"gofreta/app"
"gofreta/utils"
"regexp"
"strconv"
"strings"
"time"
jwt "github.com/dgrijalva/jwt-go"
"github.com/globalsign/mgo/bson"
"github.com/go-ozzo/ozzo-routing/auth"
"github.com/go-ozzo/ozzo-validation"
"github.com/go-ozzo/ozzo-validation/is"
"golang.org/x/crypto/bcrypt"
)
const (
// UserStatusActive specifies the active user model status state.
UserStatusActive = "active"
// UserStatusActive specifies the inactive user model status state.
UserStatusInactive = "inactive"
)
// -------------------------------------------------------------------
// • User model
// -------------------------------------------------------------------
// User defines the User model fields.
type User struct {
ID bson.ObjectId `json:"id" bson:"_id"`
Username string `json:"username" bson:"username"`
Email string `json:"email" bson:"email"`
Status string `json:"status" bson:"status"`
PasswordHash string `json:"-" bson:"password_hash"`
ResetPasswordHash string `json:"-" bson:"reset_password_hash"`
Access map[string][]string `json:"access" bson:"access"`
Created int64 `json:"created" bson:"created"`
Modified int64 `json:"modified" bson:"modified"`
}
// ValidatePassword validates User model `PasswordHash` string against a plain password
func (m User) ValidatePassword(password string) bool {
bytePassword := []byte(password)
bytePasswordHash := []byte(m.PasswordHash)
// comparing the password with the hash
err := bcrypt.CompareHashAndPassword(bytePasswordHash, bytePassword)
// nil means it is a match
return err == nil
}
// SetPassword sets cryptographically secure User model `PasswordHash` string
func (m *User) SetPassword(password string) {
bytePassword := []byte(password)
// hashing the password
hashedPassword, err := bcrypt.GenerateFromPassword(bytePassword, 12)
if err != nil {
panic(err)
}
m.PasswordHash = string(hashedPassword)
m.ResetPasswordHash = ""
}
// NewAuthToken generates and returns new user authentication token.
func (m User) NewAuthToken(exp int64) (string, error) {
claims := jwt.MapClaims{
"id": m.ID.Hex(),
"model": "user",
"exp": exp,
}
signingKey := app.Config.GetString("jwt.signingKey")
return auth.NewJWT(claims, signingKey)
}
// HasValidResetPasswordHash checks whether the model reset password hash is valid.
func (m User) HasValidResetPasswordHash() bool {
parts := strings.SplitN(m.ResetPasswordHash, "_", 2)
if len(parts) == 2 {
if castedVal, castErr := strconv.Atoi(parts[1]); castErr == nil {
hashTime := int64(castedVal)
currentTime := time.Now().Unix()
secret := app.Config.GetString("resetPassword.secret")
return currentTime < hashTime && parts[0] == utils.MD5(m.ID.Hex()+secret)
}
}
return false
}
// SetResetPasswordHash sets new user reset password hash.
func (m *User) SetResetPasswordHash(exp int64) {
secret := app.Config.GetString("resetPassword.secret")
m.ResetPasswordHash = utils.MD5(m.ID.Hex()+secret) + "_" + strconv.FormatInt(exp, 10)
}
// -------------------------------------------------------------------
// • User create form model
// -------------------------------------------------------------------
// UserCreateForm defines struct to create a new user.
type UserCreateForm struct {
Username string `json:"username" form:"username"`
Email string `json:"email" form:"email"`
Status string `json:"status" form:"status"`
Password string `json:"password" form:"password"`
PasswordConfirm string `json:"password_confirm" form:"password_confirm"`
Access map[string][]string `json:"access" form:"access"`
}
// Validate validates user create form fields.
func (m UserCreateForm) Validate() error {
return validation.ValidateStruct(&m,
validation.Field(&m.Username, validation.Required, validation.Length(3, 255), validation.Match(regexp.MustCompile(`^[\w\.]+$`))),
validation.Field(&m.Email, validation.Required, is.Email),
validation.Field(&m.Status, validation.Required, validation.In(UserStatusActive, UserStatusInactive)),
validation.Field(&m.Password, validation.Required),
validation.Field(&m.PasswordConfirm, validation.Required, validation.By(checkPasswordConfirm(m.Password))),
validation.Field(&m.Access, validation.Required),
)
}
// ResolveModel creates and returns new User model based on the create form fields.
func (m UserCreateForm) ResolveModel() *User {
now := time.Now().Unix()
user := &User{
ID: bson.NewObjectId(),
Username: m.Username,
Email: m.Email,
Access: m.Access,
Status: m.Status,
Created: now,
Modified: now,
}
user.SetPassword(m.Password)
return user
}
// -------------------------------------------------------------------
// • User update form model
// -------------------------------------------------------------------
// UserUpdateForm defines struct to update an user.
type UserUpdateForm struct {
Model *User `json:"-" form:"-"`
Username string `json:"username" form:"username"`
Email string `json:"email" form:"email"`
Status string `json:"status" form:"status"`
Access map[string][]string `json:"access" form:"access"`
Password string `json:"password" form:"password"`
PasswordConfirm string `json:"password_confirm" form:"password_confirm"`
}
// Validate validates user update form fields.
func (m UserUpdateForm) Validate() error {
return validation.ValidateStruct(&m,
validation.Field(&m.Username, validation.Required, validation.Length(3, 255), validation.Match(regexp.MustCompile(`^[\w\.]+$`))),
validation.Field(&m.Email, validation.Required, is.Email),
validation.Field(&m.Status, validation.Required, validation.In(UserStatusActive, UserStatusInactive)),
validation.Field(&m.Access, validation.Required),
validation.Field(&m.PasswordConfirm, validation.By(checkOptionalRequirement(m.Password)), validation.By(checkPasswordConfirm(m.Password))),
)
}
// ResolveModel resolves and returns the update form user model.
func (m UserUpdateForm) ResolveModel() *User {
model := *m.Model
if m.Model == nil {
return nil
}
model.Username = m.Username
model.Email = m.Email
model.Status = m.Status
model.Access = m.Access
model.Modified = time.Now().Unix()
// set new password
if m.Password != "" && m.Password == m.PasswordConfirm {
model.SetPassword(m.Password)
}
return &model
}
// -------------------------------------------------------------------
// • User reset password form model
// -------------------------------------------------------------------
// UserUpdateForm defines struct to update an user.
type UserResetPasswordForm struct {
Model *User `json:"-" form:"-"`
Password string `json:"password" form:"password"`
PasswordConfirm string `json:"password_confirm" form:"password_confirm"`
}
// Validate validates user reset password form fields.
func (m UserResetPasswordForm) Validate() error {
return validation.ValidateStruct(&m,
validation.Field(&m.Password, validation.Required),
validation.Field(&m.PasswordConfirm, validation.Required, validation.By(checkPasswordConfirm(m.Password))),
)
}
// ResolveModel resolves and returns the reset password form user model.
func (m UserResetPasswordForm) ResolveModel() *User {
model := *m.Model
if m.Model == nil {
return nil
}
if m.Password != "" && m.Password == m.PasswordConfirm {
model.SetPassword(m.Password)
}
model.Modified = time.Now().Unix()
return &model
}
// -------------------------------------------------------------------
// • Common user forms helpers and validators
// -------------------------------------------------------------------
// checkPasswordConfirm validates and checks whether the provided password has the same value as the validating one.
func checkPasswordConfirm(comparePassword string) validation.RuleFunc {
return func(value interface{}) error {
v, _ := value.(string)
if v != comparePassword {
return errors.New("Password confirmation doesn't match.")
}
return nil
}
}
// checkOptionalRequirement requires the validating field to be required if `compareValue` is not empty.
func checkOptionalRequirement(compareValue string) validation.RuleFunc {
return func(value interface{}) error {
v, _ := value.(string)
if compareValue != "" && v == "" {
return errors.New("This field is required.")
}
return nil
}
}