2024-08-30 11:19:25 +08:00

112 lines
2.4 KiB
Go

package controller
import (
"crypto/md5"
"encoding/hex"
"fmt"
"github.com/gin-gonic/gin"
"vote-admin-api/api/dao"
"vote-admin-api/api/dto"
"vote-admin-api/api/requests"
"vote-admin-api/api/responses"
"vote-admin-api/config"
"vote-admin-api/global"
"vote-admin-api/utils"
)
type Public struct{}
// Login 登陆
func (b *Public) Login(c *gin.Context) {
publicRequest := requests.PublicRequest{}
req := publicRequest.Login
if err := c.ShouldBind(&req); err != nil {
responses.FailWithMessage(err.Error(), c)
return
}
// 参数验证
if err := global.Validate.Struct(req); err != nil {
responses.FailWithMessage(utils.Translate(err), c)
return
}
if err := c.ShouldBind(&req); err != nil {
responses.FailWithMessage(err.Error(), c)
return
}
// 验证验证码
if config.C.Env == "prod" {
isValid := utils.VerifyCaptcha(req.CaptchaId, req.Captcha)
if !isValid {
// 验证码错误
responses.FailWithMessage("验证码错误", c)
return
}
}
// 获取用户信息
AdminUserDao := dao.AdminUserDao{}
maps := make(map[string]interface{})
maps["access"] = req.Access
adminUser, err := AdminUserDao.GetAdminUser(maps)
if err != nil || adminUser == nil {
responses.FailWithMessage("用户名或密码错误", c)
return
}
// 检测用户密码
password := md5.Sum([]byte(req.Password + adminUser.Salt))
// 将哈希值转换为16进制字符串
passwordString := hex.EncodeToString(password[:])
fmt.Println(passwordString)
if passwordString != adminUser.Password {
responses.FailWithMessage("用户名或密码错误", c)
return
}
// 检测用户状态
if adminUser.IsDeleted == 1 {
responses.FailWithMessage("非法用户", c)
return
}
if adminUser.IsDisabled == 1 {
responses.FailWithMessage("您的账号已被禁用,请联系管理员处理", c)
return
}
// 下发token
token := &utils.Token{
UserId: fmt.Sprintf("%d", adminUser.UserId),
}
// 生成jwt
jwt, err := token.NewJWT()
if err != nil || jwt == "" {
responses.FailWithMessage("登陆失败", c)
return
}
g := dto.AdminLoginDto(adminUser)
g.LoadToken(jwt)
responses.OkWithData(g, c)
}
// GetCaptcha 获取验证码
func (b *Public) GetCaptcha(c *gin.Context) {
id, b64s, err := utils.GenerateCaptcha()
if err != nil {
responses.FailWithMessage("验证码获取失败", c)
}
responses.OkWithData(gin.H{
"id": id,
"b64s": b64s,
}, c)
}