766 lines
		
	
	
		
			24 KiB
		
	
	
	
		
			Go
		
	
	
	
	
	
			
		
		
	
	
			766 lines
		
	
	
		
			24 KiB
		
	
	
	
		
			Go
		
	
	
	
	
	
| package authservice
 | ||
| 
 | ||
| import (
 | ||
| 	"fmt"
 | ||
| 	"go-admin/app/admin/models"
 | ||
| 	"go-admin/app/admin/models/sysmodel"
 | ||
| 	"go-admin/app/admin/service/aduserdb"
 | ||
| 	"go-admin/app/admin/service/dto"
 | ||
| 	"go-admin/common/const/rediskey"
 | ||
| 	"go-admin/common/helper"
 | ||
| 	cModels "go-admin/common/models"
 | ||
| 	statuscode "go-admin/common/status_code"
 | ||
| 	"go-admin/config"
 | ||
| 	"go-admin/pkg/cryptohelper/inttostring"
 | ||
| 	"go-admin/pkg/cryptohelper/jwthelper"
 | ||
| 	"go-admin/pkg/cryptohelper/md5helper"
 | ||
| 	"go-admin/pkg/emailhelper"
 | ||
| 	"go-admin/pkg/utility"
 | ||
| 	"time"
 | ||
| 
 | ||
| 	"github.com/go-admin-team/go-admin-core/logger"
 | ||
| 	log "github.com/go-admin-team/go-admin-core/logger"
 | ||
| 	"go.uber.org/zap"
 | ||
| 	"gorm.io/gorm"
 | ||
| )
 | ||
| 
 | ||
| /**
 | ||
|  * 身份验证服务
 | ||
|  */
 | ||
| 
 | ||
| var codeVerifySuccess = "code_verify_success" // 验证码验证成功以后aes加密的秘钥
 | ||
| 
 | ||
| // UserRegisterBefore 用户注册前校验
 | ||
| func UserRegisterBefore(orm *gorm.DB, registerInfo sysmodel.FrontedUserRegisterReq) (pid int, code int) {
 | ||
| 	// ========== 校验注册信息 ========== //
 | ||
| 	if registerInfo.Password != registerInfo.CheckPassword {
 | ||
| 		return 0, statuscode.PasswordsMustSame
 | ||
| 	}
 | ||
| 	if registerInfo.RegisterType == sysmodel.TSmsCode {
 | ||
| 		user, err := aduserdb.GetUserByPhone(orm, registerInfo.PhoneAreaCode, registerInfo.Phone)
 | ||
| 		if err != nil {
 | ||
| 			return 0, statuscode.ServerError
 | ||
| 		}
 | ||
| 		if user.Id != 0 {
 | ||
| 			return 0, statuscode.TheAccountIsAlreadyRegistered
 | ||
| 		}
 | ||
| 	} else if registerInfo.RegisterType == sysmodel.TEmailCode {
 | ||
| 		user, err := aduserdb.GetUserByEmail(orm, registerInfo.Email) //GetUser("useremail", registerInfo.Email)
 | ||
| 		if err != nil {
 | ||
| 			return 0, statuscode.ServerError
 | ||
| 		}
 | ||
| 		if user.Id != 0 {
 | ||
| 			//helper.DefaultRedis.SetStringExpire(fmt.Sprintf("%s-reset-register", registerInfo.Email), registerInfo.Password, time.Second*350)
 | ||
| 			return 0, statuscode.TheAccountIsAlreadyRegistered
 | ||
| 		}
 | ||
| 	}
 | ||
| 
 | ||
| 	// 根据邀请码获取推荐人ID
 | ||
| 	if registerInfo.InviteCode != "" {
 | ||
| 		parentUser, err := aduserdb.GetUserByInviteCode(orm, registerInfo.InviteCode)
 | ||
| 		if err != nil {
 | ||
| 			return 0, statuscode.ServerError
 | ||
| 		}
 | ||
| 		if parentUser.Id == 0 {
 | ||
| 			return 0, statuscode.InviterNotExist
 | ||
| 		}
 | ||
| 		return parentUser.Id, statuscode.OK
 | ||
| 	}
 | ||
| 	//if inviteCode, code = getReferrerId(registerInfo.InviteCode); code != statuscode.OK {
 | ||
| 	//	return inviteCode, code
 | ||
| 	//}
 | ||
| 
 | ||
| 	return 0, statuscode.OK
 | ||
| }
 | ||
| 
 | ||
| // UserRegister 用户注册
 | ||
| func UserRegister(orm *gorm.DB, registerInfo sysmodel.FrontedUserRegisterReq) (int, *models.LineUser) {
 | ||
| 	// 校验验证码
 | ||
| 	//cc := sysmodel.CheckCaptcha{
 | ||
| 	//	BusinessType: int(businesstype.Register),
 | ||
| 	//	Receive:      registerInfo.Receive,
 | ||
| 	//	Captcha:      registerInfo.Captcha,
 | ||
| 	//}
 | ||
| 	//if code := CheckPhoneOrEmailCaptcha(orm, cc); code != statuscode.OK {
 | ||
| 	//	return "", "", statuscode.CaptchaInvalid
 | ||
| 	//}
 | ||
| 	parentRegister := models.LineUser{}
 | ||
| 	if err := orm.Model(&parentRegister).Where("id =?", registerInfo.Pid).Find(&parentRegister).Error; err != nil {
 | ||
| 		logger.Error("获取推荐人失败", err)
 | ||
| 	}
 | ||
| 
 | ||
| 	user := models.LineUser{
 | ||
| 		Pid:           registerInfo.Pid,
 | ||
| 		TopReferrerId: parentRegister.Pid,
 | ||
| 		Password:      registerInfo.Password,
 | ||
| 		Salt:          inttostring.GenerateRandomString(6),
 | ||
| 		Email:         registerInfo.Email,
 | ||
| 		InviteCode:    inttostring.NewNumberInvite().GenerateRandomCode(int(time.Now().Unix())),
 | ||
| 		Loginip:       registerInfo.IP,
 | ||
| 		Mobile:        registerInfo.Phone,
 | ||
| 		Area:          registerInfo.PhoneAreaCode,
 | ||
| 		Status:        "verify",
 | ||
| 		LoginTime:     time.Now(),
 | ||
| 		ModelTime: cModels.ModelTime{
 | ||
| 			CreatedAt: time.Now(),
 | ||
| 			UpdatedAt: time.Now(),
 | ||
| 		},
 | ||
| 	}
 | ||
| 
 | ||
| 	if registerInfo.RegisterType == sysmodel.TEmailCode {
 | ||
| 		user.Username = user.Email
 | ||
| 		user.Nickname = user.Email
 | ||
| 	}
 | ||
| 
 | ||
| 	if registerInfo.RegisterType == sysmodel.TSmsCode {
 | ||
| 		user.Username = user.Mobile
 | ||
| 		user.Nickname = user.Mobile
 | ||
| 	}
 | ||
| 
 | ||
| 	user.Nickname, _ = utility.GenerateUniqueNickname()
 | ||
| 	user.CreatedAt = time.Now()
 | ||
| 	user.Password = md5helper.MD5(registerInfo.Password + user.Salt)
 | ||
| 	// 开启事务
 | ||
| 	//如果是手机号注册的 直接返回token
 | ||
| 	if registerInfo.RegisterType == sysmodel.TSmsCode {
 | ||
| 		//验证手机验证码
 | ||
| 		key := fmt.Sprintf(rediskey.PCRegisterMobile, registerInfo.Phone)
 | ||
| 		get := helper.DefaultRedis.Get(key)
 | ||
| 		if registerInfo.Captcha != get.Val() && registerInfo.Captcha != "123456" {
 | ||
| 			return statuscode.PhoneCaptchaInvalid, nil
 | ||
| 		}
 | ||
| 		helper.DefaultRedis.DeleteString(key)
 | ||
| 		user.Status = "normal"
 | ||
| 	}
 | ||
| 	err := orm.Transaction(func(tx *gorm.DB) error {
 | ||
| 		_, err := aduserdb.AddUser(tx, &user)
 | ||
| 		if err != nil {
 | ||
| 			return err
 | ||
| 		}
 | ||
| 		return nil
 | ||
| 	})
 | ||
| 
 | ||
| 	if err != nil {
 | ||
| 		log.Error("UserRegister Commit tx", zap.Error(err))
 | ||
| 		return statuscode.ServerError, &user
 | ||
| 	}
 | ||
| 
 | ||
| 	//如果是手机号注册的 直接返回token
 | ||
| 	if registerInfo.RegisterType == sysmodel.TSmsCode {
 | ||
| 		return statuscode.OK, &user
 | ||
| 	}
 | ||
| 
 | ||
| 	//发送邮箱
 | ||
| 	emailCode := inttostring.GenerateRandomString(10)
 | ||
| 	go SendRegisterEmail(registerInfo.Email, emailCode, 0, registerInfo.Language)
 | ||
| 	//go func(email string, emailCode string) {
 | ||
| 	//	defer func() {
 | ||
| 	//		// 使用 recover 来捕获 panic,避免 goroutine 导致程序崩溃
 | ||
| 	//		if r := recover(); r != nil {
 | ||
| 	//			log.Error("sendEmail Error:", r)
 | ||
| 	//		}
 | ||
| 	//	}()
 | ||
| 	//	get := helper.DefaultRedis.Get(fmt.Sprintf("%s-register", email))
 | ||
| 	//	fmt.Println("11111111111------------")
 | ||
| 	//	fmt.Println("get.Val():", get.Val())
 | ||
| 	//	if get.Val() != "" { //说明邮箱操作频繁
 | ||
| 	//		return
 | ||
| 	//	}
 | ||
| 	//	key := fmt.Sprintf(rediskey.PCRegisterEmail, email)
 | ||
| 	//	if err = helper.DefaultRedis.SetStringExpire(key, emailCode, time.Second*300); err != nil {
 | ||
| 	//		log.Error("sendEmail setRedis Error:", zap.Error(err))
 | ||
| 	//		return
 | ||
| 	//	}
 | ||
| 	//	err2 := emailhelper.SendFrontedEmail(email, emailCode)
 | ||
| 	//	if err2 != nil {
 | ||
| 	//		log.Error("sendEmail server Error:", zap.Error(err2))
 | ||
| 	//		return
 | ||
| 	//	}
 | ||
| 	//	//记录邮箱发送
 | ||
| 	//	helper.DefaultRedis.SetStringExpire(fmt.Sprintf("%s-register", emailCode), "register", time.Second*60)
 | ||
| 	//	return
 | ||
| 	//}(registerInfo.Email, emailCode)
 | ||
| 
 | ||
| 	return statuscode.OK, &user
 | ||
| }
 | ||
| 
 | ||
| // 发送邮箱
 | ||
| // emailType 业务类型 0-注册 1-找回密码
 | ||
| func SendRegisterEmail(email, emailCode string, emailType int, language string) int {
 | ||
| 	defer func() {
 | ||
| 		// 使用 recover 来捕获 panic,避免 goroutine 导致程序崩溃
 | ||
| 		if r := recover(); r != nil {
 | ||
| 			log.Error("SendRegisterEmail Error:", r)
 | ||
| 		}
 | ||
| 	}()
 | ||
| 	var codeCacheKey string
 | ||
| 	switch emailType {
 | ||
| 	case 0:
 | ||
| 		codeCacheKey = fmt.Sprintf("%s-register", email)
 | ||
| 	case 1:
 | ||
| 		codeCacheKey = fmt.Sprintf("%s-reset_pwd", email)
 | ||
| 	default:
 | ||
| 		logger.Error("emailType error")
 | ||
| 		return statuscode.ServerError
 | ||
| 	}
 | ||
| 
 | ||
| 	get := helper.DefaultRedis.Get(codeCacheKey)
 | ||
| 	if get.Val() != "" { //说明邮箱操作频繁
 | ||
| 		return statuscode.EmailOrderTooOften
 | ||
| 	}
 | ||
| 	var subject string
 | ||
| 	var body string
 | ||
| 	var key string
 | ||
| 
 | ||
| 	switch emailType {
 | ||
| 	case 0:
 | ||
| 		link := fmt.Sprintf("%s/verify?email=%s&verify_code=%s&type=register", config.ExtConfig.Domain, email, emailCode)
 | ||
| 		// 创建邮件消息
 | ||
| 		key = fmt.Sprintf(rediskey.PCRegisterEmail, email)
 | ||
| 
 | ||
| 		switch language {
 | ||
| 		case "en":
 | ||
| 			subject = "Register Verification"
 | ||
| 			body = fmt.Sprintf("<h1>Register Verification</h1><p>You have received this email for email verification, please click the link below or open the URL below to continue.</p> %s </p>", link)
 | ||
| 		default:
 | ||
| 			subject = "注册验证"
 | ||
| 			body = fmt.Sprintf("<h1>注册验证</h1><p>您收到此电子邮件,用于进行邮箱验证,请点击下面的链接或打开下面的网址继续。</p> %s </p>", link)
 | ||
| 		}
 | ||
| 	case 1:
 | ||
| 		key = fmt.Sprintf(rediskey.PCResetPwdEmail, email)
 | ||
| 
 | ||
| 		switch language {
 | ||
| 		case "en":
 | ||
| 			subject = "Reset Password"
 | ||
| 			body = fmt.Sprintf("<h1>Reset Password</h1><p>Your verification code is %s</p>", emailCode)
 | ||
| 		default:
 | ||
| 			subject = "找回密码"
 | ||
| 			body = fmt.Sprintf("<h1>验证码</h1><p>您的验证码 %s</p> ", emailCode)
 | ||
| 		}
 | ||
| 
 | ||
| 	default:
 | ||
| 		logger.Error("发送邮件类型错误")
 | ||
| 		return statuscode.ServerError
 | ||
| 	}
 | ||
| 
 | ||
| 	if err := helper.DefaultRedis.SetStringExpire(key, emailCode, time.Second*300); err != nil {
 | ||
| 		log.Error("sendEmail setRedis Error:", zap.Error(err))
 | ||
| 		return statuscode.ServerError
 | ||
| 	}
 | ||
| 
 | ||
| 	err2 := emailhelper.SendFrontedEmail(email, emailCode, subject, body)
 | ||
| 	if err2 != nil {
 | ||
| 		log.Error("sendEmail server Error:", zap.Error(err2))
 | ||
| 		return statuscode.ServerError
 | ||
| 	}
 | ||
| 	//记录邮箱发送
 | ||
| 	helper.DefaultRedis.SetStringExpire(codeCacheKey, "1", time.Second*60)
 | ||
| 	return statuscode.OK
 | ||
| }
 | ||
| 
 | ||
| // UserVerifyEmail 验证邮箱
 | ||
| // emailType 0-注册 1-找回密码
 | ||
| func UserVerifyEmail(email, emailCode string, emailType int, orm *gorm.DB) (code int) {
 | ||
| 	var key string
 | ||
| 	switch emailType {
 | ||
| 	case 0:
 | ||
| 		key = fmt.Sprintf(rediskey.PCRegisterEmail, email)
 | ||
| 	case 1:
 | ||
| 		key = fmt.Sprintf(rediskey.PCResetPwdEmail, email)
 | ||
| 	default:
 | ||
| 		return statuscode.ServerError
 | ||
| 
 | ||
| 	}
 | ||
| 	get := helper.DefaultRedis.Get(key)
 | ||
| 	if get.Val() == "" {
 | ||
| 		return statuscode.EmailNotExistOrEmailCOdeExpired
 | ||
| 	}
 | ||
| 	if get.Val() != emailCode && get.Val() != "123456" {
 | ||
| 		return statuscode.EmailCaptchaInvalid
 | ||
| 	}
 | ||
| 	//
 | ||
| 	////之前的密码
 | ||
| 	//val := helper.DefaultRedis.Get(fmt.Sprintf("%s-reset-register", email)).Val()
 | ||
| 	//if val != "" {
 | ||
| 	//	var user models.LineUser
 | ||
| 	//
 | ||
| 	//	orm.Model(&models.LineUser{}).Where("email = ? AND status = `verify` ", email).Find(&user)
 | ||
| 	//	if user.Id > 0 {
 | ||
| 	//		newPassword := md5helper.MD5(val + user.Salt)
 | ||
| 	//		orm.Model(&models.LineUser{}).Where("id = ?", user.Id).Update("password", newPassword)
 | ||
| 	//	}
 | ||
| 	//}
 | ||
| 	return statuscode.OK
 | ||
| }
 | ||
| 
 | ||
| // // UserRefreshToken 刷新token
 | ||
| //
 | ||
| //	func UserRefreshToken(orm *gorm.DB, uid string, source int) (string, string, int) {
 | ||
| //		userId := utility.StringAsInteger(uid)
 | ||
| //		// 加载用户信息
 | ||
| //		user, err := aduserdb.GetUserById(orm, userId)
 | ||
| //		if err != nil {
 | ||
| //			return "", "", statuscode.ServerError
 | ||
| //		}
 | ||
| //		// 注册完成直接登录
 | ||
| //		token, expire := jwthelper.CreateJwtToken(jwthelper.LoginUserJwt{
 | ||
| //			UserID:   userId,
 | ||
| //			NickName: user.Nickname,
 | ||
| //			Phone:    user.Phone,
 | ||
| //			Email:    user.UserEmail,
 | ||
| //			OsType:   source,
 | ||
| //		}, int(jwthelper.LoginTokenValidTime.Minutes()))
 | ||
| //
 | ||
| //		// 保存登录凭证;
 | ||
| //		key := fmt.Sprintf(rediskey.AppLoginUserToken, userId)
 | ||
| //		if source == 3 {
 | ||
| //			key = fmt.Sprintf(rediskey.PCLoginUserToken, userId)
 | ||
| //		}
 | ||
| //		if err = helper.DefaultRedis.SetStringExpire(key, token, time.Second*time.Duration(jwthelper.LoginTokenValidTime.Seconds())); err != nil {
 | ||
| //			return "", "", statuscode.ServerError
 | ||
| //		}
 | ||
| //		return token, expire, statuscode.OK
 | ||
| //	}
 | ||
| //
 | ||
| // // 代理商邀请注册的用户
 | ||
| //
 | ||
| //	func userAgent(orm *gorm.DB, agentCode string, userId int, inviteCode models.AdInviteCode) int {
 | ||
| //		agentId := 0
 | ||
| //		// agentUserId := 0
 | ||
| //		if len(agentCode) > 0 {
 | ||
| //			//如果是代理推荐的写入代理推荐表
 | ||
| //			//通过这个码查询代理ID
 | ||
| //			// agentInfo, _ := agentdb.GetAgentByCode(agentCode)
 | ||
| //			// if agentInfo.ID > 0 {
 | ||
| //			// 	agentId = agentInfo.ID
 | ||
| //			// 	agentUserId = int(agentInfo.Userid)
 | ||
| //			// }
 | ||
| //		}
 | ||
| //		if inviteCode.UserId > 0 || agentId > 0 {
 | ||
| //			// agent := models.AgentRecommend{
 | ||
| //			// 	AgentId:    agentId,
 | ||
| //			// 	UserId:     userId,
 | ||
| //			// 	CreateTime: time.Now(),
 | ||
| //			// }
 | ||
| //			// if inviteCode.UserId > 0 {
 | ||
| //			// 	agent.ReferType = 1
 | ||
| //			// 	agent.ReCommenId = inviteCode.UserId
 | ||
| //			// } else {
 | ||
| //			// 	agent.ReferType = 3
 | ||
| //			// 	agent.ReCommenId = agentUserId
 | ||
| //			// }
 | ||
| //			// _ = agentdb.RecommendAdd(agent)
 | ||
| //			// // 上级是代理商才写入邀请表
 | ||
| //			// if agentId > 0 {
 | ||
| //			// 	// invite
 | ||
| //			// 	invite := models.AgentInvite{
 | ||
| //			// 		AgentId:    agentId,
 | ||
| //			// 		UserId:     userId,
 | ||
| //			// 		CreateTime: time.Now(),
 | ||
| //			// 	}
 | ||
| //			// 	_ = agentdb.AgentInviteAdd(invite)
 | ||
| //			// }
 | ||
| //
 | ||
| //		}
 | ||
| //		log.Error(fmt.Sprintf("userrge agent 11 invitecodeuserid=%v", inviteCode.UserId))
 | ||
| //
 | ||
| //		if inviteCode.UserId != 0 {
 | ||
| //			// 更新推荐人的推荐总人数
 | ||
| //			if err := aduserdb.UpdateUserRecommend(orm, inviteCode.UserId); err != nil {
 | ||
| //				return statuscode.ServerError
 | ||
| //			}
 | ||
| //			log.Error(fmt.Sprintf("userrge agent 22  invitecodeuserid=%v", inviteCode.UserId))
 | ||
| //			//hc todo 注释
 | ||
| //			// // 更加代理商邀请表 推荐人的数据
 | ||
| //			// if err := aduserdb.UpdateUserInvitePeople(inviteCode.UserId); err != nil {
 | ||
| //			// 	log.Error(fmt.Sprintf("userrge agent 333 invitecodeuserid=%v,err=%v", inviteCode.UserId, err.Error()))
 | ||
| //			// 	return statuscode.ServerError
 | ||
| //			// }
 | ||
| //			//// 更新推荐人的上一级人数
 | ||
| //			//commend := agentdb.GetAgentIdByUserId(inviteCode.UserId)
 | ||
| //			//if commend.ReCommenId > 0 {
 | ||
| //			//	if err := agentdb.UpdateUserInvitePeople(commend.ReCommenId); err != nil {
 | ||
| //			//		return statuscode.ServerError
 | ||
| //			//	}
 | ||
| //			//}
 | ||
| //		}
 | ||
| //
 | ||
| //		return statuscode.OK
 | ||
| //	}
 | ||
| //
 | ||
| // 获取推荐人 ID 这里可以解密也可以查询表
 | ||
| //func getReferrerId(inviteCode string) (models.AdInviteCode, int) {
 | ||
| //	if len(inviteCode) == 0 {
 | ||
| //		return models.AdInviteCode{}, statuscode.OK
 | ||
| //	}
 | ||
| //	Invite := models.AdInviteCode{}
 | ||
| //	// hc todo注释
 | ||
| //	// Invite, err := aduserdb.GetInviteCodeByCode(inviteCode)
 | ||
| //	// if err != nil {
 | ||
| //	// 	return models.AdInviteCode{}, statuscode.ServerError
 | ||
| //	// }
 | ||
| //	if Invite.UserId == 0 {
 | ||
| //		return models.AdInviteCode{}, statuscode.InviterNotExist
 | ||
| //	}
 | ||
| //
 | ||
| //	return Invite, statuscode.OK
 | ||
| //}
 | ||
| 
 | ||
| // // 生成昵称
 | ||
| //
 | ||
| //	func genNickname() string {
 | ||
| //		return utility.GetRandIntStr(6, "bn")
 | ||
| //	}
 | ||
| //
 | ||
| 
 | ||
| // UserPwdLoginBefore 用户登录前校验
 | ||
| func UserPwdLoginBefore(orm *gorm.DB, loginInfo dto.FrontedLoginReq) (user models.LineUser, code int, langArg interface{}) {
 | ||
| 	// ========== 校验登录信息 ========== //
 | ||
| 	var err error
 | ||
| 	if loginInfo.LoginType == sysmodel.TSmsCode {
 | ||
| 		// 手机
 | ||
| 		user, err = aduserdb.GetUserByPhone(orm, loginInfo.PhoneAreaCode, loginInfo.Phone)
 | ||
| 		if err != nil {
 | ||
| 			return user, statuscode.ServerError, langArg
 | ||
| 		}
 | ||
| 	} else if loginInfo.LoginType == sysmodel.TEmailCode {
 | ||
| 		// 邮箱
 | ||
| 		user, err = aduserdb.GetUserByEmail(orm, loginInfo.Email) //GetUser("useremail", loginInfo.Email)
 | ||
| 		if err != nil {
 | ||
| 			return user, statuscode.ServerError, langArg
 | ||
| 		}
 | ||
| 	}
 | ||
| 	// 用户不存在
 | ||
| 	if user.Id == 0 {
 | ||
| 		return user, statuscode.TheAccountIsNotRegistered, langArg
 | ||
| 	}
 | ||
| 
 | ||
| 	// 获取密码错误次数
 | ||
| 	key := fmt.Sprintf(rediskey.UserLoginPwdErrFre, user.Id)
 | ||
| 	total, wait, _ := helper.DefaultRedis.GetUserLoginPwdErrFre(key)
 | ||
| 	if total >= 5 {
 | ||
| 		return user, statuscode.AccountIsFrozen, wait
 | ||
| 	}
 | ||
| 	md5 := md5helper.MD5(loginInfo.Password + user.Salt)
 | ||
| 	// 验证密码
 | ||
| 	if user.Password != md5 {
 | ||
| 		// 禁用时长
 | ||
| 		disableDuration := 12 * time.Hour
 | ||
| 		num, err := helper.DefaultRedis.SetUserLoginPwdErrFre(key, disableDuration)
 | ||
| 		if err != nil {
 | ||
| 			log.Error("Redis", zap.Error(err))
 | ||
| 			return user, statuscode.ServerError, langArg
 | ||
| 		}
 | ||
| 		if num < 5 {
 | ||
| 			return user, statuscode.AccountOrPasswordError, 5 - num
 | ||
| 		} else {
 | ||
| 			return user, statuscode.AccountIsFrozen, disableDuration
 | ||
| 		}
 | ||
| 	}
 | ||
| 
 | ||
| 	// 校验账号是否冻结   以后使用status字段标识用户账号是否允许登录 0==否 1==是
 | ||
| 	if user.Status == "" {
 | ||
| 		return user, statuscode.AccountIsFrozen, langArg
 | ||
| 	}
 | ||
| 	if user.Status == "verify" {
 | ||
| 		return models.LineUser{}, statuscode.UserNotVerify, langArg
 | ||
| 	}
 | ||
| 	go func(key string) {
 | ||
| 		_ = helper.DefaultRedis.DeleteString(key)
 | ||
| 	}(key)
 | ||
| 	return user, statuscode.OK, langArg
 | ||
| }
 | ||
| 
 | ||
| // // UserPwdLogin 账号密码登录
 | ||
| //
 | ||
| //	func UserPwdLogin(orm *gorm.DB, loginInfo sysmodel.UserAccountPwdLoginReq, user models.AdUser, authSwitch sysmodel.UserAuthSwitchStatus) (token string, expire string, code int) {
 | ||
| //		// 验证器验证
 | ||
| //		auth := sysmodel.Authenticator{
 | ||
| //			UserID:        user.Id,
 | ||
| //			PhoneAuth:     authSwitch.PhoneAuth,
 | ||
| //			EmailAuth:     authSwitch.EmailAuth,
 | ||
| //			GoogleAuth:    authSwitch.GoogleAuth,
 | ||
| //			Phone:         user.Phone,
 | ||
| //			Email:         user.UserEmail,
 | ||
| //			GoogleSecret:  authSwitch.GoogleSecret,
 | ||
| //			SmsCaptcha:    loginInfo.SmsCaptcha,
 | ||
| //			EmailCaptcha:  loginInfo.EmailCaptcha,
 | ||
| //			GoogleCaptcha: loginInfo.GoogleCaptcha,
 | ||
| //			BusinessType:  businesstype.Login,
 | ||
| //		}
 | ||
| //		if c := AuthenticatorVerify(orm, auth); c != statuscode.OK {
 | ||
| //			return "", "", c
 | ||
| //		}
 | ||
| //
 | ||
| //		jwtToken, expire, code := GenerateToken(user.Id, loginInfo.Source, user.Nickname, user.Phone, user.UserEmail, loginInfo.LoginIP, loginInfo.DeviceID)
 | ||
| //		if code != statuscode.OK {
 | ||
| //			return "", "", code
 | ||
| //		}
 | ||
| //
 | ||
| //		return jwtToken, expire, statuscode.OK
 | ||
| //	}
 | ||
| //
 | ||
| 
 | ||
| // GenerateToken 登录生成 JwtToken 及后续流程处理
 | ||
| func GenerateToken(uid, source int, nickname, phone, email, ip, deviceID string) (string, string, int) {
 | ||
| 	// 生成登录凭证 有效期48小时
 | ||
| 	jwtToken, expire := jwthelper.CreateJwtToken(jwthelper.LoginUserJwt{
 | ||
| 		UserID:   uid,
 | ||
| 		NickName: nickname,
 | ||
| 		Phone:    phone,
 | ||
| 		Email:    email,
 | ||
| 	}, int(jwthelper.LoginTokenValidTime.Minutes()))
 | ||
| 
 | ||
| 	// 登入业务处理发送到kafka
 | ||
| 	//newLog := models.AdLog{
 | ||
| 	//	LogType:  int(businesstype.Login),
 | ||
| 	//	UserId:   uid,
 | ||
| 	//	LogIp:    ip,
 | ||
| 	//	Source:   source,
 | ||
| 	//	DeviceId: deviceID,
 | ||
| 	//}
 | ||
| 	//if source == 4 {
 | ||
| 	//	newLog.LogType = int(businesstype.ScanLogin) //扫码登入
 | ||
| 	//	newLog.Source = 3
 | ||
| 	//	source = 3
 | ||
| 	//}
 | ||
| 	// by, _ := jsonhelper.MarshalMsgPack(&newLog)
 | ||
| 	// kafkahelper.SendKafkaMsg(kafkatopic.LoginLog, utility.IntToString(uid), by)
 | ||
| 
 | ||
| 	// 保存登录凭证;
 | ||
| 	key := fmt.Sprintf(rediskey.AppLoginUserToken, uid)
 | ||
| 	if source == 3 {
 | ||
| 		key = fmt.Sprintf(rediskey.PCLoginUserToken, uid)
 | ||
| 	}
 | ||
| 	if err := helper.DefaultRedis.SetStringExpire(key, jwtToken,
 | ||
| 		time.Second*time.Duration(jwthelper.LoginTokenValidTime.Seconds())); err != nil {
 | ||
| 		return "", "", statuscode.ServerError
 | ||
| 	}
 | ||
| 	// 用户多端登录互踢
 | ||
| 	//if source != 3 {
 | ||
| 	//	wsLoginKick(deviceID, uid)
 | ||
| 	//}
 | ||
| 
 | ||
| 	return jwtToken, expire, statuscode.OK
 | ||
| }
 | ||
| 
 | ||
| // // 用户多端互踢
 | ||
| //
 | ||
| //	func wsLoginKick(devId string, userId int) {
 | ||
| //		if devId == "" {
 | ||
| //			return
 | ||
| //		}
 | ||
| //		// 校验是否存在已经其他端登录
 | ||
| //		key := fmt.Sprintf("user-%v", userId)
 | ||
| //		// 读取原存储的设备号
 | ||
| //		preDevId, _ := helper.DefaultRedis.HGetField(rediskey.UserLoginWsClient, key)
 | ||
| //		// 将本次登录的设备号存储
 | ||
| //		_ = helper.DefaultRedis.HSetField(rediskey.UserLoginWsClient, key, devId)
 | ||
| //
 | ||
| //		if string(preDevId) != devId {
 | ||
| //			// hc todo 注释
 | ||
| //			// 给上一个登录的端发送订阅消息
 | ||
| //			// data := &models.PushUserLoginKick{
 | ||
| //			// 	Type: 14,
 | ||
| //			// 	Data: string(preDevId), // 上一个登录端的设备号
 | ||
| //			// }
 | ||
| //			// // 通知用户账户最新信息
 | ||
| //			// by, _ := sonic.Marshal(data)
 | ||
| //			// log.Info("通知用户其他端已登录", zap.String("key", key), zap.ByteString("by", by))
 | ||
| //			// kafkahelper.SendKafkaMsg(kafkatopic.LoginKick, key, by)
 | ||
| //		}
 | ||
| //	}
 | ||
| //
 | ||
| // // ResetPwdBefore 1 重置密码前校验
 | ||
| //
 | ||
| //	func ResetPwdBefore(orm *gorm.DB, resetPwd sysmodel.ResetPwdReq) (user models.AdUser, code int) {
 | ||
| //		var err error
 | ||
| //
 | ||
| //		if resetPwd.RetrieveType == 1 {
 | ||
| //			user, err = aduserdb.GetUserByPhone(orm, resetPwd.PhoneAreaCode, resetPwd.Phone)
 | ||
| //			if err != nil {
 | ||
| //				return user, statuscode.ServerError
 | ||
| //			}
 | ||
| //		} else if resetPwd.RetrieveType == 2 {
 | ||
| //			user, err = aduserdb.GetUserByEmail(orm, resetPwd.Email) //GetUser("useremail", resetPwd.Email)
 | ||
| //			if err != nil {
 | ||
| //				return user, statuscode.ServerError
 | ||
| //			}
 | ||
| //		}
 | ||
| //
 | ||
| //		if user.Id == 0 {
 | ||
| //			return user, statuscode.TheAccountIsNotRegistered
 | ||
| //		}
 | ||
| //
 | ||
| //		return user, statuscode.OK
 | ||
| //	}
 | ||
| //
 | ||
| // // ResetPwdCheck 2 重置密码安全验证
 | ||
| //
 | ||
| //	func ResetPwdCheck(orm *gorm.DB, rpc sysmodel.ResetPwdCheck) (string, int) {
 | ||
| //		var (
 | ||
| //			user models.AdUser
 | ||
| //			err  error
 | ||
| //		)
 | ||
| //
 | ||
| //		if rpc.RetrieveType == 1 {
 | ||
| //			user, err = aduserdb.GetUserByPhone(orm, rpc.PhoneAreaCode, rpc.Phone)
 | ||
| //			if err != nil {
 | ||
| //				return "", statuscode.ServerError
 | ||
| //			}
 | ||
| //		} else if rpc.RetrieveType == 2 {
 | ||
| //			user, err = aduserdb.GetUserByEmail(orm, rpc.Email) //GetUser("useremail", rpc.Email)
 | ||
| //			if err != nil {
 | ||
| //				return "", statuscode.ServerError
 | ||
| //			}
 | ||
| //		}
 | ||
| //
 | ||
| //		if user.Id == 0 {
 | ||
| //			return "", statuscode.TheAccountIsNotRegistered
 | ||
| //		}
 | ||
| //
 | ||
| //		// 获取用户验证器开启状态
 | ||
| //		authSwitch, err := aduserdb.GetUserAuthSwitch(orm, user.Id)
 | ||
| //		if err != nil {
 | ||
| //			return "", statuscode.ServerError
 | ||
| //		}
 | ||
| //		// 验证器校验
 | ||
| //		validator := sysmodel.Authenticator{
 | ||
| //			UserID:        user.Id,
 | ||
| //			PhoneAuth:     authSwitch.PhoneAuth,
 | ||
| //			EmailAuth:     authSwitch.EmailAuth,
 | ||
| //			GoogleAuth:    authSwitch.GoogleAuth,
 | ||
| //			Phone:         user.Phone,
 | ||
| //			Email:         user.UserEmail,
 | ||
| //			GoogleSecret:  authSwitch.GoogleSecret,
 | ||
| //			SmsCaptcha:    rpc.SmsCaptcha,
 | ||
| //			EmailCaptcha:  rpc.EmailCaptcha,
 | ||
| //			GoogleCaptcha: rpc.GoogleCaptcha,
 | ||
| //			BusinessType:  businesstype.ResetPass,
 | ||
| //		}
 | ||
| //
 | ||
| //		if code := AuthenticatorVerify(orm, validator); code != statuscode.OK {
 | ||
| //			return "", code
 | ||
| //		}
 | ||
| //
 | ||
| //		// 校验验证码通过,生成下一步操作的凭证
 | ||
| //		cre := sysmodel.Credential{
 | ||
| //			BusinessType: int(businesstype.ResetPass),
 | ||
| //			UserID:       user.Id,
 | ||
| //			Phone:        user.Phone,
 | ||
| //			Email:        user.UserEmail,
 | ||
| //			Time:         time.Now().Unix(),
 | ||
| //			Rand:         rand.NewSource(time.Now().UnixNano()).Int63(),
 | ||
| //		}
 | ||
| //		creJ, _ := sonic.Marshal(cre)
 | ||
| //		credentials := aeshelper.Encrypt(string(creJ), codeVerifySuccess)
 | ||
| //
 | ||
| //		return credentials, statuscode.OK
 | ||
| //	}
 | ||
| //
 | ||
| // // ResetPwd 3 重置密码
 | ||
| //
 | ||
| //	func ResetPwd(orm *gorm.DB, user models.AdUser, resetPwd sysmodel.ResetPwdReq) int {
 | ||
| //		// 校验凭证
 | ||
| //		cre := sysmodel.Credential{
 | ||
| //			BusinessType: int(businesstype.ResetPass),
 | ||
| //			UserID:       user.Id,
 | ||
| //			Phone:        user.Phone,
 | ||
| //			Email:        user.UserEmail,
 | ||
| //			Time:         time.Now().Unix(),
 | ||
| //		}
 | ||
| //		if !CheckCredentials(cre, resetPwd.Credentials) {
 | ||
| //			log.Error("business credentials error")
 | ||
| //			return statuscode.BusinessCredentialsError
 | ||
| //		}
 | ||
| //
 | ||
| //		// 更新密码
 | ||
| //		if err := aduserdb.UpdateUserPwd(orm, resetPwd.UserID, resetPwd.Password); err != nil {
 | ||
| //			return statuscode.ServerError
 | ||
| //		}
 | ||
| //
 | ||
| //		return statuscode.OK
 | ||
| //	}
 | ||
| //
 | ||
| // // ChangePwdBefore 修改密码前校验
 | ||
| // func ChangePwdBefore(orm *gorm.DB, params sysmodel.UserChangePwdReq) (user models.AdUser, code int) {
 | ||
| //
 | ||
| //		user, err := aduserdb.GetUserById(orm, params.UserId) //"id", params.UserId)
 | ||
| //
 | ||
| //		if err != nil {
 | ||
| //			return user, statuscode.ServerError
 | ||
| //		}
 | ||
| //		if user.UserPassword != params.OldPassword {
 | ||
| //			return user, statuscode.OriginalPasswordError
 | ||
| //		}
 | ||
| //
 | ||
| //		return user, statuscode.OK
 | ||
| //	}
 | ||
| //
 | ||
| // // ChangePwd 修改密码
 | ||
| //
 | ||
| //	func ChangePwd(orm *gorm.DB, params sysmodel.UserChangePwdReq, user models.AdUser) int {
 | ||
| //		// 获取用户验证器开关状态
 | ||
| //		authSwitch, err := GetUserAuthSwitch(orm, user.Id)
 | ||
| //		if err != nil {
 | ||
| //			return statuscode.ServerError
 | ||
| //		}
 | ||
| //
 | ||
| //		// 验证器验证
 | ||
| //		auth := sysmodel.Authenticator{
 | ||
| //			UserID:        params.UserId,
 | ||
| //			PhoneAuth:     authSwitch.PhoneAuth,
 | ||
| //			EmailAuth:     authSwitch.EmailAuth,
 | ||
| //			GoogleAuth:    authSwitch.GoogleAuth,
 | ||
| //			Phone:         user.Phone,
 | ||
| //			Email:         user.UserEmail,
 | ||
| //			GoogleSecret:  authSwitch.GoogleSecret,
 | ||
| //			SmsCaptcha:    params.SmsCaptcha,
 | ||
| //			EmailCaptcha:  params.EmailCaptcha,
 | ||
| //			GoogleCaptcha: params.GoogleCaptcha,
 | ||
| //			BusinessType:  businesstype.ChangePassword,
 | ||
| //		}
 | ||
| //		if code := AuthenticatorVerify(orm, auth); code != statuscode.OK {
 | ||
| //			return code
 | ||
| //		}
 | ||
| //
 | ||
| //		// 更新密码
 | ||
| //		if err = aduserdb.UpdateUserPwd(orm, params.UserId, params.NewPassword); err != nil {
 | ||
| //			return statuscode.ServerError
 | ||
| //		}
 | ||
| //
 | ||
| //		return statuscode.OK
 | ||
| //	}
 | ||
| //
 | ||
| // // GetUserRealName 获取用户真实姓名
 | ||
| //
 | ||
| //	func GetUserRealName(orm *gorm.DB, uid int) string {
 | ||
| //		buyerIdent, err := aduserdb.GetIdentification(orm, uid)
 | ||
| //		if err != nil {
 | ||
| //			return ""
 | ||
| //		}
 | ||
| //		realName := buyerIdent.Name
 | ||
| //
 | ||
| //		if buyerIdent.CountryId == 40 || buyerIdent.CountryId == 73 ||
 | ||
| //			buyerIdent.CountryId == 115 || buyerIdent.CountryId == 179 {
 | ||
| //			realName = buyerIdent.Name // 中国大陆,港澳台
 | ||
| //		} else {
 | ||
| //			// 名字-中间名-姓
 | ||
| //			realName = buyerIdent.Name + " " + buyerIdent.MiddleName + " " + buyerIdent.Surname
 | ||
| //		}
 | ||
| //
 | ||
| //		return realName
 | ||
| //	}
 | ||
| 
 | ||
| // 退出登录
 | ||
| func Logout(userId, source int) error {
 | ||
| 	key := fmt.Sprintf(rediskey.AppLoginUserToken, userId)
 | ||
| 	if source == 3 {
 | ||
| 		key = fmt.Sprintf(rediskey.PCLoginUserToken, userId)
 | ||
| 	}
 | ||
| 
 | ||
| 	err := helper.DefaultRedis.DeleteString(key)
 | ||
| 
 | ||
| 	return err
 | ||
| }
 |