service.go
27.0 KB
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
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
package service
import (
"github.com/GeeTeam/gt3-golang-sdk/geetest"
"github.com/google/uuid"
"github.com/linmadan/egglib-go/utils/json"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-gateway/pkg/application/auth/dto"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-gateway/pkg/application/auth/query"
"time"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-gateway/pkg/log"
"github.com/linmadan/egglib-go/core/application"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-gateway/pkg/application/auth/command"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-gateway/pkg/application/factory"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-gateway/pkg/domain"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-gateway/pkg/infrastructure/cache"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-gateway/pkg/infrastructure/service_gateway/allied_creation_user"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-gateway/pkg/infrastructure/service_gateway/sms_serve"
)
const (
captchaID = "33a2abf9c5df0d6bc3b89fb39280114b"
privateKey = "13320fd2b10199e9a2440a4fbb4d46f7"
)
// 组织管理
type AuthService struct {
}
//AuthLogin 用户登录
func (svr AuthService) AuthLogin(loginCommand *command.LoginCommand) (interface{}, error) {
var (
authCode string
result interface{}
err error
loginPlatform string = domain.LoginPlatformApp
)
if loginCommand.DeviceType == domain.DeviceTypeWeb {
loginPlatform = domain.LoginPlatformWeb
}
creationUserGateway := allied_creation_user.NewHttplibAlliedCreationUser(domain.Operator{})
_, err = creationUserGateway.AuthRefreshIM(allied_creation_user.ReqAuthRefreshIM{
Phone: loginCommand.Phone,
})
if err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
switch loginCommand.GrantType {
case domain.LoginPwd:
authCode, err = svr.SignInPassword(loginCommand.Phone, loginCommand.Password, loginPlatform)
case domain.LoginSmsCode:
authCode, err = svr.SignInCaptcha(loginCommand.Phone, loginCommand.Captcha, loginPlatform)
default:
err = application.ThrowError(application.TRANSACTION_ERROR, "登录方式无法解析")
}
if err != nil {
return nil, application.ThrowError(application.BUSINESS_ERROR, err.Error())
}
result, err = svr.GetAuthAccessToken(&command.AccessTokenCommand{
AuthCode: authCode,
SessionMode: loginCommand.SessionMode,
LoginPlatform: loginPlatform,
})
return map[string]interface{}{
"access": result,
}, err
}
//AuthLogin 用户登录
func (svr AuthService) AuthLoginPwd(loginCommand *command.LoginPwdCommand) (interface{}, error) {
if err := loginCommand.ValidateCommand(); err != nil {
return nil, application.ThrowError(application.ARG_ERROR, err.Error())
}
login := &command.LoginCommand{
GrantType: "signInPassword",
Phone: loginCommand.Username,
Password: loginCommand.Password,
SessionMode: loginCommand.SessionMode,
DeviceType: loginCommand.DeviceType,
}
if len(loginCommand.CaptchaChallenge) > 0 {
geetest := geetest.NewGeetestLib(captchaID, privateKey, 2*time.Second)
validateResult := geetest.SuccessValidate(loginCommand.CaptchaChallenge, loginCommand.CaptchaValidate, loginCommand.CaptchaSeccode, "", "")
if !validateResult {
log.Logger.Error("validate captcha fail")
}
}
return svr.AuthLogin(login)
}
//AuthLogin 用户登录
func (svr AuthService) AuthLoginSms(loginCommand *command.LoginSmsCommand) (interface{}, error) {
if err := loginCommand.ValidateCommand(); err != nil {
return nil, application.ThrowError(application.ARG_ERROR, err.Error())
}
login := &command.LoginCommand{
GrantType: "signInCaptcha",
Phone: loginCommand.Phone,
Captcha: loginCommand.Code,
SessionMode: loginCommand.SessionMode,
DeviceType: loginCommand.DeviceType,
}
return svr.AuthLogin(login)
}
//AuthLoginQrcode 扫码登录
func (svr AuthService) AuthLoginQrcode(queryParam *query.QrcodeLoginStatusQuery) (interface{}, error) {
qrmsg := domain.QrcodeMessage{}
failLoginData := map[string]interface{}{
"isLogin": false,
"access": struct{}{},
}
err := qrmsg.ParseToken(queryParam.Key)
if err != nil {
log.Logger.Error(err.Error())
return nil, application.ThrowError(application.TRANSACTION_ERROR, "二维码已失效")
}
qrCache := cache.LoginQrcodeCache{}
qrmsgCache, err := qrCache.Get(qrmsg.Id)
if err != nil {
log.Logger.Error(err.Error())
return nil, application.ThrowError(application.TRANSACTION_ERROR, "二维码已失效")
}
if !qrmsgCache.IsLogin {
return failLoginData, nil
}
loginToken := domain.LoginToken{
UserId: qrmsgCache.UserId,
UserBaseId: qrmsgCache.UserBaseId,
Account: qrmsgCache.Account,
Platform: domain.LoginPlatformWeb,
CompanyId: qrmsgCache.CompanyId,
OrgId: qrmsgCache.OrgId,
}
accessToken, err := loginToken.GenerateAccessToken()
if err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
qrCache.Remove(qrmsgCache.Id)
_ = accessToken
result, err := svr.getToken(loginToken)
data := map[string]interface{}{
"isLogin": qrmsgCache.IsLogin,
"access": result["token"],
}
return data, nil
}
//AuthLoginQrcodeBind 扫码登录-绑定
func (svr AuthService) AuthLoginQrcodeBinding(bindingCmd *command.QrcodeBindingCommand) (interface{}, error) {
qrmsg := domain.QrcodeMessage{}
err := qrmsg.ParseToken(bindingCmd.Key)
if err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, "您扫描的二维码无效,请确认后重新扫描")
}
qrCache := cache.LoginQrcodeCache{}
qrmsgCache, err := qrCache.Get(qrmsg.Id)
if err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, "您扫描的二维码无效,请确认后重新扫描")
}
if err := qrmsgCache.BindUser(bindingCmd.Operator); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
if err := qrCache.Save(*qrmsgCache); err != nil {
log.Logger.Error(err.Error())
return nil, application.ThrowError(application.TRANSACTION_ERROR, "登录失败,请重试")
}
return struct{}{}, nil
}
//SendSmsCaptcha 发送验证码短信
func (svr AuthService) SendSmsCaptcha(smsCodeCommand *command.SendSmsCodeCommand) error {
if err := smsCodeCommand.ValidateCommand(); err != nil {
return application.ThrowError(application.ARG_ERROR, err.Error())
}
if smsCodeCommand.Flag == 1 {
creationUserGateway := allied_creation_user.NewHttplibAlliedCreationUser(domain.Operator{})
userBase, err := creationUserGateway.AuthUserBaseInfo(allied_creation_user.ReqAuthUserBase{
Account: smsCodeCommand.Phone,
})
if err != nil || userBase.UserInfo.Phone != smsCodeCommand.Phone {
return application.ThrowError(application.TRANSACTION_ERROR, "输入的手机号不是平台用户,请重新输入")
}
}
smsServeGateway := sms_serve.NewHttplibHttplibSmsServe()
err := smsServeGateway.SendSms(smsCodeCommand.Phone)
if err != nil {
return application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
return nil
}
//SignInPassword 使用账号密码校验
func (svr AuthService) SignInPassword(account string, password string, loginPlatform string) (string, error) {
creationUserGateway := allied_creation_user.NewHttplibAlliedCreationUser(domain.Operator{})
_, err := creationUserGateway.AuthCheckPassword(allied_creation_user.ReqAuthCheckPassword{
Password: password,
Phone: account,
})
if err != nil {
return "", application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
loginToken := domain.LoginToken{
UserId: 0,
Account: account,
Platform: loginPlatform,
CompanyId: 0,
}
authCode, err := loginToken.GenerateAuthCode()
if err != nil {
return "", application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
return authCode, nil
}
//SignInCaptcha 使用手机验证码登录
func (svr AuthService) SignInCaptcha(phone string, captcha string, loginPlatform string) (string, error) {
smsServeGateway := sms_serve.NewHttplibHttplibSmsServe()
err := smsServeGateway.CheckSmsCode(phone, captcha)
if err != nil {
return "", application.ThrowError(application.BUSINESS_ERROR, err.Error())
}
loginToken := domain.LoginToken{
UserId: 0,
Account: phone,
Platform: loginPlatform,
CompanyId: 0,
}
authCode, err := loginToken.GenerateAuthCode()
if err != nil {
return "", application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
return authCode, nil
}
//GetAuthAccessToken 获取令牌Token
func (svr AuthService) GetAuthAccessToken(accessTokenCommand *command.AccessTokenCommand) (interface{}, error) {
if err := accessTokenCommand.ValidateCommand(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
loginToken := &domain.LoginToken{}
err := loginToken.ParseToken(accessTokenCommand.AuthCode)
if err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
loginToken.Platform = accessTokenCommand.LoginPlatform
loginToken.SessionMode = accessTokenCommand.SessionMode
result, err := svr.getToken(*loginToken)
return result["token"], err
}
func (svr AuthService) RefreshAuthAccessToken(refreshTokenCommand *command.RefreshTokenCommand) (interface{}, error) {
if err := refreshTokenCommand.ValidateCommand(); err != nil {
return nil, domain.NewApplicationError(domain.InvalidRefreshToken)
}
loginToken := domain.LoginToken{}
err := loginToken.ParseToken(refreshTokenCommand.RefreshToken)
if err != nil {
return nil, domain.NewApplicationError(domain.InvalidRefreshToken)
}
//redis缓存
tokenCache := cache.LoginTokenCache{}
refreshToken, err := tokenCache.GetRefreshToken(loginToken.Account, loginToken.Platform)
if err != nil {
log.Logger.Debug(err.Error())
return nil, domain.NewApplicationError(domain.InvalidRefreshToken)
}
if refreshToken != refreshTokenCommand.RefreshToken {
return nil, domain.NewApplicationError(domain.InvalidRefreshToken)
}
token, err := svr.getToken(loginToken)
if err != nil {
return nil, domain.NewApplicationError(domain.InvalidRefreshToken)
}
return map[string]interface{}{
"access": token["token"],
}, err
}
//GetUserMenus 获取用户信息
func (svr AuthService) GetUserInfo(userInfoCommand *command.UserInfoCommand) (interface{}, error) {
user, err := svr.getUserInfo(userInfoCommand.Operator)
if err != nil {
return nil, application.ThrowError(application.BUSINESS_ERROR, err.Error())
}
return map[string]interface{}{
"user": user,
}, nil
}
//GetUserMenus 获取用户信息-额外的数据
func (svr AuthService) GetFavoriteMenus(userInfoCommand *command.UserInfoCommand) (interface{}, error) {
creationUserGateway := allied_creation_user.NewHttplibAlliedCreationUser(
userInfoCommand.Operator)
resultUser, err := creationUserGateway.UserGet(allied_creation_user.ReqGetUser{
UserId: int(userInfoCommand.Operator.UserId),
})
if err != nil {
return nil, application.ThrowError(application.BUSINESS_ERROR, err.Error())
}
return map[string]interface{}{
"favoriteMenus": resultUser.FavoriteMenus,
}, nil
}
//GetUserMenus 获取用户菜单
func (svr AuthService) GetUserMenus(userMenusCommand *command.UserMenusCommand) (interface{}, error) {
if userMenusCommand.Operator.UserId == 0 {
return map[string]interface{}{
"accessMenus": struct{}{},
}, nil
}
creationUserGateway := allied_creation_user.NewHttplibAlliedCreationUser(
userMenusCommand.Operator)
resultMenu, err := creationUserGateway.UserAccessMenus(allied_creation_user.ReqUserAccessMenus{
UserId: int(userMenusCommand.Operator.UserId),
MenuCategory: userMenusCommand.MenuCategory,
ALLDisableMenu: userMenusCommand.ALLDisableMenu,
})
if err != nil {
return nil, application.ThrowError(application.BUSINESS_ERROR, err.Error())
}
return map[string]interface{}{
"accessMenus": resultMenu.Menus,
}, nil
}
//GetUserMenus 获取用户组织
func (svr AuthService) GetUserOrg(userOrgCommand *command.UserOrgCommand) (interface{}, error) {
creationUserGateway := allied_creation_user.NewHttplibAlliedCreationUser(userOrgCommand.Operator)
result, err := creationUserGateway.UserSearch(allied_creation_user.ReqUserSearch{
Offset: 0,
Limit: 100,
UserBaseId: userOrgCommand.Operator.UserBaseId,
UserType: domain.UserTypeEmployee,
EnableStatus: domain.UserStatusEnable,
PullRealTime: true,
})
if err != nil {
return nil, application.ThrowError(application.BUSINESS_ERROR, err.Error())
}
var res = make([]interface{}, 0)
for i := range result.Users {
for j := range result.Users[i].UserOrg {
org := result.Users[i].UserOrg[j]
res = append(res, map[string]interface{}{
"orgId": org.OrgID,
"orgName": org.OrgName,
})
}
}
return map[string]interface{}{
"orgs": res,
}, nil
}
//OrgSwitch 组织切换
func (svr AuthService) OrgSwitch(switchOrgCommand *command.SwitchOrgCommand) (interface{}, error) {
if err := switchOrgCommand.ValidateCommand(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
loginToken := domain.LoginToken{}
err := loginToken.ParseToken(switchOrgCommand.Operator.Token)
if err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, "accessToken 不可用,"+err.Error())
}
loginToken.OrgId = switchOrgCommand.OrgId
token, err := svr.getToken(loginToken)
if err != nil {
return nil, application.ThrowError(application.BUSINESS_ERROR, err.Error())
}
var userId int64
if v, ok := token["userId"]; ok {
if vInt, ok := v.(int); !ok || vInt == 0 {
return nil, application.ThrowError(application.TRANSACTION_ERROR, "用户不存在")
} else {
userId = int64(vInt)
}
}
user, err := svr.getUserInfo(domain.Operator{UserId: userId, OrgId: loginToken.OrgId})
if err != nil {
return nil, application.ThrowError(application.BUSINESS_ERROR, err.Error())
}
creationUserGateway := allied_creation_user.NewHttplibAlliedCreationUser(
switchOrgCommand.Operator)
resultMenu, err := creationUserGateway.UserAccessMenus(allied_creation_user.ReqUserAccessMenus{
UserId: int(userId),
})
if err != nil {
return nil, application.ThrowError(application.BUSINESS_ERROR, err.Error())
}
var res = map[string]interface{}{
"user": user,
"accessMenus": resultMenu.Menus,
"access": token["token"],
}
return res, nil
}
// CompanySignUp 企业注册
func (svr AuthService) CompanySignUp(companySignUpCommand *command.CompanySignUpCommand) (interface{}, error) {
smsServeGateway := sms_serve.NewHttplibHttplibSmsServe()
err := smsServeGateway.CheckSmsCode(companySignUpCommand.Phone, companySignUpCommand.SmsCode)
if err != nil {
return nil, application.ThrowError(application.BUSINESS_ERROR, err.Error())
}
creationUserGateway := allied_creation_user.NewHttplibAlliedCreationUser(domain.Operator{})
_, err = creationUserGateway.AuthCompanySignUp(allied_creation_user.ReqAuthCompanySignUp{
CompanyName: companySignUpCommand.CompanyName,
Phone: companySignUpCommand.Phone,
Password: companySignUpCommand.Password,
Contacts: companySignUpCommand.Contacts,
IndustryCategory: companySignUpCommand.IndustryCategory,
Scale: companySignUpCommand.Scale,
})
if err != nil {
return nil, application.ThrowError(application.BUSINESS_ERROR, err.Error())
}
return companySignUpCommand, err
}
// ResetPassword 重置密码(找回密码)
func (svr AuthService) ResetPassword(resetPasswordCommand *command.ResetPasswordCommand) (interface{}, error) {
if err := resetPasswordCommand.ValidateCommand(); err != nil {
return nil, application.ThrowError(application.ARG_ERROR, err.Error())
}
var phone = resetPasswordCommand.Phone
if len(resetPasswordCommand.SmsCode) > 0 {
smsServeGateway := sms_serve.NewHttplibHttplibSmsServe()
err := smsServeGateway.CheckSmsCode(resetPasswordCommand.Phone, resetPasswordCommand.SmsCode)
if err != nil {
return nil, application.ThrowError(application.BUSINESS_ERROR, err.Error())
}
} else {
pcc := cache.PhoneCheckCache{}
var item = &cache.PhoneCheckItem{}
if err := pcc.Get(resetPasswordCommand.SmsCodeIdentity, item); err != nil {
log.Logger.Error(err.Error())
return nil, application.ThrowError(application.BUSINESS_ERROR, "验证码已失效")
}
phone = item.Phone
}
// 2.重置密码
creationUserGateway := allied_creation_user.NewHttplibAlliedCreationUser(domain.Operator{})
result, err := creationUserGateway.AuthResetPassword(allied_creation_user.ReqAuthResetPassword{
Phone: phone,
Password: resetPasswordCommand.Password,
})
if err != nil {
return nil, application.ThrowError(application.BUSINESS_ERROR, err.Error())
}
return result, err
}
func (svr AuthService) getUserInfo(operator domain.Operator) (interface{}, error) {
creationUserGateway := allied_creation_user.NewHttplibAlliedCreationUser(
operator)
// 个人用户登录
if operator.UserId == 0 && len(operator.Phone) != 0 {
resultUser, err := creationUserGateway.AuthUserBaseInfo(allied_creation_user.ReqAuthUserBase{
Account: operator.Phone,
})
if err != nil {
return nil, application.ThrowError(application.BUSINESS_ERROR, err.Error())
}
var user = map[string]interface{}{
"userId": resultUser.UserBaseID,
//"userOpenId": fmt.Sprintf("%v",resultUser.UserBaseID),
"userInfo": map[string]interface{}{
"userName": resultUser.UserInfo.UserName,
"userPhone": resultUser.UserInfo.Phone,
"userAvatar": resultUser.UserInfo.Avatar,
"email": resultUser.UserInfo.Email,
},
"department": struct{}{},
"company": map[string]interface{}{},
"im": resultUser.Im,
"org": struct{}{},
}
return user, nil
}
// 企业用户登录
resultUser, err := creationUserGateway.UserGet(allied_creation_user.ReqGetUser{
UserId: int(operator.UserId),
})
if err != nil {
return nil, application.ThrowError(application.BUSINESS_ERROR, err.Error())
}
resultOrg, err := creationUserGateway.OrgGet(allied_creation_user.ReqOrgGet{
OrgId: int(operator.OrgId),
})
if err != nil {
return nil, application.ThrowError(application.BUSINESS_ERROR, err.Error())
}
var user = map[string]interface{}{
"userId": resultUser.UserBaseId,
//"publicUserId":fmt.Sprintf("%v",resultUser.UserBaseId),
"userCode": resultUser.UserCode,
"userInfo": map[string]interface{}{
"userName": resultUser.UserInfo.UserName,
"userPhone": resultUser.UserInfo.Phone,
"userAvatar": resultUser.UserInfo.Avatar,
"userCode": resultUser.UserInfo.UserCode,
"email": resultUser.UserInfo.Email,
},
"department": resultUser.Department,
"company": map[string]interface{}{
"companyId": resultUser.Company.CompanyId,
"companyName": resultUser.Company.CompanyName,
"logo": resultUser.Company.Log,
"systemName": resultUser.Company.SystemName,
"address": resultUser.Company.Address,
},
"im": resultUser.IM,
"org": map[string]interface{}{
"orgId": resultOrg.OrgID,
"orgName": resultOrg.OrgName,
"orgCode": resultOrg.OrgCode,
"companyId": resultOrg.CompanyID,
},
//"currentLoginOrg": resultUser.Org,
"favoriteMenus": resultUser.FavoriteMenus,
}
return user, nil
}
func (svr AuthService) getToken(loginToken domain.LoginToken) (map[string]interface{}, error) {
// 1.匹配账号对应的用户
currentUser, err := svr.matchUser(&loginToken)
if err != nil {
return nil, application.ThrowError(application.BUSINESS_ERROR, err.Error())
}
// 2. 更新LoginAccess
transactionContext, err := factory.CreateTransactionContext(nil)
if err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
if err := transactionContext.StartTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
defer func() {
transactionContext.RollbackTransaction()
}()
var loginAccessRepository domain.LoginAccessRepository
if loginAccessRepository, err = factory.CreateLoginAccessRepository(map[string]interface{}{
"transactionContext": transactionContext,
}); err != nil {
return nil, application.ThrowError(application.BUSINESS_ERROR, err.Error())
}
_, lAccess, err := loginAccessRepository.Find(map[string]interface{}{
"account": loginToken.Account,
"platform": loginToken.Platform,
})
if err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
var currentAccess = &domain.LoginAccess{CreatedTime: time.Now()}
if len(lAccess) > 0 {
currentAccess = lAccess[0]
}
if _, err = currentAccess.ResetLoginAccess(loginToken); err != nil {
return nil, application.ThrowError(application.BUSINESS_ERROR, err.Error())
}
//存数据库
if _, err = loginAccessRepository.Save(currentAccess); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
//redis缓存
tokenCache := cache.LoginTokenCache{}
if err = tokenCache.SaveAccessToken(currentAccess); err != nil {
return nil, err
}
if err = tokenCache.SaveRefreshToken(currentAccess); err != nil {
return nil, err
}
if err := transactionContext.CommitTransaction(); err != nil {
return nil, application.ThrowError(application.BUSINESS_ERROR, err.Error())
}
nowTime := time.Now().Unix()
token := map[string]interface{}{
"refreshToken": currentAccess.RefreshToken,
"accessToken": currentAccess.AccessToken,
"expiresIn": currentAccess.AccessExpired - nowTime,
}
return map[string]interface{}{
"token": token,
"userId": currentUser.UserId,
}, nil
}
func (svr AuthService) matchUser(loginToken *domain.LoginToken) (*allied_creation_user.UserDetail, error) {
creationUserGateway := allied_creation_user.NewHttplibAlliedCreationUser(domain.Operator{})
userSearchResult, err := creationUserGateway.UserSearch(allied_creation_user.ReqUserSearch{
Phone: loginToken.Account,
UserType: domain.UserTypeEmployee,
EnableStatus: domain.UserStatusEnable,
})
if err != nil {
return nil, application.ThrowError(application.BUSINESS_ERROR, "用户信息获取失败,"+err.Error())
}
// 1 . 判定当前凭证的companyId,OrganizationId 是否在用户列表中
var currentOrgIsOK bool
var currentUser allied_creation_user.UserDetail
loopUser1:
for _, v := range userSearchResult.Users {
for _, vv := range v.UserOrg {
if vv.OrgID == int(loginToken.OrgId) {
currentOrgIsOK = true
currentUser = v
break loopUser1
}
}
}
if !currentOrgIsOK {
loopUser2:
for _, v := range userSearchResult.Users {
for _, vv := range v.UserOrg {
loginToken.OrgId = int64(vv.OrgID)
currentOrgIsOK = true
currentUser = v
break loopUser2
}
}
}
if !currentOrgIsOK && loginToken.Platform == domain.LoginPlatformWeb {
return nil, application.ThrowError(application.TRANSACTION_ERROR, "登录的公司组织不可用")
}
if currentOrgIsOK {
loginToken.UserId = int64(currentUser.UserId)
loginToken.UserBaseId = int64(currentUser.UserBaseId)
loginToken.CompanyId = int64(currentUser.Company.CompanyId)
var orgIds []int64
for i := range currentUser.UserOrg {
orgIds = append(orgIds, int64(currentUser.UserOrg[i].OrgID))
}
loginToken.OrgIds = orgIds
}
// 个人登录
if !currentOrgIsOK { //|| len(userSearchResult.Users) == 0
userBase, err := creationUserGateway.AuthUserBaseInfo(allied_creation_user.ReqAuthUserBase{
Account: loginToken.Account,
})
if err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, "账号不存在")
}
loginToken.UserBaseId = int64(userBase.UserBaseID)
if userBase.UserBaseID > 0 {
cooperationUsers, _ := creationUserGateway.UserSearch(allied_creation_user.ReqUserSearch{
UserBaseId: int64(userBase.UserBaseID),
UserType: domain.UserTypeCooperation,
EnableStatus: domain.UserStatusEnable,
})
if len(cooperationUsers.Users) > 0 {
loginToken.CompanyId = int64(cooperationUsers.Users[0].Company.CompanyId)
loginToken.UserId = int64(cooperationUsers.Users[0].UserId)
loginToken.OrgId = int64(cooperationUsers.Users[0].Org.OrgId)
currentUser = cooperationUsers.Users[0]
}
}
}
return ¤tUser, nil
}
//GetCompanyOrgsByUser 获取登录用户的公司组织列表
func (svr AuthService) GetCompanyOrgsByUser(queryParam *query.GetCompanyOrgsByUserQuery) (interface{}, error) {
creationUserGateway := allied_creation_user.NewHttplibAlliedCreationUser(queryParam.Operator)
result, err := creationUserGateway.UserSearch(allied_creation_user.ReqUserSearch{
Phone: queryParam.Operator.Phone,
UserType: domain.UserTypeEmployee,
PullRealTime: true,
})
if err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
var (
companys []dto.CompanyItem
orgs []dto.OrgItem
mapCompany = make(map[int]interface{})
)
for i := range result.Users {
user := result.Users[i]
if _, ok := mapCompany[user.Company.CompanyId]; !ok {
companys = append(companys, dto.CompanyItem{
CompanyId: user.Company.CompanyId,
CompanyName: user.Company.CompanyName,
})
}
for j := range user.UserOrg {
org := user.UserOrg[j]
orgs = append(orgs, dto.OrgItem{
OrganizationId: org.OrgID,
OrganizationName: org.OrgName,
CompanyId: user.Company.CompanyId,
})
}
}
data := map[string]interface{}{
"companys": companys,
"organizations": orgs,
}
return data, nil
}
//GetQrcode 获取扫码登录需要的二维码
func (svr AuthService) GetQrcode() (interface{}, error) {
qrmsg := domain.QrcodeMessage{}
_, err := qrmsg.GenerateImageBase64() //imgBase64
if err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
qrCache := cache.LoginQrcodeCache{}
err = qrCache.Save(qrmsg)
if err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
data := map[string]interface{}{
//"image": imgBase64,
"key": qrmsg.Token,
}
return data, nil
}
//CheckSmsCode 验证手机短信验证码
func (svr AuthService) CheckSmsCode(smsCodeCommand *command.CheckSmsCodeCommand) (interface{}, error) {
smsServeGateway := sms_serve.NewHttplibHttplibSmsServe()
err := smsServeGateway.CheckSmsCode(smsCodeCommand.Phone, smsCodeCommand.SmsCode)
if err != nil {
return nil, application.ThrowError(application.BUSINESS_ERROR, err.Error())
}
uid := uuid.New()
pcc := cache.PhoneCheckCache{}
if err := pcc.Add(uid.String(), cache.PhoneCheckItem{
Phone: smsCodeCommand.Phone,
SmsCodeIdentity: uid.String(),
Action: smsCodeCommand.Action,
}); err != nil {
log.Logger.Error(err.Error())
return nil, application.ThrowError(application.BUSINESS_ERROR, "系统错误")
}
return map[string]interface{}{
"smsCodeIdentity": uid.String(),
}, nil
}
func (svr *AuthService) CaptchaInit(request *query.CaptchaInitRequest) (interface{}, error) {
var rsp map[string]interface{}
var err error
lib := geetest.NewGeetestLib(captchaID, privateKey, 2*time.Second)
status, responseBt := lib.PreProcess("", request.UserIp)
var geetestRsp geetest.FailbackRegisterRespnse
json.Unmarshal(responseBt, &geetestRsp)
rspData := map[string]interface{}{
"success": geetestRsp.Success,
"gt": geetestRsp.GT,
"challenge": geetestRsp.Challenge,
"newCaptcha": geetestRsp.NewCaptcha,
}
if status == 0 {
return nil, application.ThrowError(application.BUSINESS_ERROR, "获取图形验证码失败,请重试")
}
rsp = rspData
return rsp, err
}