package controller import ( "context" "fmt" "github.com/gin-gonic/gin" "github.com/go-playground/validator/v10" "hongze/hongze_yb_en_api/controller/resp" "hongze/hongze_yb_en_api/global" "hongze/hongze_yb_en_api/models/english_report_email" "hongze/hongze_yb_en_api/models/msg_code" "hongze/hongze_yb_en_api/models/session" "hongze/hongze_yb_en_api/services" "hongze/hongze_yb_en_api/utils" "time" ) type AuthController struct { } func (a *AuthController) Login(c *gin.Context) { req := new(services.LoginReq) err := c.ShouldBind(&req) if err != nil { errs, ok := err.(validator.ValidationErrors) if !ok { resp.FailData("参数解析失败", "Err:"+err.Error(), c) return } resp.FailData("参数解析失败", errs.Translate(global.Trans), c) return } if req.Account == "" { resp.Fail("邮箱或手机号错误", c) return } userEmail := new(english_report_email.Email) emailItem := new(english_report_email.Email) if req.Type == 1 { userEmail, err = emailItem.GetByEmail(req.Account) if err != nil || userEmail.IsDeleted == 1 { if err == utils.ErrNoRow || userEmail.IsDeleted == 1 { resp.Unregistered("账号未注册", c) return } resp.FailData("获取客户邮箱信息失败 ", "Err:"+err.Error(), c) return } } else { userEmail, err := emailItem.GetByMobile(req.Account, req.CountryCode) if err != nil || userEmail.IsDeleted == 1 { if err == utils.ErrNoRow || userEmail.IsDeleted == 1 { resp.Unbound("手机号未绑定", c) return } resp.FailData("获取客户邮箱信息失败 ", "Err:"+err.Error(), c) return } } password := utils.MD5(req.Password + utils.KEY) sysUser, err := english_report_email.CheckUserPwd(req.Type, req.CountryCode, req.Account, password) if err != nil { resp.FailData("Login failed. Please check your entries and try again.", "Err:"+err.Error(), c) return } if sysUser == nil { resp.Fail("Login failed. Please check your entries and try again.", c) return } if sysUser.Enable == 0 { resp.Fail("Your account has been disabled, please contact stephanie@hzinsights.com", c) return } if sysUser.Status == 3 { resp.Expired("试用权限超期", c) return } account := utils.MD5(req.Account) token, err := utils.GenToken(account) sysSession := new(session.EnglishYbSession) sysSession.UserId = int(sysUser.Id) //现在要求永不过期 sysSession.ExpireTime = time.Now().AddDate(99, 0, 0) sysSession.CreatedTime = time.Now() sysSession.LastUpdatedTime = time.Now() sysSession.AccessToken = token err = sysSession.AddSession() fmt.Println("id:", sysSession.SessionId) if err != nil { resp.FailData("新增session信息失败", "Err:"+err.Error(), c) return } respItem := session.LoginResp{ Mobile: sysUser.Mobile, Email: sysUser.Email, CountryCode: sysUser.CountryCode, Name: sysUser.Name, EnglishYbSession: sysSession, } resp.OkData("登陆成功", respItem, c) } func (a *AuthController) Register(c *gin.Context) { req := new(services.RegisterReq) err := c.ShouldBind(&req) if err != nil { errs, ok := err.(validator.ValidationErrors) if !ok { resp.FailData("参数解析失败", "Err:"+err.Error(), c) return } resp.FailData("参数解析失败", errs.Translate(global.Trans), c) return } code := global.Redis.Get(context.TODO(), req.Email).Val() fmt.Println("code:", code) if code == "" || code != req.SmsCode { resp.Fail("Verification code error.", c) return } emailItem, err := english_report_email.CheckUser(req.Email) if err != nil && err != utils.ErrNoRow { resp.FailData("检测用户重复错误, Err:", err.Error(), c) return } userId := 0 password := utils.MD5(req.Password + utils.KEY) if emailItem.Id > 0 { if emailItem.Status == 1 && emailItem.Password == "" { //已经是正式用户,更新密码即可 emailItem.Password = password emailItem.ModifyTime = time.Now() emailItem.RegisterTime = time.Now() err = emailItem.Update([]string{"Password", "ModifyTime", "RegisterTime"}) if err != nil { resp.FailMsg("修改密码失败", "修改密码失败,Err:"+err.Error(), c) return } userId = int(emailItem.Id) } else if emailItem.Status == 1 && emailItem.Password != "" { resp.Registered("邮箱已注册.", c) return } else if emailItem.Status == 2 { resp.Registered("邮箱已注册.", c) return } else if emailItem.Status == 3 { resp.Expired("试用权限超期", c) return } } else { //状态为临时 user := english_report_email.Email{ Name: req.Name, CompanyName: req.CompanyName, Email: req.Email, Password: password, Enable: 1, Status: 2, RegisterTime: time.Now(), } user.Set() err = user.Add() if err != nil { resp.FailData("新增用户信息失败"+"Err:"+err.Error(), "Err:"+err.Error(), c) return } userId = int(user.Id) } sysSession := new(session.EnglishYbSession) if userId > 0 { account := utils.MD5(req.Email) token, err := utils.GenToken(account) sysSession.UserId = userId //现在要求永不过期 sysSession.ExpireTime = time.Now().AddDate(99, 0, 0) sysSession.CreatedTime = time.Now() sysSession.LastUpdatedTime = time.Now() sysSession.AccessToken = token err = sysSession.AddSession() fmt.Println("id:", sysSession.SessionId) if err != nil { resp.FailData("新增session信息失败", "Err:"+err.Error(), c) return } } respItem := session.LoginResp{ Email: req.Email, Name: req.Name, EnglishYbSession: sysSession, } resp.OkData("注册成功", respItem, c) } // @Title 修改密码 // @Description 修改密码 // @Param request body models.ModifyPwdReq true "type json string" // @Success 200 {object} models.LoginResp // @router /modifyPwd [post] func (a *AuthController) ModifyPwd(c *gin.Context) { req := new(services.ModifyPwdReq) err := c.ShouldBind(&req) if err != nil { errs, ok := err.(validator.ValidationErrors) if !ok { resp.FailData("参数解析失败", "Err:"+err.Error(), c) return } resp.FailData("参数解析失败", errs.Translate(global.Trans), c) return } userinfo := services.GetInfoByClaims(c) if req.NewPwd == "" { resp.Fail("Please enter a new password", c) return } if req.OldPwd == "" { resp.Fail("Please enter the original password", c) return } if req.OldPwd != userinfo.Password { resp.Fail("The old password is wrong, please re-enter.", c) return } password := utils.MD5(req.NewPwd + utils.KEY) emailitem := english_report_email.Email{ Id: userinfo.Id, Password: password, } emailitem.ModifyTime = time.Now() err = emailitem.Update([]string{"Password"}) if err != nil { resp.FailMsg("修改密码失败", "修改密码失败,Err:"+err.Error(), c) return } resp.Ok("修改成功", c) } // GetSmsCode 获取短信验证码接口 // @Tags 用户模块 // @Summary 获取短信验证码 // @Description 获取短信验证码接口 // @Security ApiKeyAuth // @securityDefinitions.basic BasicAuth // @Param Mobile query string true "手机号" // @Param AreaNum query string true "手机国际区号(中国大陆:86)" // @Accept json // @Product json // @Success 200 {string} string 获取验证码成功 // @Failure 400 {string} string 手机号不能为空,请输入手机号 // @Router /smsCode [get] func (a *AuthController) GetSmsCode(c *gin.Context) { mobile := c.DefaultQuery("Mobile", "") areaNum := c.DefaultQuery("AreaNum", "") err, errMsg := services.SendSmsCode(mobile, areaNum) if err != nil { if errMsg != "" { errMsg = "获取验证码失败" } resp.Fail("mobile phone number format is wrong.", c) return } resp.Ok("获取验证码成功", c) } // GetEmailCode 获取邮箱验证码接口 // @Tags 用户模块 // @Summary 获取邮箱验证码 // @Description 获取邮箱验证码 // @Security ApiKeyAuth // @securityDefinitions.basic BasicAuth // @Param email query string true "电子邮箱账号" // @Accept json // @Product json // @Success 200 {string} string 获取验证码成功 // @Failure 400 {string} string 请输入邮箱地址 // @Router /emailCode [get] func (a *AuthController) GetEmailCode(c *gin.Context) { email := c.DefaultQuery("Email", "") if email == "" { resp.Fail("请输入邮箱地址", c) return } if !utils.ValidateEmailFormatat(email) { resp.Fail("邮箱格式错误,请重新输入", c) return } name := c.DefaultQuery("Name", "") if name == "" { emailItem := new(english_report_email.Email) userEmail, err := emailItem.GetByEmail(email) if err != nil && err != utils.ErrNoRow { resp.FailData("获取客户邮箱信息失败 ", "Err:"+err.Error(), c) return } if userEmail != nil { name = userEmail.Name } } err, errMsg := services.SendEmailCode(name, email) if err != nil { if errMsg != "" { errMsg = "获取验证码失败" } resp.Fail(errMsg, c) return } resp.Ok("获取验证码成功", c) } func (a *AuthController) BindMobile(c *gin.Context) { req := new(services.BindMobileReq) err := c.ShouldBind(&req) if err != nil { errs, ok := err.(validator.ValidationErrors) if !ok { resp.FailData("参数解析失败", "Err:"+err.Error(), c) return } resp.FailData("参数解析失败", errs.Translate(global.Trans), c) return } userinfo := services.GetInfoByClaims(c) if req.Mobile == "" { resp.Fail("手机号不能为空", c) return } if req.SmsCode == "" { resp.Fail("验证码不能为空", c) return } if req.CountryCode == "" { resp.Fail("区号不能为空", c) return } emailItem := new(english_report_email.Email) userEmail, err := emailItem.GetByMobile(req.Mobile, req.CountryCode) if err != nil && err != utils.ErrNoRow { resp.FailData("获取客户邮箱信息失败 ", "Err:"+err.Error(), c) return } if userEmail.Id != 0 { resp.Bound("手机号已绑定 ", c) return } _, err = msg_code.GetMsgCode(req.Mobile, req.SmsCode) if err != nil { resp.Fail("Verification code error."+err.Error(), c) return } user := english_report_email.Email{ Id: userinfo.Id, Mobile: req.Mobile, CountryCode: req.CountryCode, } user.ModifyTime = time.Now() err = user.Update([]string{"Mobile", "CountryCode", "ModifyTime"}) if err != nil { resp.FailMsg("绑定手机号失败", "修改手机号失败,Err:"+err.Error(), c) return } resp.Ok("绑定成功", c) } func (a *AuthController) ForgetPwd(c *gin.Context) { req := new(services.ForgetPwdReq) err := c.ShouldBind(&req) if err != nil { errs, ok := err.(validator.ValidationErrors) if !ok { resp.FailData("参数解析失败", "Err:"+err.Error(), c) return } resp.FailData("参数解析失败", errs.Translate(global.Trans), c) return } if req.Account == "" { resp.Fail("账号不能为空", c) return } if req.SmsCode == "" { resp.Fail("验证码不能为空", c) return } if req.Password == "" { resp.Fail("Please enter a new password", c) return } userEmail := new(english_report_email.Email) emailItem := new(english_report_email.Email) if req.Type == 1 { userEmail, err = emailItem.GetByEmail(req.Account) if err != nil || userEmail.IsDeleted == 1 { if err == utils.ErrNoRow || userEmail.IsDeleted == 1 || userEmail.Password == "" { resp.Unregistered("账号未注册", c) return } resp.FailData("获取客户邮箱信息失败 ", "Err:"+err.Error(), c) return } } else { userEmail, err = emailItem.GetByMobile(req.Account, req.CountryCode) if err != nil || userEmail.IsDeleted == 1 { if err == utils.ErrNoRow || userEmail.IsDeleted == 1 || userEmail.Password == "" { resp.Unbound("手机号未绑定", c) return } resp.FailData("获取客户邮箱信息失败 ", "Err:"+err.Error(), c) return } } if req.Type == 2 { _, err = msg_code.GetMsgCode(req.Account, req.SmsCode) if err != nil { resp.Fail("Verification code error."+err.Error(), c) return } } else { code := global.Redis.Get(context.TODO(), req.Account).Val() if code == "" || code != req.SmsCode { resp.Fail("Verification code error.", c) return } } cols := []string{"ModifyTime","Password"} password := utils.MD5(req.Password + utils.KEY) emailitem := english_report_email.Email{ Id: userEmail.Id, Password: password, } //if emailitem.RegisterTime.IsZero() { // emailitem.RegisterTime = time.Now() // cols = append(cols, "RegisterTime") //} emailitem.ModifyTime = time.Now() err = emailitem.Update(cols) if err != nil { resp.FailMsg("修改密码失败", "修改密码失败,Err:"+err.Error(), c) return } resp.Ok("修改成功", c) } func (a *AuthController) ModifyMobile(c *gin.Context) { req := new(services.ModifyMobile) err := c.ShouldBind(&req) if err != nil { errs, ok := err.(validator.ValidationErrors) if !ok { resp.FailData("参数解析失败", "Err:"+err.Error(), c) return } resp.FailData("参数解析失败", errs.Translate(global.Trans), c) return } userinfo := services.GetInfoByClaims(c) if req.NewMobile == "" { resp.Fail("Please enter a new phone number", c) return } if req.OldMobile == "" { resp.Fail("Please enter the original phone number", c) return } if req.OldMobile != userinfo.Mobile { resp.Fail("The old phone number is wrong, please re-enter.", c) return } if req.SmsCode == "" { resp.Fail("验证码不能为空", c) return } if req.CountryCode == "" { resp.Fail("区号不能为空", c) return } emailitem := english_report_email.Email{ Id: userinfo.Id, Mobile: req.NewMobile, CountryCode: req.CountryCode, } emailitem.ModifyTime = time.Now() err = emailitem.Update([]string{"Mobile", "CountryCode", "ModifyTime"}) if err != nil { resp.FailMsg("修改手机号失败", "修改手机号失败,Err:"+err.Error(), c) return } resp.Ok("修改成功", c) }