git-subtree-dir: server git-subtree-mainline:c4e617ada7git-subtree-split:e64421295f
93 lines
2.3 KiB
Go
93 lines
2.3 KiB
Go
package service
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"time"
|
|
|
|
"slogan-agent/common"
|
|
"slogan-agent/styleagent/dao"
|
|
"slogan-agent/styleagent/model/entity"
|
|
|
|
"github.com/golang-jwt/jwt/v5"
|
|
"golang.org/x/crypto/bcrypt"
|
|
)
|
|
|
|
type userService struct{}
|
|
|
|
var UserService = new(userService)
|
|
|
|
func (s *userService) Register(ctx context.Context, account, password, name string) (int64, error) {
|
|
if account == "" || password == "" {
|
|
return 0, errors.New("账号和密码不能为空")
|
|
}
|
|
existing, err := dao.User.GetByAccount(ctx, account)
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
if existing != nil {
|
|
return 0, errors.New("账号已存在")
|
|
}
|
|
hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
if name == "" {
|
|
name = account
|
|
}
|
|
return dao.User.Insert(ctx, &entity.User{
|
|
Role: "user",
|
|
Username: account,
|
|
Password: string(hash),
|
|
Name: name,
|
|
})
|
|
}
|
|
|
|
func (s *userService) Login(ctx context.Context, account, password string) (*entity.User, string, error) {
|
|
if account == "" {
|
|
return nil, "", errors.New("请输入账号")
|
|
}
|
|
user, err := dao.User.GetByAccount(ctx, account)
|
|
if err != nil {
|
|
return nil, "", err
|
|
}
|
|
if user == nil {
|
|
return nil, "", errors.New("账号不存在")
|
|
}
|
|
if bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(password)) != nil {
|
|
return nil, "", errors.New("密码错误")
|
|
}
|
|
now := time.Now()
|
|
claims := common.JwtClaims{
|
|
UserId: user.Id,
|
|
Role: user.Role,
|
|
RegisteredClaims: jwt.RegisteredClaims{
|
|
ExpiresAt: jwt.NewNumericDate(now.Add(7 * 24 * time.Hour)),
|
|
IssuedAt: jwt.NewNumericDate(now),
|
|
},
|
|
}
|
|
token, err := jwt.NewWithClaims(jwt.SigningMethodHS256, claims).SignedString([]byte(common.GetJwtSecret()))
|
|
if err != nil {
|
|
return nil, "", err
|
|
}
|
|
return user, token, nil
|
|
}
|
|
|
|
func (s *userService) ChangePassword(ctx context.Context, userId int64, oldPwd, newPwd string) error {
|
|
user, err := dao.User.GetOne(ctx, userId)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if user == nil {
|
|
return errors.New("用户不存在")
|
|
}
|
|
if bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(oldPwd)) != nil {
|
|
return errors.New("原密码错误")
|
|
}
|
|
hash, err := bcrypt.GenerateFromPassword([]byte(newPwd), bcrypt.DefaultCost)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
return dao.User.UpdateFields(ctx, userId, map[string]any{"password": string(hash)})
|
|
}
|