forked from GoAdminGroup/go-admin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
user.go
507 lines (419 loc) · 12.2 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
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
package models
import (
"database/sql"
"net/url"
"regexp"
"strconv"
"strings"
"time"
"github.com/nneesshh/go-admin/modules/config"
"github.com/nneesshh/go-admin/modules/db"
"github.com/nneesshh/go-admin/modules/db/dialect"
"github.com/nneesshh/go-admin/modules/logger"
"github.com/nneesshh/go-admin/modules/utils"
"github.com/nneesshh/go-admin/plugins/admin/modules/constant"
)
// UserModel is user model structure.
type UserModel struct {
Base `json:"-"`
Id int64 `json:"id"`
Name string `json:"name"`
UserName string `json:"user_name"`
Password string `json:"password"`
Avatar string `json:"avatar"`
RememberToken string `json:"remember_token"`
Permissions []PermissionModel `json:"permissions"`
MenuIds []int64 `json:"menu_ids"`
Roles []RoleModel `json:"role"`
Level string `json:"level"`
LevelName string `json:"level_name"`
CreatedAt string `json:"created_at"`
UpdatedAt string `json:"updated_at"`
cacheReplacer *strings.Replacer
}
// User return a default user model.
func User() UserModel {
return UserModel{Base: Base{TableName: config.GetAuthUserTable()}}
}
// UserWithId return a default user model of given id.
func UserWithId(id string) UserModel {
idInt, _ := strconv.Atoi(id)
return UserModel{Base: Base{TableName: config.GetAuthUserTable()}, Id: int64(idInt)}
}
func (t UserModel) SetConn(con db.Connection) UserModel {
t.Conn = con
return t
}
func (t UserModel) WithTx(tx *sql.Tx) UserModel {
t.Tx = tx
return t
}
// Find return a default user model of given id.
func (t UserModel) Find(id interface{}) UserModel {
item, _ := t.Table(t.TableName).Find(id)
return t.MapToModel(item)
}
// FindByUserName return a default user model of given name.
func (t UserModel) FindByUserName(username interface{}) UserModel {
item, _ := t.Table(t.TableName).Where("username", "=", username).First()
return t.MapToModel(item)
}
// IsEmpty check the user model is empty or not.
func (t UserModel) IsEmpty() bool {
return t.Id == int64(0)
}
// HasMenu check the user has visitable menu or not.
func (t UserModel) HasMenu() bool {
return len(t.MenuIds) != 0 || t.IsSuperAdmin()
}
// IsSuperAdmin check the user model is super admin or not.
func (t UserModel) IsSuperAdmin() bool {
for _, per := range t.Permissions {
if len(per.HttpPath) > 0 && per.HttpPath[0] == "*" && per.HttpMethod[0] == "" {
return true
}
}
return false
}
func (t UserModel) GetCheckPermissionByUrlMethod(path, method string) string {
if !t.CheckPermissionByUrlMethod(path, method, url.Values{}) {
return ""
}
return path
}
func (t UserModel) IsVisitor() bool {
return !t.CheckPermissionByUrlMethod(config.Url("/info/normal_manager"), "GET", url.Values{})
}
func (t UserModel) HideUserCenterEntrance() bool {
return t.IsVisitor() && config.GetHideVisitorUserCenterEntrance()
}
func (t UserModel) Template(str string) string {
if t.cacheReplacer == nil {
t.cacheReplacer = strings.NewReplacer("{{.AuthId}}", strconv.Itoa(int(t.Id)),
"{{.AuthName}}", t.Name, "{{.AuthUserName}}", t.UserName)
}
return t.cacheReplacer.Replace(str)
}
func (t UserModel) CheckPermissionByUrlMethod(path, method string, formParams url.Values) bool {
// path, _ = url.PathUnescape(path)
if t.IsSuperAdmin() {
return true
}
if path == "" {
return false
}
logoutCheck, _ := regexp.Compile(config.Url("/logout") + "(.*?)")
if logoutCheck.MatchString(path) {
return true
}
if path != "/" && path[len(path)-1] == '/' {
path = path[:len(path)-1]
}
path = utils.ReplaceAll(path, constant.EditPKKey, "id", constant.DetailPKKey, "id")
path, params := getParam(path)
for key, value := range formParams {
if len(value) > 0 {
params.Add(key, value[0])
}
}
for _, v := range t.Permissions {
if v.HttpMethod[0] == "" || inMethodArr(v.HttpMethod, method) {
if v.HttpPath[0] == "*" {
return true
}
for i := 0; i < len(v.HttpPath); i++ {
matchPath := config.Url(t.Template(strings.TrimSpace(v.HttpPath[i])))
matchPath, matchParam := getParam(matchPath)
if matchPath == path {
if t.checkParam(params, matchParam) {
return true
}
}
reg, err := regexp.Compile(matchPath)
if err != nil {
logger.Error("CheckPermissions error: ", err)
continue
}
if reg.FindString(path) == path {
if t.checkParam(params, matchParam) {
return true
}
}
}
}
}
return false
}
func getParam(u string) (string, url.Values) {
m := make(url.Values)
urr := strings.Split(u, "?")
if len(urr) > 1 {
m, _ = url.ParseQuery(urr[1])
}
return urr[0], m
}
func (t UserModel) checkParam(src, comp url.Values) bool {
if len(comp) == 0 {
return true
}
if len(src) == 0 {
return false
}
for key, value := range comp {
v, find := src[key]
if !find {
return false
}
if len(value) == 0 {
continue
}
if len(v) == 0 {
return false
}
for i := 0; i < len(v); i++ {
if v[i] == t.Template(value[i]) {
continue
} else {
return false
}
}
}
return true
}
func inMethodArr(arr []string, str string) bool {
for i := 0; i < len(arr); i++ {
if strings.EqualFold(arr[i], str) {
return true
}
}
return false
}
// UpdateAvatar update the avatar of user.
func (t UserModel) ReleaseConn() UserModel {
t.Conn = nil
return t
}
// UpdateAvatar update the avatar of user.
func (t UserModel) UpdateAvatar(avatar string) {
t.Avatar = avatar
}
// WithRoles query the role info of the user.
func (t UserModel) WithRoles() UserModel {
roleModel, _ := t.Table("goadmin_role_users").
LeftJoin("goadmin_roles", "goadmin_roles.id", "=", "goadmin_role_users.role_id").
Where("user_id", "=", t.Id).
Select("goadmin_roles.id", "goadmin_roles.name", "goadmin_roles.slug",
"goadmin_roles.created_at", "goadmin_roles.updated_at").
All()
for _, role := range roleModel {
t.Roles = append(t.Roles, Role().MapToModel(role))
}
if len(t.Roles) > 0 {
t.Level = t.Roles[0].Slug
t.LevelName = t.Roles[0].Name
}
return t
}
func (t UserModel) GetAllRoleId() []interface{} {
var ids = make([]interface{}, len(t.Roles))
for key, role := range t.Roles {
ids[key] = role.Id
}
return ids
}
// WithPermissions query the permission info of the user.
func (t UserModel) WithPermissions() UserModel {
var permissions = make([]map[string]interface{}, 0)
roleIds := t.GetAllRoleId()
if len(roleIds) > 0 {
permissions, _ = t.Table("goadmin_role_permissions").
LeftJoin("goadmin_permissions", "goadmin_permissions.id", "=", "goadmin_role_permissions.permission_id").
WhereIn("role_id", roleIds).
Select("goadmin_permissions.http_method", "goadmin_permissions.http_path",
"goadmin_permissions.id", "goadmin_permissions.name", "goadmin_permissions.slug",
"goadmin_permissions.created_at", "goadmin_permissions.updated_at").
All()
}
userPermissions, _ := t.Table("goadmin_user_permissions").
LeftJoin("goadmin_permissions", "goadmin_permissions.id", "=", "goadmin_user_permissions.permission_id").
Where("user_id", "=", t.Id).
Select("goadmin_permissions.http_method", "goadmin_permissions.http_path",
"goadmin_permissions.id", "goadmin_permissions.name", "goadmin_permissions.slug",
"goadmin_permissions.created_at", "goadmin_permissions.updated_at").
All()
permissions = append(permissions, userPermissions...)
for i := 0; i < len(permissions); i++ {
exist := false
for j := 0; j < len(t.Permissions); j++ {
if t.Permissions[j].Id == permissions[i]["id"] {
exist = true
break
}
}
if exist {
continue
}
t.Permissions = append(t.Permissions, Permission().MapToModel(permissions[i]))
}
return t
}
// WithMenus query the menu info of the user.
func (t UserModel) WithMenus() UserModel {
var menuIdsModel []map[string]interface{}
if t.IsSuperAdmin() {
menuIdsModel, _ = t.Table("goadmin_role_menu").
LeftJoin("goadmin_menu", "goadmin_menu.id", "=", "goadmin_role_menu.menu_id").
Select("menu_id", "parent_id").
All()
} else {
rolesId := t.GetAllRoleId()
if len(rolesId) > 0 {
menuIdsModel, _ = t.Table("goadmin_role_menu").
LeftJoin("goadmin_menu", "goadmin_menu.id", "=", "goadmin_role_menu.menu_id").
WhereIn("goadmin_role_menu.role_id", rolesId).
Select("menu_id", "parent_id").
All()
}
}
var menuIds []int64
for _, mid := range menuIdsModel {
if parentId, ok := mid["parent_id"].(int64); ok && parentId != 0 {
for _, mid2 := range menuIdsModel {
if mid2["menu_id"].(int64) == mid["parent_id"].(int64) {
menuIds = append(menuIds, mid["menu_id"].(int64))
break
}
}
} else {
menuIds = append(menuIds, mid["menu_id"].(int64))
}
}
t.MenuIds = menuIds
return t
}
// New create a user model.
func (t UserModel) New(username, password, name, avatar string) (UserModel, error) {
id, err := t.WithTx(t.Tx).Table(t.TableName).Insert(dialect.H{
"username": username,
"password": password,
"name": name,
"avatar": avatar,
})
t.Id = id
t.UserName = username
t.Password = password
t.Avatar = avatar
t.Name = name
return t, err
}
// Update update the user model.
func (t UserModel) Update(username, password, name, avatar string, isUpdateAvatar bool) (int64, error) {
fieldValues := dialect.H{
"username": username,
"name": name,
"updated_at": time.Now().Format("2006-01-02 15:04:05"),
}
if avatar == "" || isUpdateAvatar {
fieldValues["avatar"] = avatar
}
if password != "" {
fieldValues["password"] = password
}
return t.WithTx(t.Tx).Table(t.TableName).
Where("id", "=", t.Id).
Update(fieldValues)
}
// UpdatePwd update the password of the user model.
func (t UserModel) UpdatePwd(password string) UserModel {
_, _ = t.Table(t.TableName).
Where("id", "=", t.Id).
Update(dialect.H{
"password": password,
})
t.Password = password
return t
}
// CheckRole check the role of the user model.
func (t UserModel) CheckRoleId(roleId string) bool {
checkRole, _ := t.Table("goadmin_role_users").
Where("role_id", "=", roleId).
Where("user_id", "=", t.Id).
First()
return checkRole != nil
}
// DeleteRoles delete all the roles of the user model.
func (t UserModel) DeleteRoles() error {
return t.Table("goadmin_role_users").
Where("user_id", "=", t.Id).
Delete()
}
// AddRole add a role of the user model.
func (t UserModel) AddRole(roleId string) (int64, error) {
if roleId != "" {
if !t.CheckRoleId(roleId) {
return t.WithTx(t.Tx).Table("goadmin_role_users").
Insert(dialect.H{
"role_id": roleId,
"user_id": t.Id,
})
}
}
return 0, nil
}
// CheckRole check the role of the user.
func (t UserModel) CheckRole(slug string) bool {
for _, role := range t.Roles {
if role.Slug == slug {
return true
}
}
return false
}
// CheckPermission check the permission of the user.
func (t UserModel) CheckPermissionById(permissionId string) bool {
checkPermission, _ := t.Table("goadmin_user_permissions").
Where("permission_id", "=", permissionId).
Where("user_id", "=", t.Id).
First()
return checkPermission != nil
}
// CheckPermission check the permission of the user.
func (t UserModel) CheckPermission(permission string) bool {
for _, per := range t.Permissions {
if per.Slug == permission {
return true
}
}
return false
}
// DeletePermissions delete all the permissions of the user model.
func (t UserModel) DeletePermissions() error {
return t.WithTx(t.Tx).Table("goadmin_user_permissions").
Where("user_id", "=", t.Id).
Delete()
}
// AddPermission add a permission of the user model.
func (t UserModel) AddPermission(permissionId string) (int64, error) {
if permissionId != "" {
if !t.CheckPermissionById(permissionId) {
return t.WithTx(t.Tx).Table("goadmin_user_permissions").
Insert(dialect.H{
"permission_id": permissionId,
"user_id": t.Id,
})
}
}
return 0, nil
}
// MapToModel get the user model from given map.
func (t UserModel) MapToModel(m map[string]interface{}) UserModel {
t.Id, _ = m["id"].(int64)
t.Name, _ = m["name"].(string)
t.UserName, _ = m["username"].(string)
t.Password, _ = m["password"].(string)
t.Avatar, _ = m["avatar"].(string)
t.RememberToken, _ = m["remember_token"].(string)
t.CreatedAt, _ = m["created_at"].(string)
t.UpdatedAt, _ = m["updated_at"].(string)
return t
}