56 lines
1.3 KiB
Go
56 lines
1.3 KiB
Go
package auth
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
|
|
"online-back/pkg/utils"
|
|
|
|
"golang.org/x/crypto/bcrypt"
|
|
)
|
|
|
|
// ErrInvalidCredentials covers both "no such user" and "wrong password" for
|
|
// login, and any refresh-token validation failure — callers map it to 401.
|
|
// Any other error from these methods (token generation failure) maps to 400.
|
|
var ErrInvalidCredentials = errors.New("invalid credentials")
|
|
|
|
type Service struct {
|
|
repository Repository
|
|
}
|
|
|
|
func NewService(repository Repository) *Service {
|
|
return &Service{repository: repository}
|
|
}
|
|
|
|
func (s *Service) Login(ctx context.Context, dto LoginDTO) (map[string]string, error) {
|
|
user, err := s.repository.Login(ctx, dto)
|
|
if err != nil {
|
|
return nil, ErrInvalidCredentials
|
|
}
|
|
|
|
if err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(dto.Password)); err != nil {
|
|
return nil, ErrInvalidCredentials
|
|
}
|
|
|
|
return utils.GenerateTokenPair(user.Id)
|
|
}
|
|
|
|
func (s *Service) RefreshToken(ctx context.Context, refreshToken string) (map[string]string, error) {
|
|
claims, err := utils.ParseRefreshToken(refreshToken)
|
|
if err != nil {
|
|
return nil, ErrInvalidCredentials
|
|
}
|
|
|
|
id, ok := utils.ClaimID(claims)
|
|
if !ok {
|
|
return nil, ErrInvalidCredentials
|
|
}
|
|
|
|
user, err := s.repository.GetUserByID(ctx, id)
|
|
if err != nil || user.Id != id {
|
|
return nil, ErrInvalidCredentials
|
|
}
|
|
|
|
return utils.GenerateTokenPair(id)
|
|
}
|