-
Notifications
You must be signed in to change notification settings - Fork 2
/
user.go
488 lines (448 loc) · 14.4 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
package models
import (
"context"
"encoding/json"
"errors"
"fmt"
"log/slog"
"net/http"
"strings"
larkauthen "github.com/larksuite/oapi-sdk-go/v3/service/authen/v1"
"golang.org/x/oauth2"
"github.com/gin-gonic/gin"
corePKG "github.com/mss-boot-io/mss-boot/pkg"
"github.com/mss-boot-io/mss-boot/pkg/config/gormdb"
"github.com/mss-boot-io/mss-boot/pkg/enum"
"github.com/mss-boot-io/mss-boot/pkg/security"
"gorm.io/gorm"
"gorm.io/gorm/schema"
"github.com/mss-boot-io/mss-boot-admin/center"
"github.com/mss-boot-io/mss-boot-admin/pkg"
)
/*
* @Author: lwnmengjing<lwnmengjing@qq.com>
* @Date: 2023/8/6 22:02:39
* @Last Modified by: lwnmengjing<lwnmengjing@qq.com>
* @Last Modified time: 2023/8/6 22:02:39
*/
type User struct {
ModelGormTenant
UserLogin `json:",inline"`
Name string `json:"name" gorm:"column:name;type:varchar(100)"`
Avatar string `json:"avatar" gorm:"column:avatar;type:varchar(255)"`
Signature string `json:"signature" gorm:"column:signature;type:varchar(255)"`
Title string `json:"title" gorm:"column:title;type:varchar(100)"`
Group string `json:"group" gorm:"column:group;type:varchar(255)"`
Country string `json:"country" gorm:"column:country;type:varchar(20)"`
Province string `json:"province" gorm:"column:province;type:varchar(20)"`
City string `json:"city" gorm:"column:city;type:varchar(20)"`
Address string `json:"address" gorm:"column:address;type:varchar(255)"`
Phone string `json:"phone" gorm:"column:phone;type:varchar(20)"`
Profile string `json:"profile" gorm:"column:profile;type:bytes"`
Tags ArrayString `json:"tags" swaggertype:"array,string" gorm:"type:text"`
Permissions map[string]bool `json:"permissions" gorm:"-"`
}
type Tag struct {
Key string `json:"key"`
Label string `json:"label"`
}
func (e *User) BeforeCreate(tx *gorm.DB) error {
err := e.ModelGormTenant.BeforeCreate(tx)
if err != nil {
return err
}
e.Salt = security.GenerateRandomKey6()
hash, err := security.SetPassword(e.Password, e.Salt)
if err != nil {
return err
}
e.PasswordHash = hash
return err
}
func (e *User) BeforeSave(*gorm.DB) error {
//todo 判断密码强度
return nil
}
func (*User) TableName() string {
return "mss_boot_users"
}
func (e *User) GetUserID() string {
return e.ID
}
// PasswordReset reset password
func PasswordReset(ctx context.Context, userID string, password string) error {
user := &User{}
err := gormdb.DB.WithContext(ctx).First(user, "id = ?", userID).Error
if err != nil {
return err
}
user.Salt = security.GenerateRandomKey6()
hash, err := security.SetPassword(password, user.Salt)
if err != nil {
return err
}
err = gormdb.DB.Model(user).Updates(User{
UserLogin: UserLogin{
PasswordHash: hash,
Salt: user.Salt,
},
}).Error
if err != nil {
return err
}
return nil
}
// GetUserByUsername get user by username
func GetUserByUsername(username string) (*User, error) {
var user User
err := gormdb.DB.Model(&user).Preload("Role").First(&user, "username = ?", username).Error
if err != nil {
return nil, err
}
return &user, nil
}
type UserLogin struct {
RoleID string `json:"roleID" gorm:"index;type:varchar(64)" swaggerignore:"true"`
Role *Role `json:"role" gorm:"foreignKey:RoleID;references:ID"`
PostID string `json:"postID" gorm:"index;type:varchar(64)" swaggerignore:"true"`
Post *Post `json:"post" gorm:"foreignKey:PostID;references:ID"`
DepartmentID string `json:"departmentID" gorm:"index;type:varchar(64)" swaggerignore:"true"`
Department *Department `json:"department" gorm:"foreignKey:DepartmentID;references:ID"`
Username string `json:"username" gorm:"type:varchar(20);uniqueIndex"`
Email string `json:"email" gorm:"type:varchar(100);uniqueIndex"`
Password string `json:"password,omitempty" gorm:"-"`
PasswordHash string `json:"-" gorm:"size:255;comment:密码hash" swaggerignore:"true"`
PasswordStrength string `json:"passwordStrength" gorm:"size:20;comment:密码强度"`
Salt string `json:"-" gorm:"size:255;comment:加盐" swaggerignore:"true"`
Status enum.Status `json:"status" gorm:"size:10"`
OAuth2 []*UserOAuth2 `json:"oauth2" gorm:"foreignKey:UserID;references:ID"`
Provider pkg.OAuth2Provider `json:"type" gorm:"-"`
}
func (e *UserLogin) TableName() string {
return "mss_boot_users"
}
func (e *UserLogin) GetUserID() string {
return e.Username
}
func (e *UserLogin) GetTenantID() string {
if e.Role == nil {
return ""
}
return e.Role.TenantID
}
func (e *UserLogin) GetRoleID() string {
return e.RoleID
}
func (e *UserLogin) GetEmail() string {
return e.Email
}
func (e *UserLogin) GetUsername() string {
return e.Username
}
func (e *UserLogin) Root() bool {
if e.Role == nil {
return false
}
return e.Role.Root
}
// Verify verify password
func (e *UserLogin) Verify(ctx context.Context) (bool, security.Verifier, error) {
c := ctx.(*gin.Context)
defaultRole := &Role{Default: true}
_ = center.GetDB(ctx.(*gin.Context), &Role{}).Where(*defaultRole).First(defaultRole).Error
switch e.Provider {
case pkg.OAuth2GithubProvider:
// get user from github, then add user to db
// github user
clientID, _ := center.GetAppConfig().GetAppConfig(c, "security.githubClientId")
clientSecret, _ := center.GetAppConfig().GetAppConfig(c, "security.githubClientSecret")
redirectURL, _ := center.GetAppConfig().GetAppConfig(c, "security.githubRedirectUrl")
scope, _ := center.GetAppConfig().GetAppConfig(c, "security.githubScope")
scopes := strings.Split(scope, ",")
allowGroup, _ := center.GetAppConfig().GetAppConfig(c, "security.githubAllowGroup")
allowGroups := strings.Split(allowGroup, ",")
conf := &oauth2.Config{
ClientID: clientID,
ClientSecret: clientSecret,
Scopes: scopes,
RedirectURL: redirectURL,
Endpoint: oauth2.Endpoint{
AuthURL: "https://github.com/login/oauth/authorize",
TokenURL: "https://github.com/login/oauth/access_token",
},
}
githubUser, err := pkg.GetUserFromGithub(ctx, conf, e.Password)
if err != nil {
slog.Error("get user from github error", slog.Any("error", err))
return false, nil, err
}
if len(allowGroups) > 0 {
org, err := pkg.GetOrganizationsFromGithub(ctx, conf, e.Password)
if err != nil {
slog.Error("get organizations from github error", slog.Any("error", err))
return false, nil, err
}
if !pkg.InArray(allowGroups, org, "", 0) {
err = errors.New("user not in allow group")
slog.Error(err.Error())
return false, nil, err
}
}
// get user from db
userOAuth2 := &UserOAuth2{}
err = center.GetDB(ctx.(*gin.Context), &UserOAuth2{}).Preload("User.Role").First(userOAuth2, "open_id = ?", fmt.Sprintf("%d", githubUser.ID)).Error
if err != nil {
if !errors.Is(err, gorm.ErrRecordNotFound) {
slog.Error("get user from db error", slog.Any("error", err))
return false, nil, err
}
err = nil
userOAuth2 = &UserOAuth2{
OpenID: fmt.Sprintf("%d", githubUser.ID),
Sub: "github",
Name: githubUser.Login,
Email: githubUser.Email,
Profile: githubUser.Blog,
Picture: githubUser.AvatarURL,
NickName: githubUser.Login,
Website: githubUser.HTMLURL,
EmailVerified: true,
Locale: githubUser.Location,
Provider: pkg.OAuth2GithubProvider,
User: &User{
UserLogin: UserLogin{
RoleID: defaultRole.ID,
Username: githubUser.Email,
Email: githubUser.Email,
Password: e.Password,
Provider: pkg.OAuth2GithubProvider,
Status: enum.Enabled,
},
Name: githubUser.Login,
Avatar: githubUser.AvatarURL,
//Organization: githubUser.Company,
//Location: githubUser.Location,
//Introduction: githubUser.Bio,
Profile: githubUser.Blog,
//Verified: true,
//AccountID: fmt.Sprintf("%d", githubUser.ID),
},
}
// register user
err = center.GetDB(ctx.(*gin.Context), &User{}).Create(userOAuth2).Error
if err != nil {
slog.Error("create user error", slog.Any("error", err))
return false, nil, err
}
userOAuth2.User.Role = defaultRole
}
return true, userOAuth2.User, nil
case pkg.OAuth2LarkProvider:
client := http.Client{}
req, err := http.NewRequest(http.MethodGet, "https://open.larksuite.com/open-apis/authen/v1/user_info", nil)
if err != nil {
slog.Error("new request error", slog.Any("error", err))
return false, nil, err
}
req.Header.Add("Authorization", "Bearer "+e.Password)
resp, err := client.Do(req)
if err != nil {
slog.Error("do request error", slog.Any("error", err))
return false, nil, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
err = errors.New("get user from lark error")
slog.Error(err.Error())
return false, nil, err
}
result := &larkauthen.GetUserInfoResp{}
err = json.NewDecoder(resp.Body).Decode(result)
if err != nil {
slog.Error("decode response error", slog.Any("error", err))
return false, nil, err
}
userOAuth2 := &UserOAuth2{}
err = center.GetDB(ctx.(*gin.Context), &UserOAuth2{}).
Preload("User.Role").
First(userOAuth2, "union_id = ?", result.Data.UnionId).Error
if err != nil {
if !errors.Is(err, gorm.ErrRecordNotFound) {
slog.Error("get user from db error", slog.Any("error", err))
return false, nil, err
}
err = nil
email := ""
if result.Data.EnterpriseEmail != nil {
email = *result.Data.EnterpriseEmail
}
if email == "" && result.Data.Email != nil {
email = *result.Data.Email
}
userOAuth2 = &UserOAuth2{
UnionID: *result.Data.UnionId,
OpenID: *result.Data.OpenId,
Sub: *result.Data.TenantKey,
Name: *result.Data.Name,
Email: email,
Picture: *result.Data.AvatarUrl,
NickName: *result.Data.Name,
EmailVerified: email != "",
Provider: pkg.OAuth2LarkProvider,
User: &User{
UserLogin: UserLogin{
RoleID: defaultRole.ID,
Username: *result.Data.UserId,
Email: email,
Password: e.Password,
Provider: pkg.OAuth2LarkProvider,
Status: enum.Enabled,
},
Name: *result.Data.Name,
Avatar: *result.Data.AvatarUrl,
},
}
if result.Data.Mobile != nil {
userOAuth2.PhoneNumber = *result.Data.Mobile
}
if result.Data.EmployeeNo != nil {
userOAuth2.EmployeeNO = *result.Data.EmployeeNo
}
// register user
err = center.GetDB(c, &User{}).Create(userOAuth2).Error
if err != nil {
slog.Error("create user error", slog.Any("error", err))
return false, nil, err
}
userOAuth2.User.Role = defaultRole
}
return true, userOAuth2.User, nil
}
// username and password
user, err := GetUserByUsername(e.Username)
if err != nil {
return false, nil, err
}
verify, err := security.SetPassword(e.Password, user.Salt)
if err != nil {
return false, nil, err
}
return verify == user.PasswordHash, user, nil
}
func (e *UserLogin) GetDepartmentUserID(tx *gorm.DB) []string {
ids := make([]string, 0)
tx.Model(&User{}).
Where("department_id = ?", e.DepartmentID).Pluck("id", &ids)
return ids
}
func (e *UserLogin) GetDepartmentAndChildrenUserID(tx *gorm.DB) []string {
ids := make([]string, 0)
deptIDS := e.Department.GetAllChildrenID(tx)
tx.Model(&User{}).
Where("department_id in ?", deptIDS).Pluck("id", &ids)
return ids
}
func (e *UserLogin) GetCustomDepartmentUserID(tx *gorm.DB) []string {
ids := make([]string, 0)
tx.Model(&User{}).Where("department_id in ?", e.Post.DeptIDSArr).Pluck("id", &ids)
return ids
}
func (e *UserLogin) GetPostUserID(tx *gorm.DB) []string {
ids := make([]string, 0)
tx.Model(&User{}).Where("post_id = ?", e.PostID).Pluck("id", &ids)
return ids
}
func (e *UserLogin) GetPostAndChildrenUserID(tx *gorm.DB) []string {
ids := make([]string, 0)
postIDS := e.Post.GetChildrenID(tx)
tx.Model(&User{}).Where("post_id in ?", postIDS).Pluck("id", &ids)
return ids
}
func (e *UserLogin) GetPostAndAllChildrenUserID(tx *gorm.DB) []string {
ids := make([]string, 0)
postIDS := e.Post.GetAllChildrenID(tx)
postIDS = append(postIDS, e.PostID)
tx.Model(&User{}).Where("post_id in ?", postIDS).Pluck("id", &ids)
return ids
}
func (e *UserLogin) getDataScopeCreator(ctx context.Context) []string {
// get user from db
if e.Post == nil {
return nil
}
ids := make([]string, 0)
tx := center.GetDB(ctx.(*gin.Context), &User{})
switch e.Post.DataScope {
case DataScopeAll:
return nil
case DataScopeCurrentDept:
return e.GetDepartmentUserID(tx)
case DataScopeCurrentAndChildrenDept:
return e.GetDepartmentAndChildrenUserID(tx)
case DataScopeCustomDept:
return e.GetCustomDepartmentUserID(tx)
case DataScopeSelf:
return append(ids, e.GetUserID())
case DataScopeSelfAndChildren:
return e.GetPostAndChildrenUserID(tx)
case DataScopeSelfAndAllChildren:
return e.GetPostAndAllChildrenUserID(tx)
}
return nil
}
func (e *UserLogin) Scope(ctx *gin.Context, table schema.Tabler) func(db *gorm.DB) *gorm.DB {
return func(db *gorm.DB) *gorm.DB {
if !corePKG.SupportCreator(table) {
return db
}
ids := e.getDataScopeCreator(ctx)
if len(ids) == 0 {
return db
}
db = db.Where("creator_id in ?", ids)
return db
}
}
// ********************* statistics *********************
func (e *User) AfterCreate(tx *gorm.DB) error {
ctx, ok := tx.Statement.Context.(*gin.Context)
if !ok {
return nil
}
_ = center.Default.NowIncrease(ctx, e)
return nil
}
func (e *User) AfterDelete(tx *gorm.DB) error {
ctx, ok := tx.Statement.Context.(*gin.Context)
if !ok {
return nil
}
_ = center.Default.NowReduce(ctx, e)
return nil
}
// StatisticsName statistics name
func (*User) StatisticsName() string {
return "user-total"
}
// StatisticsType statistics type
func (*User) StatisticsType() string {
return "user"
}
// StatisticsTime statistics time
func (*User) StatisticsTime() string {
return pkg.NowFormatDay()
}
func (*User) StatisticsStep() int {
return 100
}
// StatisticsCalibrate statistics calibrate
func (e *User) StatisticsCalibrate() (int, error) {
var count int64
err := gormdb.DB.Model(e).
Count(&count).Error
if err != nil {
return 0, err
}
return int(count), nil
}
// ********************* statistics *********************