changed arhitecture
This commit is contained in:
1 parent
7e3a5cebcc
commit
585ba63bc2
95 files changed
+4985
-1360
No files matched your search
@@ -0,0 +1,55 @@
|
||||
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)
|
||||
}
|
||||
Reference in new issue
Block a user