-
Notifications
You must be signed in to change notification settings - Fork 0
/
user.go
254 lines (211 loc) · 5.95 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
package models
import (
"encoding/json"
"net/http"
"regexp"
"strings"
"github.com/astaxie/beego"
"github.com/astaxie/beego/orm"
"golang.org/x/crypto/bcrypt"
)
// Role is an enum which spcify the role of a `User`
type Role string
// Values for `Role` enum
const (
EnumRoleAdmin Role = "administrator"
EnumRoleUser Role = "user"
)
// User is the `User` model in the database
type User struct {
ID int64 `json:"id" orm:"pk;auto"`
Username string `json:"username" orm:"unique"`
Email string `json:"email" orm:"unique"`
Role Role `json:"role"`
PasswordHash string `json:"-"`
}
// NewUser is the model sent to create a new `User`
type NewUser struct {
Username string `json:"username"`
Email string `json:"email"`
Password string `json:"password"`
Role Role `json:"role"`
}
// PutUser is only use to document the PUT `User` endpoint
type PutUser struct {
Username string `json:"username"`
Email string `json:"email"`
Password string `json:"password"`
}
func init() {
orm.RegisterModel(new(User))
}
// Bind transforms the given payload into a `User`, with some validations
func (u *User) Bind(requestBody []byte) *JSONError {
var newUser NewUser
if err := json.Unmarshal(requestBody, &newUser); err != nil {
return NewBadRequestError()
}
// fields validation
if len(newUser.Username) == 0 {
return &JSONError{
Status: http.StatusBadRequest,
Error: "username is required.",
}
}
re := regexp.MustCompile("^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$")
if !re.MatchString(newUser.Email) {
return &JSONError{
Status: http.StatusBadRequest,
Error: "email address is not valid.",
}
}
if len(newUser.Password) < 8 {
return &JSONError{
Status: http.StatusBadRequest,
Error: "password should be at least 8 characters.",
}
}
if newUser.Role != EnumRoleAdmin {
newUser.Role = EnumRoleUser
}
cost, _ := beego.AppConfig.Int("hashcost")
bytes, _ := bcrypt.GenerateFromPassword([]byte(newUser.Password), cost)
// `NewUser` --> `User`
u.Username = newUser.Username
u.Email = newUser.Email
u.PasswordHash = string(bytes)
u.Role = newUser.Role
return nil
}
// BindWithEmptyFields transforms the given payload into a `User`, with
// some validations, but does not require any field (they should be either nil
// or valid)
func (u *User) BindWithEmptyFields(requestBody []byte) *JSONError {
var newUser NewUser
if err := json.Unmarshal(requestBody, &newUser); err != nil {
return NewBadRequestError()
}
if newUser.Username != "" {
u.Username = newUser.Username
}
if newUser.Email != "" {
re := regexp.MustCompile("^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$")
if !re.MatchString(newUser.Email) {
return &JSONError{
Status: http.StatusBadRequest,
Error: "email address is not valid.",
}
}
u.Email = newUser.Email
}
if newUser.Password != "" {
if len(newUser.Password) < 8 {
return &JSONError{
Status: http.StatusBadRequest,
Error: "password should be at least 8 characters.",
}
}
cost, _ := beego.AppConfig.Int("hashcost")
bytes, _ := bcrypt.GenerateFromPassword([]byte(newUser.Password), cost)
u.PasswordHash = string(bytes)
}
return nil
}
// AddUser inserts a new `User` into the database
func AddUser(u *User) *JSONError {
o := orm.NewOrm()
if _, err := o.Insert(u); err != nil {
if strings.Contains(err.Error(), "duplicate key") {
return &JSONError{
Status: http.StatusConflict,
Error: "username and/or email already exist(s).",
}
}
return NewInternalServerError()
}
return nil
}
// GetUser returns the `User` with the given `uid` from the database
func GetUser(uid int64) (*User, *JSONError) {
o := orm.NewOrm()
user := User{ID: uid}
if err := o.Read(&user); err != nil {
if err == orm.ErrNoRows {
return nil, &JSONError{
Status: http.StatusNotFound,
Error: "user does not exist.",
}
}
return nil, NewInternalServerError()
}
return &user, nil
}
// GetAllUsers returns all the `User` from the database
func GetAllUsers() (users []*User, jsonErr *JSONError) {
o := orm.NewOrm()
if _, err := o.QueryTable("user").All(&users); err != nil {
return nil, NewInternalServerError()
}
return users, nil
}
// UpdateUser modifies the `User` with the given `uid` in the database, with some validations
func UpdateUser(uid int64, uu *User) (u *User, jsonErr *JSONError) {
o := orm.NewOrm()
u, jsonErr = GetUser(uid)
if jsonErr != nil {
return nil, jsonErr
}
if uu.Username != "" {
u.Username = uu.Username
}
if uu.Email != "" {
u.Email = uu.Email
}
if uu.PasswordHash != "" {
u.PasswordHash = uu.PasswordHash
}
if _, err := o.Update(u); err != nil {
if strings.Contains(err.Error(), "duplicate key") {
return nil, &JSONError{
Status: http.StatusConflict,
Error: "username and/or email already exist(s).",
}
//jsonErr.Status = http.StatusConflict
//jsonErr.Error = "username or email already exists"
//logs.Debug("json error: ", *jsonErr)
//return nil, jsonErr
}
return nil, NewInternalServerError()
}
return u, nil
}
// DeleteUser removes the given Rubus `User` from the database
func DeleteUser(uid int64) *JSONError {
o := orm.NewOrm()
user := User{ID: uid}
uid, err := o.Delete(&user)
if uid == 0 {
return &JSONError{
Status: http.StatusNotFound,
Error: "user does not exist.",
}
}
if err != nil {
return NewInternalServerError()
}
return nil
}
// Login checks if the given credentials are valid or not
func Login(username, password string) (*int64, *Role, bool) {
o := orm.NewOrm()
var user User
err := o.QueryTable("user").Filter("username", username).One(&user)
if err == orm.ErrNoRows {
return nil, nil, false
}
err = bcrypt.CompareHashAndPassword([]byte(user.PasswordHash), []byte(password))
if err != nil {
return nil, nil, false
}
return &user.ID, &user.Role, true
}