Files
tianyuan-api-server/apps/user/internal/logic/auth/loginuserlogic.go
2024-10-02 00:57:17 +08:00

61 lines
1.4 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 authlogic
import (
"context"
"crypto/sha256"
"encoding/hex"
"errors"
jwtx "tianyuan-api/pkg/jwt"
"tianyuan-api/apps/user/internal/svc"
"tianyuan-api/apps/user/user"
"github.com/zeromicro/go-zero/core/logx"
)
type LoginUserLogic struct {
ctx context.Context
svcCtx *svc.ServiceContext
logx.Logger
}
func NewLoginUserLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginUserLogic {
return &LoginUserLogic{
ctx: ctx,
svcCtx: svcCtx,
Logger: logx.WithContext(ctx),
}
}
// 登录接口
func (l *LoginUserLogic) LoginUser(in *user.LoginReq) (*user.LoginResp, error) {
if in.Username == "" || in.Password == "" {
return nil, errors.New("用户名或密码不能为空")
}
// 使用 FindOneByUsername 查找用户
users, err := l.svcCtx.UserModel.FindOneByUsername(l.ctx, in.Username)
if err != nil {
return nil, errors.New("用户未注册")
}
// 验证密码
if hashPassword(in.Password) != users.Password {
return nil, errors.New("密码错误")
}
// 生成 JWT token调用封装好的函数
token, err := jwtx.GenerateJwtToken(users.Id, l.svcCtx.Config.AuthJWT.AccessSecret, l.svcCtx.Config.AuthJWT.AccessExpire)
if err != nil {
return nil, err
}
return &user.LoginResp{
Token: token,
}, nil
}
func hashPassword(password string) string {
h := sha256.New()
h.Write([]byte(password))
return hex.EncodeToString(h.Sum(nil))
}