Add internal/service/auth.go
This commit is contained in:
69
internal/service/auth.go
Normal file
69
internal/service/auth.go
Normal file
@@ -0,0 +1,69 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"gotest/internal/config"
|
||||
"gotest/internal/middleware"
|
||||
"gotest/internal/model"
|
||||
"gotest/internal/repository"
|
||||
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// AuthService 认证服务
|
||||
type AuthService struct {
|
||||
userRepo *repository.UserRepository
|
||||
cfg *config.Config
|
||||
}
|
||||
|
||||
// NewAuthService 创建认证服务实例
|
||||
func NewAuthService(userRepo *repository.UserRepository, cfg *config.Config) *AuthService {
|
||||
return &AuthService{userRepo: userRepo, cfg: cfg}
|
||||
}
|
||||
|
||||
// Login 用户登录,校验账号密码并返回 JWT token
|
||||
func (s *AuthService) Login(username, password string) (string, *model.User, error) {
|
||||
user, err := s.userRepo.FindByUsername(username)
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return "", nil, errors.New("用户名或密码错误")
|
||||
}
|
||||
return "", nil, err
|
||||
}
|
||||
|
||||
// 校验密码
|
||||
if err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(password)); err != nil {
|
||||
return "", nil, errors.New("用户名或密码错误")
|
||||
}
|
||||
|
||||
// 校验账号状态
|
||||
if user.Status != 1 {
|
||||
return "", nil, errors.New("账号已被禁用")
|
||||
}
|
||||
|
||||
// 生成 token
|
||||
token, err := s.GenerateToken(user)
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
|
||||
return token, user, nil
|
||||
}
|
||||
|
||||
// GenerateToken 根据用户信息生成 JWT token
|
||||
func (s *AuthService) GenerateToken(user *model.User) (string, error) {
|
||||
claims := middleware.Claims{
|
||||
UserID: user.ID,
|
||||
Role: user.Role,
|
||||
RegisteredClaims: jwt.RegisteredClaims{
|
||||
ExpiresAt: jwt.NewNumericDate(time.Now().Add(time.Duration(s.cfg.JWT.ExpireHours) * time.Hour)),
|
||||
IssuedAt: jwt.NewNumericDate(time.Now()),
|
||||
},
|
||||
}
|
||||
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
|
||||
return token.SignedString([]byte(s.cfg.JWT.Secret))
|
||||
}
|
||||
Reference in New Issue
Block a user