Files
tp/serv_nginx/api_bb/internal/service/auth_service.go
T

64 lines
1.5 KiB
Go

// service/auth_service.go
package service
import (
"errors"
"go-rest-api/internal/models"
"go-rest-api/internal/repository"
)
type AuthService interface {
Register(user *models.User) error
Login(email, password string) (*models.User, string, error)
GetUserProfile(userID uint) (*models.User, error)
}
type authService struct {
userRepo repository.UserRepository
jwtService JWTService
}
func NewAuthService(userRepo repository.UserRepository, jwtService JWTService) AuthService {
return &authService{
userRepo: userRepo,
jwtService: jwtService,
}
}
func (s *authService) Register(user *models.User) error {
// Проверяем, существует ли пользователь
existingUser, err := s.userRepo.FindByEmail(user.Email)
if err == nil && existingUser != nil {
return errors.New("user with this email already exists")
}
// Хешируем пароль
if err := user.HashPassword(); err != nil {
return err
}
return s.userRepo.Create(user)
}
func (s *authService) Login(email, password string) (*models.User, string, error) {
user, err := s.userRepo.FindByEmail(email)
if err != nil {
return nil, "", errors.New("invalid email or password")
}
if !user.CheckPassword(password) {
return nil, "", errors.New("invalid email or password")
}
token, err := s.jwtService.GenerateToken(user.ID, user.Email)
if err != nil {
return nil, "", err
}
return user, token, nil
}
func (s *authService) GetUserProfile(userID uint) (*models.User, error) {
return s.userRepo.FindByID(userID)
}