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
package auth

import (
	"fmt"
	"strconv"
	"strings"
	"time"

	"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"
)

// 该方法废弃
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
}

/**
 * @Author SteveChan
 * @Description 企业平台-密码登录校验
 * @Date 11:06 2021/2/5
 * @Param
 * @return
 **/
func PasswordLogin(header *protocol.RequestHeader, request *protocol.LoginRequest) (v interface{}, err error) {
	var (
		transactionContext, _ = factory.CreateTransactionContext(nil)
		loginSvr              = domain_service.NewPgLoginService(transactionContext)
	)

	if err = transactionContext.StartTransaction(); err != nil {
		log.Error(err)
		return nil, err
	}

	defer func() {
		transactionContext.RollbackTransaction()
	}()

	// loginSvr 初始化
	loginSvr.Init(request.Phone)

	if len(loginSvr.Users) == 0 && len(loginSvr.PartnerInfo) == 0 {
		v = map[string]interface{}{}
		err = protocol.NewErrWithMessage(10001)
		return
	}

	if len(request.Password) == 0 {
		v = map[string]interface{}{}
		err = protocol.NewCustomMessage(1, "密码不能为空!")
		return
	}

	if loginSvr.ManagerLogin(request.Phone, request.Password) != nil && loginSvr.PartnerLogin(request.Phone, request.Password) != nil {
		v = map[string]interface{}{}
		err = protocol.NewCustomMessage(1, "密码输入有误!")
		return
	}

	v = map[string]interface{}{}
	err = transactionContext.CommitTransaction()
	return
}

/**
 * @Author SteveChan
 * @Description //TODO 企业平台-多公司登录,判断是否高管,优化游客登录
 * @Date 15:01 2021/1/12
 * @Param
 * @return
 **/
func CompaniesLogin(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()
	}()

	//TODO 通过密码或校验码登录的普通用户或通过校验码登录的游客,注册一个账号到配置的公司去
	if request.GrantType == protocol.LoginBySmsCode || request.GrantType == protocol.LoginByPassword {
		userErr := loginSvr.RegistryGuest(request.Phone)
		//userErr := loginSvr.OperateGuest(request.Phone)
		if userErr != nil {
			log.Error(userErr)
		}
	}

	// loginSvr 初始化
	_ = loginSvr.Init(request.Phone)

	// 所有公司有效用户不存在、所有公司有效合伙人不存在、所有公司合伙人不存在
	if len(loginSvr.Users) == 0 && len(loginSvr.PartnerInfo) == 0 && len(loginSvr.NormalPartnerInfo) == 0 {
		err = protocol.NewErrWithMessage(10001) // 用户不存在
		return
	}

	switch request.GrantType {
	case protocol.LoginByPassword:
		if len(request.Password) == 0 {
			err = protocol.NewCustomMessage(1, "密码不能为空!")
			return
		}

		//manageLoginErr := loginSvr.ManagerLogin(request.Phone, request.Password)
		//fmt.Print("用户登录:", manageLoginErr, "\n")
		//partnerLoginErr := loginSvr.PartnerLogin(request.Phone, request.Password)
		//fmt.Print("合伙人登录:", partnerLoginErr, "\n")
		//
		//if manageLoginErr != nil && partnerLoginErr != nil {
		//	//if len(loginSvr.PartnerInfo) == 0 { // 不存在有效用户
		//	//	err = protocol.NewErrWithMessage(10008)
		//	//	return
		//	//}
		//	err = protocol.NewCustomMessage(1, "密码输入有误!")
		//	return
		//} else if manageLoginErr != nil && partnerLoginErr == nil {
		//	if len(loginSvr.PartnerInfo) == 1 && len(loginSvr.NormalUsers) == 0 {
		//		if loginSvr.PartnerInfo[0].CompanyId == int64(constant.DEFAULT_GUEST_COMPANY) {
		//			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 constant.DISENABLE_MULTI_DEVICE_LOGIN {
			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.HasAvailableCompany && !loginSvr.HasAvailableManagerCompany { // 判断合伙人或者高管是否有可访问的公司
		err = protocol.NewErrWithMessage(10008) //账号禁用, 抱歉,企业管理员未帮您开通权限。如需访问,请联系企业管理员
		return
	}

	// 初始化网易IM信息
	//var nickName string
	//if len(loginSvr.Users) > 0 {
	//	nickName = loginSvr.Users[0].Name
	//} else if len(loginSvr.PartnerInfo) > 0 {
	//	nickName = loginSvr.PartnerInfo[0].PartnerName
	//}
	//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.CsAccountID = "3129687690100739"
	rsp.ImToken = "d31efb292166d07a3cd9f6693b7601ab"
	rsp.Accid = 3722917312790528
	rsp.Phone = request.Phone
	rsp.Credentials, _ = utils.GenerateToken(int64(phoneId), request.Phone, protocol.RefreshTokenExipre*time.Second)

	// 添加手机对应的凭证
	userAuth.NewRedisUserCredential(request.Phone).AddAuth(rsp.Credentials)

	v = map[string]interface{}{"center": rsp}

	err = transactionContext.CommitTransaction()
	return
}

/**
 * @Author SteveChan
 * @Description //TODO 企业平台-多公司登录 - 通过凭证,判断是否高管
 * @Date 15:00 2021/1/12
 * @Param
 * @return
 **/
func CompaniesLoginByCredential(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 constant.DISENABLE_MULTI_DEVICE_LOGIN {
		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 初始化
	_ = loginSvr.Init(claim.Phone)

	// 高管标志位初始化
	_ = loginSvr.InitSenior(claim.Phone)

	// 合伙人标志位初始化
	_ = loginSvr.InitPartner(claim.Phone)

	if len(loginSvr.PartnerInfo) == 0 && len(loginSvr.Users) == 0 {
		err = protocol.NewErrWithMessage(4140, err)
		return
	}

	rsp.Partner, _ = loginSvr.PartnerStaticInfo()
	rsp.Manager, _ = loginSvr.ManagerStaticInfo()

	if !loginSvr.HasAvailableCompany && !loginSvr.HasAvailableManagerCompany {
		err = protocol.NewErrWithMessage(4140, err) //账号禁用
		return
	}

	err = transactionContext.CommitTransaction()
	return
}

/**
 * @Author SteveChan
 * @Description 登录
 * @Date 15:05 2021/1/15
 * @Param
 * @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 constant.DISENABLE_MULTI_DEVICE_LOGIN {
		//凭证是否存在
		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 u, e := UsersRepository.FindOne(map[string]interface{}{"phone": claim.Phone, "companyId": request.Cid, "deleteAtIsNull": true}); e == nil {
		//	userId = u.Id
		//	if !u.IsEnable() {
		//		err = protocol.NewErrWithMessage(10006, err) //当前账号已被禁用
		//		return
		//	}
		//}
		// 合伙人检索
		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 _, admins, e := UsersRepository.Find(map[string]interface{}{"inCompanyIds": []int64{int64(request.Cid)}, "adminType": 2, "deleteAtIsNull": true}); e == nil {
			if len(admins) > 0 {
				admin := admins[0]
				if code, e := adminApiGateway.UserAuth(admin.Id, constant.BUSINESS_ADMIN_PLATFORM_ID); e != nil || code != 0 {
					log.Debug("【合伙人检查权限】", claim.Phone, "【公司】", request.Cid, admin.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() || !p.IsUserSenior() {
				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
	}

	// 生成授权码
	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
}