auth.go
17.1 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
package auth
import (
"fmt"
"github.com/tiptok/gocomm/xa/eda"
"gitlab.fjmaimaimai.com/mmm-go/partner/pkg/application/factory"
"gitlab.fjmaimaimai.com/mmm-go/partner/pkg/application/userAuth"
"gitlab.fjmaimaimai.com/mmm-go/partner/pkg/constant"
"gitlab.fjmaimaimai.com/mmm-go/partner/pkg/domain"
"gitlab.fjmaimaimai.com/mmm-go/partner/pkg/domain/event"
"gitlab.fjmaimaimai.com/mmm-go/partner/pkg/infrastructure/domain_service"
http_gateway "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/infrastructure/svr"
"gitlab.fjmaimaimai.com/mmm-go/partner/pkg/infrastructure/utils"
"gitlab.fjmaimaimai.com/mmm-go/partner/pkg/log"
"gitlab.fjmaimaimai.com/mmm-go/partner/pkg/protocol"
protocolx "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/protocol/auth"
"strconv"
"strings"
"time"
)
func Login(header *protocol.RequestHeader, request *protocol.LoginRequest) (rsp *protocol.LoginResponse, err error) {
var (
transactionContext, _ = factory.CreateTransactionContext(nil)
PartnerInfoService, _ = factory.CreatePartnerInfoRepositoryIn(transactionContext)
partnerInfo *domain.PartnerInfo
result bool = false
PartnerSubAccountRepository, _ = factory.CreatePartnerSubAccountRepository(transactionContext)
partnerSubAccount *domain.PartnerSubAccount
)
if err = transactionContext.StartTransaction(); err != nil {
return nil, err
}
defer func() {
transactionContext.RollbackTransaction()
}()
rsp = &protocol.LoginResponse{}
if partnerSubAccount, err = PartnerSubAccountRepository.FindOne(map[string]interface{}{"account": request.Phone}); err == nil {
if partnerInfo, err = PartnerInfoService.FindOne(map[string]interface{}{"id": partnerSubAccount.PartnerId}); err != nil {
//子账号
err = protocol.NewErrWithMessage(502, err) //账号不存在
return
}
partnerInfo.Password = partnerSubAccount.Password
} else {
if partnerInfo, err = PartnerInfoService.FindOne(map[string]interface{}{"account": request.Phone}); err != nil {
//子账号
err = protocol.NewErrWithMessage(502, err) //账号不存在
return
}
}
if !partnerInfo.IsEnable() {
err = protocol.NewErrWithMessage(2002) //账号禁用
return
}
switch request.GrantType {
case protocol.LoginByPassword:
if len(partnerInfo.Password) == 0 {
err = protocol.NewCustomMessage(1, "密码不能为空!")
return
}
if result = strings.EqualFold(partnerInfo.Password, request.Password); !result {
err = protocol.NewCustomMessage(1, "密码输入有误!")
return
}
break
case protocol.LoginBySmsCode:
if _, err = CheckSmsCode(request.Phone, request.Captcha); err != nil {
return
}
break
default:
err = protocol.NewCustomMessage(1, "登录方式不支持!")
break
}
userClaim := utils.UserTokenClaims{
UserId: partnerInfo.Id,
Phone: partnerInfo.Account,
AdminType: int(protocolx.AdminTypePartner),
CompanyId: 1, //默认公司
}
rsp.AuthCode, _ = utils.GenerateTokenWithClaim(userClaim, protocol.AuthCodeExpire*time.Second)
if _, err = InitOrUpdateUserIMInfo(partnerInfo.Id, partnerInfo.PartnerName, transactionContext); err != nil {
log.Error(err)
return
}
err = transactionContext.CommitTransaction()
return
}
func SmsCode(request *protocol.SmsCodeRequest) (rsp *protocol.SmsCodeResponse, err error) {
var data map[string]interface{}
sms, _ := factory.CreateSmsCodeService()
data, err = sms.SendSms(request.Phone)
rsp = &protocol.SmsCodeResponse{}
if err != nil {
if msg, ok := data["msg"]; ok {
err = protocol.NewCustomMessage(1, msg.(string))
}
log.Error(err, data, request.Phone)
return
}
err = protocol.NewSuccessWithMessage("发送验证码成功")
return
}
func AccessToken(request *protocol.AccessTokenRequest) (rsp *protocol.AccessTokenResponse, err error) {
var (
claim *utils.UserTokenClaims
)
rsp = &protocol.AccessTokenResponse{}
if claim, err = utils.ParseJWTToken(request.AuthCode); err != nil {
err = protocol.NewErrWithMessage(4139, err)
return
}
if claim.UserId <= 0 {
err = protocol.NewErrWithMessage(1, fmt.Errorf("jwt authCode (%v) valid", request.AuthCode))
return
}
userClaims := utils.UserTokenClaims{
UserId: claim.UserId,
CompanyId: claim.CompanyId,
AdminType: claim.AdminType,
Phone: claim.Phone,
}
rsp.AccessToken, _ = utils.GenerateTokenWithClaim(userClaims, protocol.TokenExpire*time.Second)
rsp.RefreshToken, _ = utils.GenerateTokenWithClaim(userClaims, protocol.RefreshTokenExipre*time.Second)
rsp.ExpiresIn = protocol.TokenExpire
eda.Publish(&event.AccessTokenEvent{
UserPhone: claim.Phone,
AccessToken: rsp.AccessToken,
RefreshToken: rsp.RefreshToken,
})
return
}
func RefreshToken(request *protocol.RefreshTokenRequest) (rsp *protocol.RefreshTokenResponse, err error) {
var (
claim *utils.UserTokenClaims
transactionContext, _ = factory.CreateTransactionContext(nil)
PartnerInfoService, _ = factory.CreatePartnerInfoRepositoryIn(transactionContext)
UsersRepository, _ = factory.CreateUsersRepository(transactionContext)
CompanyRepository, _ = factory.CreateCompanyRepository(transactionContext)
partnerInfo *domain.PartnerInfo
user *domain.Users
company *domain.Company
userId int64
)
if err = transactionContext.StartTransaction(); err != nil {
return nil, err
}
defer func() {
transactionContext.RollbackTransaction()
}()
rsp = &protocol.RefreshTokenResponse{}
if claim, err = utils.ParseJWTToken(request.RefreshToken); err != nil {
err = protocol.NewErrWithMessage(4140, err)
return
}
if claim.UserId <= 0 {
err = protocol.NewErrWithMessage(1, fmt.Errorf("jwt refrshToken (%v) valid", request.RefreshToken))
return
}
if company, err = CompanyRepository.FindOne(map[string]interface{}{"id": claim.CompanyId, "status": 1, "enable": 1}); err != nil || company == nil {
log.Error(err)
err = protocol.NewErrWithMessage(4140, err)
return
}
switch claim.AdminType {
case int(protocolx.AdminTypePartner):
if partnerInfo, err = PartnerInfoService.FindOne(map[string]interface{}{"account": claim.Phone, "companyId": claim.CompanyId, "status": 1}); err != nil || partnerInfo == nil {
log.Error(err)
err = protocol.NewErrWithMessage(4140, err)
return
}
userId = partnerInfo.Id
break
case int(protocolx.AdminTypeManager):
if user, err = UsersRepository.FindOne(map[string]interface{}{"phone": claim.Phone, "companyId": claim.CompanyId, "status": 1}); err != nil || user == nil {
log.Error(err)
err = protocol.NewErrWithMessage(4140, err)
return
}
userId = user.Id
break
default:
err = protocol.NewErrWithMessage(4140, err)
return
}
userClaim := utils.UserTokenClaims{
UserId: userId,
Phone: claim.Phone,
AdminType: claim.AdminType,
CompanyId: claim.CompanyId,
}
rsp.AccessToken, _ = utils.GenerateTokenWithClaim(userClaim, protocol.TokenExpire*time.Second)
rsp.RefreshToken, _ = utils.GenerateTokenWithClaim(userClaim, protocol.RefreshTokenExipre*time.Second)
rsp.ExpiresIn = protocol.TokenExpire
if err = eda.Publish(&event.RefreshTokenEvent{
UserPhone: claim.Phone,
AccessToken: rsp.AccessToken,
RefreshToken: rsp.RefreshToken,
OldRefreshToken: request.RefreshToken,
OldAccessToken: "",
}); err != nil {
log.Error(err)
rsp.RefreshToken = ""
rsp.AccessToken = ""
err = protocol.NewErrWithMessage(4140, err)
return
}
err = transactionContext.CommitTransaction()
return
}
//验证短信验证码 T
func CheckSmsCode(phone, code string) (result bool, err error) {
sms, _ := factory.CreateSmsCodeService()
var data map[string]interface{}
data, err = sms.CheckSmsCode(phone, code)
if err != nil {
if msg, ok := data["msg"]; ok {
err = protocol.NewCustomMessage(1, msg.(string))
}
return
}
return
}
//验证手机号码(修改手机号码、重置密码的前一步)
func AuthCheckSmsCode(header *protocol.RequestHeader, request *protocol.AuthCheckSmsCodeRequest) (rsp *protocol.AuthCheckSmsCodeResponse, err error) {
var ()
if _, err = CheckSmsCode(request.Phone, request.Captcha); err != nil {
return
}
rsp = &protocol.AuthCheckSmsCodeResponse{
CaptchaCertificate: fmt.Sprintf("%v", utils.GenerateRangeNum(100000, 799999)),
}
return
}
//注销登录
func Revoke(header *protocol.RequestHeader, request *protocol.RevokeRequest) (rsp *protocol.RevokeResponse, err error) {
//auth := userAuth.NewRedisUserAuth(userAuth.WithUserId(header.UserId))
//rsp = &protocol.RevokeResponse{}
//if !auth.Exist() {
// return
//}
//if err = auth.RemoveAuth(); err != nil {
// log.Error(err)
// err = protocol.NewErrWithMessage(4140, err)
// return
//}
return
}
//注销登录
func UCenterRevoke(header *protocol.RequestHeader, userId int64) (rsp *protocol.RevokeResponse, err error) {
var (
transactionContext, _ = factory.CreateTransactionContext(nil)
UsersRepository, _ = factory.CreateUsersRepository(transactionContext)
user *domain.Users
)
rsp = &protocol.RevokeResponse{}
if err = transactionContext.StartTransaction(); err != nil {
return nil, err
}
defer func() {
transactionContext.RollbackTransaction()
}()
if user, err = UsersRepository.FindOne(map[string]interface{}{"openId": userId}); err != nil {
log.Error(err)
err = nil
return
}
//注销凭证
userAuth.NewRedisUserCredential(user.Phone).RemoveAuth()
//注销token
id, _ := strconv.Atoi(user.Phone)
auth := userAuth.NewRedisUserAuth(userAuth.WithUserId(int64(id)))
if !auth.Exist() {
return
}
if err = auth.RemoveAuth(); err != nil {
log.Error(err)
return
}
err = transactionContext.CommitTransaction()
return
}
func CenterCompanys(header *protocol.RequestHeader, request *protocolx.CenterCompanysRequest) (v interface{}, err error) {
var (
transactionContext, _ = factory.CreateTransactionContext(nil)
imInfo *domain.ImInfo
loginSvr = domain_service.NewPgLoginService(transactionContext)
)
phoneId, e := strconv.Atoi(request.Phone)
if e != nil {
log.Error(e)
e = protocol.NewErrWithMessage(2)
return
}
rsp := &protocolx.CenterCompanysResponse{}
if err = transactionContext.StartTransaction(); err != nil {
log.Error(err)
return nil, err
}
defer func() {
transactionContext.RollbackTransaction()
}()
loginSvr.Init(request.Phone)
if len(loginSvr.Users) == 0 && len(loginSvr.PartnerInfo) == 0 {
err = protocol.NewErrWithMessage(10001)
return
}
switch request.GrantType {
case protocol.LoginByPassword:
if len(request.Password) == 0 {
err = protocol.NewCustomMessage(1, "密码不能为空!")
return
}
if loginSvr.ManagerLogin(request.Phone, request.Password) != nil && loginSvr.PartnerLogin(request.Phone, request.Password) != nil {
err = protocol.NewCustomMessage(1, "密码输入有误!")
return
}
break
case protocol.LoginBySmsCode:
if _, err = CheckSmsCode(request.Phone, request.Captcha); err != nil {
return
}
break
case protocol.LoginByCredentials:
//凭证是否存在
if credential, e := userAuth.NewRedisUserCredential(request.Phone).GetAuth(); e != nil || !strings.EqualFold(credential, request.Credentials) {
log.Debug("凭证过期或者已失效:", request.Phone)
err = protocol.NewErrWithMessage(4140, err)
return
}
if _, err = utils.ParseJWTToken(request.Credentials); err != nil {
err = protocol.NewErrWithMessage(4140, err)
return
}
default:
err = protocol.NewCustomMessage(1, "登录方式不支持!")
break
}
//获取统计信息
rsp.Partner, _ = loginSvr.PartnerStaticInfo()
rsp.Manager, _ = loginSvr.ManagerStaticInfo()
//没有有效人的时候
if !loginSvr.AvailableCompany {
err = protocol.NewErrWithMessage(10008) //账号禁用
return
}
var nickName string
if len(loginSvr.Users) > 0 {
nickName = loginSvr.Users[0].Name
} else if len(loginSvr.PartnerInfo) > 0 {
nickName = loginSvr.PartnerInfo[0].PartnerName
}
//初始化im信息
if imInfo, err = InitOrUpdateUserIMInfo(int64(phoneId), nickName, transactionContext); err != nil {
log.Error(err)
return
}
rsp.CsAccountID = fmt.Sprintf("%v", imInfo.CustomerImId)
rsp.ImToken = imInfo.ImToken
rsp.Accid, _ = strconv.Atoi(imInfo.ImId)
rsp.Phone = request.Phone
rsp.Credentials, _ = utils.GenerateToken(int64(phoneId), request.Phone, protocol.RefreshTokenExipre*time.Second)
//添加手机对应的凭证
userAuth.NewRedisUserCredential(request.Phone).AddAuth(rsp.Credentials)
err = transactionContext.CommitTransaction()
v = map[string]interface{}{"center": rsp}
return
}
func Companys(header *protocol.RequestHeader, request *protocolx.CompanysRequest) (rsp *protocolx.CompanysResponse, err error) {
var (
transactionContext, _ = factory.CreateTransactionContext(nil)
loginSvr = domain_service.NewPgLoginService(transactionContext)
claim *utils.UserTokenClaims
)
rsp = &protocolx.CompanysResponse{}
if err = transactionContext.StartTransaction(); err != nil {
log.Error(err)
return nil, err
}
defer func() {
transactionContext.RollbackTransaction()
}()
if claim, err = utils.ParseJWTToken(request.Credentials); err != nil {
err = protocol.NewErrWithMessage(4140, err)
return
}
//凭证是否存在
if credential, e := userAuth.NewRedisUserCredential(claim.Phone).GetAuth(); e != nil || !strings.EqualFold(credential, request.Credentials) {
log.Debug("凭证过期或者已失效:", claim.Phone)
err = protocol.NewErrWithMessage(4140, err)
return
}
loginSvr.Init(claim.Phone)
rsp.Partner, _ = loginSvr.PartnerStaticInfo()
rsp.Manager, _ = loginSvr.ManagerStaticInfo()
//没有有效人的时候
if !loginSvr.AvailableCompany {
err = protocol.NewErrWithMessage(4140, err) //账号禁用
return
}
err = transactionContext.CommitTransaction()
return
}
func LoginV2(header *protocol.RequestHeader, request *protocol.LoginRequestV2) (rsp *protocol.LoginResponse, err error) {
var (
claim *utils.UserTokenClaims
transactionContext, _ = factory.CreateTransactionContext(nil)
PartnerInfoRepository, _ = factory.CreatePartnerInfoRepositoryIn(transactionContext)
UsersRepository, _ = factory.CreateUsersRepository(transactionContext)
CompanyRepository, _ = factory.CreateCompanyRepository(transactionContext)
userId int64
adminApiGateway = http_gateway.NewHttplibBusinessAdminApiServiceGateway()
)
rsp = &protocol.LoginResponse{}
if err = transactionContext.StartTransaction(); err != nil {
return nil, err
}
defer func() {
transactionContext.RollbackTransaction()
}()
if claim, err = utils.ParseJWTToken(request.Credentials); err != nil {
err = protocol.NewErrWithMessage(4140, err)
return
}
//凭证是否存在
if credential, e := userAuth.NewRedisUserCredential(claim.Phone).GetAuth(); e != nil || !strings.EqualFold(credential, request.Credentials) {
log.Debug("凭证过期或者已失效:", claim.Phone)
err = protocol.NewErrWithMessage(4140, err)
return
}
if company, e := CompanyRepository.FindOne(map[string]interface{}{"id": request.Cid, "enable": 1}); e != nil || company == nil {
err = protocol.NewErrWithMessage(10007, err)
return
}
switch request.IdType {
case int(protocolx.AdminTypePartner):
if p, e := PartnerInfoRepository.FindOne(map[string]interface{}{"account": claim.Phone, "companyId": request.Cid, "deleteAtIsNull": true}); e == nil {
userId = p.Id
if !p.IsEnable() {
err = protocol.NewErrWithMessage(10006, err) //当前账号已被禁用
return
}
}
//验证公司模块权限
if _, adminUsers, e := UsersRepository.Find(map[string]interface{}{"inCompanyIds": []int64{int64(request.Cid)}, "adminType": 2, "deleteAtIsNull": true}); e == nil {
if len(adminUsers) > 0 {
au := adminUsers[0]
if code, e := adminApiGateway.UserAuth(au.Id, constant.BUSINESS_ADMIN_PLATFORM_ID); e != nil || code != 0 {
log.Debug("【合伙人检查权限】", claim.Phone, "【公司】", request.Cid, au.Id, code, e.Error())
err = protocol.NewErrWithMessage(10008, err) // 抱歉,企业管理员未帮您开通权限
return
}
}
}
break
case int(protocolx.AdminTypeManager):
if p, e := UsersRepository.FindOne(map[string]interface{}{"phone": claim.Phone, "companyId": request.Cid, "deleteAtIsNull": true}); e == nil {
userId = p.Id
if !p.IsEnable() {
err = protocol.NewErrWithMessage(10006, err) //当前账号已被禁用
return
}
}
//校验模块权限
if userId != 0 {
if code, e := adminApiGateway.UserAuth(userId, constant.BUSINESS_ADMIN_PLATFORM_ID); e != nil || code != 0 {
log.Debug("【检查权限】", userId, "【公司】", request.Cid, "【错误】:", code, e.Error())
err = protocol.NewErrWithMessage(10008, err) // 抱歉,企业管理员未帮您开通权限
return
}
}
break
default:
err = protocol.NewErrWithMessage(2, fmt.Errorf("idType :%v not in range (1,2)", request.IdType)) //用户类型有误
return
}
if userId == 0 {
err = protocol.NewErrWithMessage(10001, err) //账号不存在
return
}
//根据simnum + cid
userClaims := utils.UserTokenClaims{
UserId: userId,
CompanyId: int64(request.Cid),
AdminType: request.IdType,
Phone: claim.Phone,
}
rsp.AuthCode, _ = utils.GenerateTokenWithClaim(userClaims, protocol.AuthCodeExpire*time.Second)
err = transactionContext.CommitTransaction()
return
}