You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
69 lines
1.5 KiB
69 lines
1.5 KiB
package auth
|
|
|
|
import (
|
|
"context"
|
|
"crypto/md5"
|
|
"fmt"
|
|
|
|
"github.com/youruser/base/internal/svc"
|
|
"github.com/youruser/base/internal/types"
|
|
"github.com/youruser/base/internal/util/jwt"
|
|
"github.com/youruser/base/model"
|
|
|
|
"github.com/zeromicro/go-zero/core/logx"
|
|
)
|
|
|
|
type LoginLogic struct {
|
|
logx.Logger
|
|
ctx context.Context
|
|
svcCtx *svc.ServiceContext
|
|
}
|
|
|
|
// 用户登录
|
|
func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
|
|
return &LoginLogic{
|
|
Logger: logx.WithContext(ctx),
|
|
ctx: ctx,
|
|
svcCtx: svcCtx,
|
|
}
|
|
}
|
|
|
|
func (l *LoginLogic) Login(req *types.LoginRequest) (resp *types.LoginResponse, err error) {
|
|
// 查询用户
|
|
user, err := model.FindOneByEmail(l.ctx, l.svcCtx.DB, req.Email)
|
|
if err != nil {
|
|
if err == model.ErrNotFound {
|
|
return &types.LoginResponse{
|
|
Code: 404,
|
|
Message: "用户不存在或密码错误",
|
|
Success: false,
|
|
}, nil
|
|
}
|
|
return nil, fmt.Errorf("查询用户失败: %v", err)
|
|
}
|
|
|
|
// 加密输入的密码并与数据库密码对比
|
|
inputPassword := fmt.Sprintf("%x", md5.Sum([]byte(req.Password)))
|
|
if user.Password != inputPassword {
|
|
return &types.LoginResponse{
|
|
Code: 400,
|
|
Message: "用户不存在或密码错误",
|
|
Success: false,
|
|
}, nil
|
|
}
|
|
|
|
// 生成 Token
|
|
token, err := jwt.GenerateToken(user.Id, user.Username, user.Email)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("生成Token失败: %v", err)
|
|
}
|
|
|
|
l.Infof("登录成功,userId=%d", user.Id)
|
|
|
|
return &types.LoginResponse{
|
|
Code: 200,
|
|
Message: "登录成功",
|
|
Success: true,
|
|
Token: token,
|
|
}, nil
|
|
}
|
|
|