lv8girl!
This commit is contained in:
87
internal/services/auth.go
Normal file
87
internal/services/auth.go
Normal file
@@ -0,0 +1,87 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"lv8girl/internal/models"
|
||||
"lv8girl/internal/repositories"
|
||||
)
|
||||
|
||||
type AuthService struct {
|
||||
userRepo *repositories.UserRepository
|
||||
}
|
||||
|
||||
func NewAuthService() *AuthService {
|
||||
return &AuthService{
|
||||
userRepo: repositories.NewUserRepository(),
|
||||
}
|
||||
}
|
||||
|
||||
type LoginResult struct {
|
||||
Success bool
|
||||
User *models.User
|
||||
Error string
|
||||
}
|
||||
|
||||
func (s *AuthService) Login(login, password string) LoginResult {
|
||||
user, err := s.userRepo.FindByUsernameOrEmail(login)
|
||||
if err != nil {
|
||||
return LoginResult{Success: false, Error: "用户名/邮箱或密码错误"}
|
||||
}
|
||||
|
||||
if !s.userRepo.CheckPassword(password, user.PasswordHash) {
|
||||
return LoginResult{Success: false, Error: "用户名/邮箱或密码错误"}
|
||||
}
|
||||
|
||||
switch user.Status {
|
||||
case "pending":
|
||||
return LoginResult{Success: false, Error: "您的账号正在等待管理员审核,请耐心等待。"}
|
||||
case "rejected":
|
||||
return LoginResult{Success: false, Error: "您的账号审核未通过,无法登录。如有疑问,请联系管理员。"}
|
||||
case "approved":
|
||||
if user.Role == "banned" {
|
||||
return LoginResult{Success: false, Error: "您的账号已被封禁,请联系管理员"}
|
||||
}
|
||||
default:
|
||||
return LoginResult{Success: false, Error: "账号状态异常,请联系管理员"}
|
||||
}
|
||||
|
||||
s.userRepo.UpdateLastActive(user.ID)
|
||||
return LoginResult{Success: true, User: user}
|
||||
}
|
||||
|
||||
type RegisterResult struct {
|
||||
Success bool
|
||||
Error string
|
||||
}
|
||||
|
||||
func (s *AuthService) Register(username, email, password string) RegisterResult {
|
||||
if len(username) < 3 || len(username) > 20 {
|
||||
return RegisterResult{Success: false, Error: "用户名长度必须在3-20个字符之间"}
|
||||
}
|
||||
|
||||
if s.userRepo.ExistsByUsernameOrEmail(username, email) {
|
||||
return RegisterResult{Success: false, Error: "用户名或邮箱已被注册"}
|
||||
}
|
||||
|
||||
passwordHash, err := s.userRepo.HashPassword(password)
|
||||
if err != nil {
|
||||
return RegisterResult{Success: false, Error: "注册失败,请稍后重试"}
|
||||
}
|
||||
|
||||
user := &models.User{
|
||||
Username: username,
|
||||
Email: email,
|
||||
PasswordHash: passwordHash,
|
||||
Role: "user",
|
||||
Status: "pending",
|
||||
}
|
||||
|
||||
if err := s.userRepo.Create(user); err != nil {
|
||||
return RegisterResult{Success: false, Error: "注册失败,请稍后重试"}
|
||||
}
|
||||
|
||||
return RegisterResult{Success: true}
|
||||
}
|
||||
|
||||
func (s *AuthService) InitAdmin() error {
|
||||
return s.userRepo.CreateAdminIfNotExists()
|
||||
}
|
||||
Reference in New Issue
Block a user