first commit
This commit is contained in:
60
apps/user/internal/logic/auth/loginuserlogic.go
Normal file
60
apps/user/internal/logic/auth/loginuserlogic.go
Normal file
@@ -0,0 +1,60 @@
|
||||
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))
|
||||
}
|
||||
Reference in New Issue
Block a user