2025-07-24 21:53:18 +08:00

44 lines
1.1 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package users
import (
"context"
"github.com/gogf/gf/v2/errors/gcode"
"github.com/gogf/gf/v2/errors/gerror"
v1 "hotgo/api/api/users/v1"
"hotgo/internal/consts"
"hotgo/internal/dao"
"hotgo/internal/model/entity"
utility "hotgo/utility/jwt"
)
func (c *ControllerV1) Login(ctx context.Context, req *v1.LoginReq) (res *v1.LoginRes, err error) {
// 1. 查找用户
user := &entity.Users{}
err = dao.Users.Ctx(ctx).Where("phone = ?", req.Phone).Scan(user)
if err != nil {
return nil, gerror.NewCode(gcode.CodeDbOperationError, "数据库错误")
}
if user.Id == 0 {
return nil, gerror.NewCode(consts.CodeUserNotFound, "用户不存在")
}
// 2. 校验密码sha256+salt
hashedPwd := utility.HashPassword(req.Password, user.Salt)
if user.Password != hashedPwd {
return nil, gerror.NewCode(consts.CodePasswordInvalid, "密码错误")
}
// 3. 生成JWT Token
token, err := utility.GenerateToken(user.Id)
if err != nil {
return nil, gerror.NewCode(consts.CodeInternalError, "生成Token失败")
}
res = &v1.LoginRes{
Token: token,
}
return
}