73 lines
1.8 KiB
Go
73 lines
1.8 KiB
Go
|
package services
|
||
|
|
||
|
import (
|
||
|
"errors"
|
||
|
"fmt"
|
||
|
"learnsteam/cslms-api/internal/models"
|
||
|
"learnsteam/cslms-api/internal/repositories"
|
||
|
"time"
|
||
|
|
||
|
"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{
|
||
|
GUID: uuid.NewString(),
|
||
|
FirstName: request.FirstName,
|
||
|
LastName: request.LastName,
|
||
|
Username: request.Username,
|
||
|
Password: string(hash),
|
||
|
Gender: request.Gender,
|
||
|
Phone: request.Phone,
|
||
|
UserRole: request.UserRole,
|
||
|
Image: request.Image,
|
||
|
RegisterAt: time.Now(),
|
||
|
}
|
||
|
|
||
|
fmt.Println(newUser)
|
||
|
|
||
|
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
|
||
|
}
|