learnsteam-quiz-api/internal/services/auth.go

64 lines
1.6 KiB
Go
Raw Normal View History

2023-10-19 22:47:12 +09:00
package services
import (
"errors"
2023-11-17 01:38:01 +09:00
"learnsteam/learsteam-quiz-api/internal/models"
"learnsteam/learsteam-quiz-api/internal/repositories"
2023-10-19 22:47:12 +09:00
"github.com/google/uuid"
"golang.org/x/crypto/bcrypt"
)
type authService struct {
userRepository repositories.UserRepository
tokenRepository repositories.TokenRepository
}
type AuthService interface {
Register(*models.RegisterRequest) (*models.User, error)
Login(*models.LoginRequest) (*models.User, error)
}
func NewAuthService(userRepository repositories.UserRepository, tokenRepository repositories.TokenRepository) AuthService {
return &authService{
userRepository: userRepository,
tokenRepository: tokenRepository,
}
}
func (s *authService) Register(request *models.RegisterRequest) (*models.User, error) {
hash, err := bcrypt.GenerateFromPassword([]byte(request.Password), 10)
if err != nil {
return nil, errors.New("fail to hash password")
}
// Create the user
newUser := models.User{
ID: uuid.NewString(),
Username: request.Username,
2023-11-17 01:38:01 +09:00
Name: request.Name,
Score: 0,
2023-10-19 22:47:12 +09:00
Password: string(hash),
}
user, err := s.userRepository.Create(&newUser)
if err != nil {
return nil, errors.New("fail to create user")
}
return user, err
}
func (s *authService) Login(request *models.LoginRequest) (*models.User, error) {
user, err := s.userRepository.FindByUsername(request.Username)
if err != nil || user == nil {
return nil, errors.New("invalid user or password")
}
err = bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(request.Password))
if err != nil {
return nil, errors.New("invalid user or password")
}
return user, nil
}