forked from leanote/leanote
/
UserService.go
520 lines (447 loc) · 14.8 KB
/
UserService.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
508
509
510
511
512
513
514
515
516
517
518
519
520
package service
import (
"github.com/JacobXie/leanote/app/db"
"github.com/JacobXie/leanote/app/info"
. "github.com/JacobXie/leanote/app/lea"
"gopkg.in/mgo.v2/bson"
"strings"
"time"
)
type UserService struct {
}
// 自增Usn
// 每次notebook,note添加, 修改, 删除, 都要修改
func (this *UserService) IncrUsn(userId string) int {
user := info.User{}
query := bson.M{"_id": bson.ObjectIdHex(userId)}
db.GetByQWithFields(db.Users, query, []string{"Usn"}, &user)
usn := user.Usn
usn += 1
Log("inc Usn")
db.UpdateByQField(db.Users, query, "Usn", usn)
return usn
// return db.Update(db.Notes, bson.M{"_id": bson.ObjectIdHex(noteId)}, bson.M{"$inc": bson.M{"ReadNum": 1}})
}
func (this *UserService) GetUsn(userId string) int {
user := info.User{}
query := bson.M{"_id": bson.ObjectIdHex(userId)}
db.GetByQWithFields(db.Users, query, []string{"Usn"}, &user)
return user.Usn
}
// 添加用户
func (this *UserService) AddUser(user info.User) bool {
if user.UserId == "" {
user.UserId = bson.NewObjectId()
}
user.CreatedTime = time.Now()
if user.Email != "" {
user.Email = strings.ToLower(user.Email)
// 发送验证邮箱
go func() {
emailService.RegisterSendActiveEmail(user, user.Email)
// 发送给我 life@leanote.com
emailService.SendEmail("life@leanote.com", "新增用户", "{header}用户名"+user.Email+"{footer}")
}()
}
return db.Insert(db.Users, user)
}
// 通过email得到userId
func (this *UserService) GetUserId(email string) string {
email = strings.ToLower(email)
user := info.User{}
db.GetByQ(db.Users, bson.M{"Email": email}, &user)
return user.UserId.Hex()
}
// 得到用户名
func (this *UserService) GetUsername(userId string) string {
user := info.User{}
db.GetByQWithFields(db.Users, bson.M{"_id": bson.ObjectIdHex(userId)}, []string{"Username"}, &user)
return user.Username
}
// 得到用户名
func (this *UserService) GetUsernameById(userId bson.ObjectId) string {
user := info.User{}
db.GetByQWithFields(db.Users, bson.M{"_id": userId}, []string{"Username"}, &user)
return user.Username
}
// 是否存在该用户 email
func (this *UserService) IsExistsUser(email string) bool {
if this.GetUserId(email) == "" {
return false
}
return true
}
// 是否存在该用户 username
func (this *UserService) IsExistsUserByUsername(username string) bool {
return db.Count(db.Users, bson.M{"Username": username}) >= 1
}
// 得到用户信息, userId, username, email
func (this *UserService) GetUserInfoByAny(idEmailUsername string) info.User {
if IsObjectId(idEmailUsername) {
return this.GetUserInfo(idEmailUsername)
}
if strings.Contains(idEmailUsername, "@") {
return this.GetUserInfoByEmail(idEmailUsername)
}
// username
return this.GetUserInfoByUsername(idEmailUsername)
}
func (this *UserService) setUserLogo(user *info.User) {
// Logo路径问题, 有些有http: 有些没有
if user.Logo == "" {
user.Logo = "images/blog/default_avatar.png"
}
if user.Logo != "" && !strings.HasPrefix(user.Logo, "http") {
user.Logo = strings.Trim(user.Logo, "/")
user.Logo = configService.GetSiteUrl() + "/" + user.Logo
}
}
// 仅得到用户
func (this *UserService) GetUser(userId string) info.User {
user := info.User{}
db.Get(db.Users, userId, &user)
return user
}
// 得到用户信息 userId
func (this *UserService) GetUserInfo(userId string) info.User {
user := info.User{}
db.Get(db.Users, userId, &user)
// Logo路径问题, 有些有http: 有些没有
this.setUserLogo(&user)
return user
}
// 得到用户信息 email
func (this *UserService) GetUserInfoByEmail(email string) info.User {
user := info.User{}
db.GetByQ(db.Users, bson.M{"Email": email}, &user)
// Logo路径问题, 有些有http: 有些没有
this.setUserLogo(&user)
return user
}
// 得到用户信息 username
func (this *UserService) GetUserInfoByUsername(username string) info.User {
user := info.User{}
username = strings.ToLower(username)
db.GetByQ(db.Users, bson.M{"Username": username}, &user)
// Logo路径问题, 有些有http: 有些没有
this.setUserLogo(&user)
return user
}
func (this *UserService) GetUserInfoByThirdUserId(thirdUserId string) info.User {
user := info.User{}
db.GetByQ(db.Users, bson.M{"ThirdUserId": thirdUserId}, &user)
this.setUserLogo(&user)
return user
}
func (this *UserService) ListUserInfosByUserIds(userIds []bson.ObjectId) []info.User {
users := []info.User{}
db.ListByQ(db.Users, bson.M{"_id": bson.M{"$in": userIds}}, &users)
return users
}
func (this *UserService) ListUserInfosByEmails(emails []string) []info.User {
users := []info.User{}
db.ListByQ(db.Users, bson.M{"Email": bson.M{"$in": emails}}, &users)
return users
}
// 用户信息即可
func (this *UserService) MapUserInfoByUserIds(userIds []bson.ObjectId) map[bson.ObjectId]info.User {
users := []info.User{}
db.ListByQ(db.Users, bson.M{"_id": bson.M{"$in": userIds}}, &users)
userMap := make(map[bson.ObjectId]info.User, len(users))
for _, user := range users {
this.setUserLogo(&user)
userMap[user.UserId] = user
}
return userMap
}
// 用户信息和博客设置信息
func (this *UserService) MapUserInfoAndBlogInfosByUserIds(userIds []bson.ObjectId) map[bson.ObjectId]info.User {
return this.MapUserInfoByUserIds(userIds)
}
// 返回info.UserAndBlog
func (this *UserService) MapUserAndBlogByUserIds(userIds []bson.ObjectId) map[string]info.UserAndBlog {
users := []info.User{}
db.ListByQ(db.Users, bson.M{"_id": bson.M{"$in": userIds}}, &users)
userBlogs := []info.UserBlog{}
db.ListByQ(db.UserBlogs, bson.M{"_id": bson.M{"$in": userIds}}, &userBlogs)
userBlogMap := make(map[bson.ObjectId]info.UserBlog, len(userBlogs))
for _, user := range userBlogs {
userBlogMap[user.UserId] = user
}
userAndBlogMap := make(map[string]info.UserAndBlog, len(users))
for _, user := range users {
this.setUserLogo(&user)
userBlog, ok := userBlogMap[user.UserId]
if !ok {
continue
}
userAndBlogMap[user.UserId.Hex()] = info.UserAndBlog{
UserId: user.UserId,
Username: user.Username,
Email: user.Email,
Logo: user.Logo,
BlogTitle: userBlog.Title,
BlogLogo: userBlog.Logo,
BlogUrl: blogService.GetUserBlogUrl(&userBlog, user.Username),
}
}
return userAndBlogMap
}
// 得到用户信息+博客主页
func (this *UserService) GetUserAndBlogUrl(userId string) info.UserAndBlogUrl {
user := this.GetUserInfo(userId)
userBlog := blogService.GetUserBlog(userId)
blogUrls := blogService.GetBlogUrls(&userBlog, &user)
return info.UserAndBlogUrl{
User: user,
BlogUrl: blogUrls.IndexUrl,
PostUrl: blogUrls.PostUrl,
}
}
// 得到userAndBlog公开信息
func (this *UserService) GetUserAndBlog(userId string) info.UserAndBlog {
user := this.GetUserInfo(userId)
userBlog := blogService.GetUserBlog(userId)
return info.UserAndBlog{
UserId: user.UserId,
Username: user.Username,
Email: user.Email,
Logo: user.Logo,
BlogTitle: userBlog.Title,
BlogLogo: userBlog.Logo,
BlogUrl: blogService.GetUserBlogUrl(&userBlog, user.Username),
BlogUrls: blogService.GetBlogUrls(&userBlog, &user),
}
}
// 通过ids得到users, 按id的顺序组织users
func (this *UserService) GetUserInfosOrderBySeq(userIds []bson.ObjectId) []info.User {
users := []info.User{}
db.ListByQ(db.Users, bson.M{"_id": bson.M{"$in": userIds}}, &users)
usersMap := map[bson.ObjectId]info.User{}
for _, user := range users {
usersMap[user.UserId] = user
}
hasAppend := map[bson.ObjectId]bool{} // 为了防止userIds有重复的
users2 := []info.User{}
for _, userId := range userIds {
if user, ok := usersMap[userId]; ok && !hasAppend[userId] {
hasAppend[userId] = true
users2 = append(users2, user)
}
}
return users2
}
// 使用email(username), 得到用户信息
func (this *UserService) GetUserInfoByName(emailOrUsername string) info.User {
emailOrUsername = strings.ToLower(emailOrUsername)
user := info.User{}
if strings.Contains(emailOrUsername, "@") {
db.GetByQ(db.Users, bson.M{"Email": emailOrUsername}, &user)
} else {
db.GetByQ(db.Users, bson.M{"Username": emailOrUsername}, &user)
}
this.setUserLogo(&user)
return user
}
// 更新username
func (this *UserService) UpdateUsername(userId, username string) (bool, string) {
//modified by JacobXie
if userId == configService.adminUserId{//admin 不能修改用户名
return false, "admin is not permitted for midification"
}
usernameRaw := username // 原先的, 可能是同一个, 但有大小写
username = strings.ToLower(username)
if userId == "" || username == "" || username == "admin" { // admin用户是内置的, 不能设置
return false, "usernameIsExisted"
}
// 先判断是否存在
userIdO := bson.ObjectIdHex(userId)
if db.Has(db.Users, bson.M{"Username": username, "_id": bson.M{"$ne": userIdO}}) {
return false, "usernameIsExisted"
}
ok := db.UpdateByQMap(db.Users, bson.M{"_id": userIdO}, bson.M{"Username": username, "UsernameRaw": usernameRaw})
return ok, ""
}
// 修改头像
func (this *UserService) UpdateAvatar(userId, avatarPath string) bool {
userIdO := bson.ObjectIdHex(userId)
return db.UpdateByQField(db.Users, bson.M{"_id": userIdO}, "Logo", avatarPath)
}
//----------------------
// 已经登录了的用户修改密码
func (this *UserService) UpdatePwd(userId, oldPwd, pwd string) (bool, string) {
userInfo := this.GetUserInfo(userId)
if !ComparePwd(oldPwd, userInfo.Pwd) {
return false, "oldPasswordError"
}
passwd := GenPwd(pwd)
if passwd == "" {
return false, "GenerateHash error"
}
ok := db.UpdateByQField(db.Users, bson.M{"_id": bson.ObjectIdHex(userId)}, "Pwd", passwd)
return ok, ""
}
// 管理员重置密码
func (this *UserService) ResetPwd(adminUserId, userId, pwd string) (ok bool, msg string) {
if configService.GetAdminUserId() != adminUserId {
return
}
passwd := GenPwd(pwd)
if passwd == "" {
return false, "GenerateHash error"
}
ok = db.UpdateByQField(db.Users, bson.M{"_id": bson.ObjectIdHex(userId)}, "Pwd", passwd)
return
}
// 修改主题
func (this *UserService) UpdateTheme(userId, theme string) bool {
ok := db.UpdateByQField(db.Users, bson.M{"_id": bson.ObjectIdHex(userId)}, "Theme", theme)
return ok
}
// 帐户类型设置
func (this *UserService) UpdateAccount(userId, accountType string, accountStartTime, accountEndTime time.Time,
maxImageNum, maxImageSize, maxAttachNum, maxAttachSize, maxPerAttachSize int) bool {
return db.UpdateByQI(db.Users, bson.M{"_id": bson.ObjectIdHex(userId)}, info.UserAccount{
AccountType: accountType,
AccountStartTime: accountStartTime,
AccountEndTime: accountEndTime,
MaxImageNum: maxImageNum,
MaxImageSize: maxImageSize,
MaxAttachNum: maxAttachNum,
MaxAttachSize: maxAttachSize,
MaxPerAttachSize: maxPerAttachSize,
})
}
//---------------
// 修改email
// 注册后验证邮箱
func (this *UserService) ActiveEmail(token string) (ok bool, msg, email string) {
tokenInfo := info.Token{}
if ok, msg, tokenInfo = tokenService.VerifyToken(token, info.TokenActiveEmail); ok {
// 修改之后的邮箱
email = tokenInfo.Email
userInfo := this.GetUserInfoByEmail(email)
if userInfo.UserId == "" {
ok = false
msg = "不存在该用户"
return
}
// 修改之, 并将verified = true
ok = db.UpdateByQMap(db.Users, bson.M{"_id": userInfo.UserId}, bson.M{"Verified": true})
return
}
ok = false
msg = "该链接已过期"
return
}
// 修改邮箱
// 在此之前, 验证token是否过期
// 验证email是否有人注册了
func (this *UserService) UpdateEmail(token string) (ok bool, msg, email string) {
tokenInfo := info.Token{}
if ok, msg, tokenInfo = tokenService.VerifyToken(token, info.TokenUpdateEmail); ok {
// 修改之后的邮箱
email = strings.ToLower(tokenInfo.Email)
// 先验证该email是否被注册了
if userService.IsExistsUser(email) {
ok = false
msg = "该邮箱已注册"
return
}
// 修改之, 并将verified = true
ok = db.UpdateByQMap(db.Users, bson.M{"_id": tokenInfo.UserId}, bson.M{"Email": email, "Verified": true})
return
}
ok = false
msg = "该链接已过期"
return
}
//---------
// 第三方添加账号
func (this *UserService) ThirdAddUser(userId, email, pwd string) (ok bool, msg string) {
// 判断该用户是否已有了帐户
userInfo := this.GetUserInfo(userId)
if userInfo.Email != "" {
msg = "你已有帐户"
return
}
// 判断email是否存在
if this.IsExistsUser(email) {
msg = "该用户已存在"
return
}
ok = db.UpdateByQMap(db.Users, bson.M{"_id": bson.ObjectIdHex(userId)}, bson.M{"Email": email, "Pwd": Md5(pwd)})
return
}
//------------
// 偏好设置
// 宽度
func (this *UserService) UpdateColumnWidth(userId string, notebookWidth, noteListWidth, mdEditorWidth int) bool {
return db.UpdateByQMap(db.Users, bson.M{"_id": bson.ObjectIdHex(userId)},
bson.M{"NotebookWidth": notebookWidth, "NoteListWidth": noteListWidth, "MdEditorWidth": mdEditorWidth})
}
// 左侧是否隐藏
func (this *UserService) UpdateLeftIsMin(userId string, leftIsMin bool) bool {
return db.UpdateByQMap(db.Users, bson.M{"_id": bson.ObjectIdHex(userId)}, bson.M{"LeftIsMin": leftIsMin})
}
//-------------
// user admin
func (this *UserService) ListUsers(pageNumber, pageSize int, sortField string, isAsc bool, email string) (page info.Page, users []info.User) {
users = []info.User{}
skipNum, sortFieldR := parsePageAndSort(pageNumber, pageSize, sortField, isAsc)
query := bson.M{}
if email != "" {
orQ := []bson.M{
bson.M{"Email": bson.M{"$regex": bson.RegEx{".*?" + email + ".*", "i"}}},
bson.M{"Username": bson.M{"$regex": bson.RegEx{".*?" + email + ".*", "i"}}},
}
query["$or"] = orQ
}
q := db.Users.Find(query)
// 总记录数
count, _ := q.Count()
// 列表
q.Sort(sortFieldR).
Skip(skipNum).
Limit(pageSize).
All(&users)
page = info.NewPage(pageNumber, pageSize, count, nil)
return
}
func (this *UserService) GetAllUserByFilter(userFilterEmail, userFilterWhiteList, userFilterBlackList string, verified bool) []info.User {
query := bson.M{}
if verified {
query["Verified"] = true
}
orQ := []bson.M{}
if userFilterEmail != "" {
orQ = append(orQ, bson.M{"Email": bson.M{"$regex": bson.RegEx{".*?" + userFilterEmail + ".*", "i"}}},
bson.M{"Username": bson.M{"$regex": bson.RegEx{".*?" + userFilterEmail + ".*", "i"}}},
)
}
if userFilterWhiteList != "" {
userFilterWhiteList = strings.Replace(userFilterWhiteList, "\r", "", -1)
emails := strings.Split(userFilterWhiteList, "\n")
orQ = append(orQ, bson.M{"Email": bson.M{"$in": emails}})
}
if len(orQ) > 0 {
query["$or"] = orQ
}
emailQ := bson.M{}
if userFilterBlackList != "" {
userFilterWhiteList = strings.Replace(userFilterBlackList, "\r", "", -1)
bEmails := strings.Split(userFilterBlackList, "\n")
emailQ["$nin"] = bEmails
query["Email"] = emailQ
}
LogJ(query)
users := []info.User{}
q := db.Users.Find(query)
q.All(&users)
Log(len(users))
return users
}
// 统计
func (this *UserService) CountUser() int {
return db.Count(db.Users, bson.M{})
}