73 lines
1.7 KiB
Go
73 lines
1.7 KiB
Go
package service
|
|
|
|
import (
|
|
"context"
|
|
|
|
"github.com/aykhans/oh-my-chat/internal/core/domain"
|
|
"github.com/aykhans/oh-my-chat/internal/core/port"
|
|
"github.com/aykhans/oh-my-chat/internal/core/utils"
|
|
)
|
|
|
|
type AuthService struct {
|
|
userRepository port.UserRepository
|
|
tokenService port.TokenService
|
|
}
|
|
|
|
// NewAuthService creates a new auth service instance
|
|
func NewAuthService(userRepository port.UserRepository, tokenService port.TokenService) *AuthService {
|
|
return &AuthService{
|
|
userRepository,
|
|
tokenService,
|
|
}
|
|
}
|
|
|
|
func (authService *AuthService) LoginByEmail(
|
|
ctx context.Context,
|
|
email, password string,
|
|
) (string, error) {
|
|
user, err := authService.userRepository.GetUserByEmail(ctx, email)
|
|
if err != nil {
|
|
if err == domain.ErrDataNotFound {
|
|
return "", domain.ErrInvalidEmailCredentials
|
|
}
|
|
return "", domain.ErrInternal
|
|
}
|
|
|
|
err = utils.ComparePassword(password, user.Password)
|
|
if err != nil {
|
|
return "", domain.ErrInvalidEmailCredentials
|
|
}
|
|
|
|
accessToken, err := authService.tokenService.CreateToken(user)
|
|
if err != nil {
|
|
return "", domain.ErrTokenCreation
|
|
}
|
|
|
|
return accessToken, nil
|
|
}
|
|
|
|
func (authService *AuthService) LoginByUsername(
|
|
ctx context.Context,
|
|
username, password string,
|
|
) (string, error) {
|
|
user, err := authService.userRepository.GetUserByEmail(ctx, username)
|
|
if err != nil {
|
|
if err == domain.ErrDataNotFound {
|
|
return "", domain.ErrInvalidUsernameCredentials
|
|
}
|
|
return "", domain.ErrInternal
|
|
}
|
|
|
|
err = utils.ComparePassword(password, user.Password)
|
|
if err != nil {
|
|
return "", domain.ErrInvalidUsernameCredentials
|
|
}
|
|
|
|
accessToken, err := authService.tokenService.CreateToken(user)
|
|
if err != nil {
|
|
return "", domain.ErrTokenCreation
|
|
}
|
|
|
|
return accessToken, nil
|
|
}
|