-
Notifications
You must be signed in to change notification settings - Fork 28
/
user_ext.go
239 lines (202 loc) · 5.26 KB
/
user_ext.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
package user
import (
"encoding/json"
"fmt"
"github.com/go-playground/validator/v10"
"github.com/infraboard/mcube/exception"
"github.com/infraboard/mcube/types/ftime"
"golang.org/x/crypto/bcrypt"
common "github.com/infraboard/keyauth/common/types"
)
const (
// DefaultExiresDays 默认多少天无登录系统就冻结该用户
DefaultExiresDays = 90
)
// use a single instance of Validate, it caches struct info
var (
validate = validator.New()
)
// New 实例
func New(req *CreateAccountRequest) (*User, error) {
if err := req.Validate(); err != nil {
return nil, exception.NewBadRequest(err.Error())
}
pass, err := NewHashedPassword(req.Password)
if err != nil {
return nil, exception.NewBadRequest(err.Error())
}
u := &User{
CreateAt: ftime.Now().Timestamp(),
UpdateAt: ftime.Now().Timestamp(),
Profile: req.Profile,
DepartmentId: req.DepartmentId,
Account: req.Account,
CreateType: req.CreateType,
Type: req.UserType,
ExpiresDays: req.ExpiresDays,
Description: req.Description,
HashedPassword: pass,
Status: &Status{
Locked: false,
},
}
if req.DepartmentId != "" && req.Profile != nil {
u.IsInitialized = true
}
return u, nil
}
// NewDefaultUser 实例
func NewDefaultUser() *User {
return &User{
Profile: NewProfile(),
Status: &Status{
Locked: false,
},
}
}
// Block 锁用户
func (u *User) Block(reason string) {
u.Status.Locked = true
u.Status.LockedReson = reason
u.Status.LockedTime = ftime.Now().Timestamp()
}
// Desensitize 关键数据脱敏
func (u *User) Desensitize() {
if u.HashedPassword != nil {
u.HashedPassword.Password = ""
u.HashedPassword.History = []string{}
}
return
}
// ChangePassword 修改用户密码
func (u *User) ChangePassword(old, new string, maxHistory uint, needReset bool) error {
// 确认旧密码
if err := u.HashedPassword.CheckPassword(old); err != nil {
return err
}
// 修改新密码
newPass, err := NewHashedPassword(new)
if err != nil {
return exception.NewBadRequest(err.Error())
}
u.HashedPassword.Update(newPass, maxHistory, needReset)
return nil
}
// HasDepartment todo
func (u *User) HasDepartment() bool {
return u.DepartmentId != ""
}
// NewProfile todo
func NewProfile() *Profile {
return &Profile{}
}
// ValidateInitialized 判断初始化数据是否准备好了
func (req *Profile) ValidateInitialized() error {
if req.Email != "" && req.Phone != "" {
return nil
}
return fmt.Errorf("email and phone required when initial")
}
// Patch todo
func (req *Profile) Patch(data *Profile) {
patchData, _ := json.Marshal(data)
json.Unmarshal(patchData, req)
}
// Validate 校验请求是否合法
func (req *CreateAccountRequest) Validate() error {
return validate.Struct(req)
}
// NewHashedPassword 生产hash后的密码对象
func NewHashedPassword(password string) (*Password, error) {
bytes, err := bcrypt.GenerateFromPassword([]byte(password), 10)
if err != nil {
return nil, err
}
return &Password{
Password: string(bytes),
CreateAt: ftime.Now().Timestamp(),
UpdateAt: ftime.Now().Timestamp(),
}, nil
}
// SetExpired 密码过期
func (p *Password) SetExpired() {
p.IsExpired = true
}
// SetNeedReset 需要被重置
func (p *Password) SetNeedReset(format string, a ...interface{}) {
p.NeedReset = true
p.ResetReason = fmt.Sprintf(format, a...)
}
// CheckPassword 判断password 是否正确
func (p *Password) CheckPassword(password string) error {
err := bcrypt.CompareHashAndPassword([]byte(p.Password), []byte(password))
if err != nil {
return exception.NewUnauthorized("user or password not connrect")
}
return nil
}
// IsHistory 检测是否是历史密码
func (p *Password) IsHistory(password string) bool {
for _, pass := range p.History {
err := bcrypt.CompareHashAndPassword([]byte(pass), []byte(password))
if err == nil {
return true
}
}
return false
}
// HistoryCount 保存了几个历史密码
func (p *Password) HistoryCount() int {
return len(p.History)
}
func (p *Password) rotaryHistory(maxHistory uint) {
if uint(p.HistoryCount()) < maxHistory {
p.History = append(p.History, p.Password)
} else {
remainHistry := p.History[:maxHistory]
p.History = []string{p.Password}
p.History = append(p.History, remainHistry...)
}
}
// Update 更新密码
func (p *Password) Update(new *Password, maxHistory uint, needReset bool) {
p.rotaryHistory(maxHistory)
p.Password = new.Password
p.NeedReset = needReset
p.UpdateAt = ftime.Now().Timestamp()
if !needReset {
p.ResetReason = ""
}
}
// NewUserSet 实例
func NewUserSet() *Set {
return &Set{
Items: []*User{},
}
}
// Add todo
func (s *Set) Add(u *User) {
s.Items = append(s.Items, u)
}
// NewPutAccountRequest todo
func NewPutAccountRequest() *UpdateAccountRequest {
return &UpdateAccountRequest{
UpdateMode: common.UpdateMode_PUT,
Profile: NewProfile(),
}
}
// NewPatchAccountRequest todo
func NewPatchAccountRequest() *UpdateAccountRequest {
return &UpdateAccountRequest{
UpdateMode: common.UpdateMode_PATCH,
Profile: NewProfile(),
}
}
// Validate 更新请求校验
func (req *UpdateAccountRequest) Validate() error {
// 用户初始化要判断初始化信息填写完整
// if err := req.ValidateInitialized(); req.IsInitialized && err != nil {
// return err
// }
return validate.Struct(req)
}