Files
mtusi2026lab2/internal/service/auth.go
OlegRood 834876c938 ЛР 2: закрыть уровень 4
Завершить PostgreSQL, Redis-сессии, миграции, таймауты и диагностику. Зафиксировать собственные тесты и доказательства финального прогона: 43 PASS, 0 FAIL, 0 SKIP; 768 HTTP-запросов без ошибок. Добавить официальный отчёт с запуском, архитектурой, SQL-планами и ограничениями. PR отложен до завершения уровня 5.
2026-10-28 13:30:26 +03:00

143 lines
2.9 KiB
Go

package service
import (
"context"
"crypto/rand"
"crypto/sha256"
"encoding/base64"
"errors"
"highload/internal/model"
"highload/internal/repository"
"highload/internal/security"
"time"
)
const tokenType = "Bearer"
type AuthService struct {
userRepo repository.UserRepository
sessionRepo repository.SessionRepository
sessionTTL time.Duration
}
func NewAuthService(userRepo repository.UserRepository, sessionRepo repository.SessionRepository, sessionTTL time.Duration) *AuthService {
return &AuthService{
userRepo: userRepo,
sessionRepo: sessionRepo,
sessionTTL: sessionTTL,
}
}
func (s *AuthService) Authenticate(ctx context.Context, username, password string) (*model.User, error) {
userOK := checkUsername(username)
passwordOK := checkPassword(password)
if !userOK || !passwordOK {
return nil, ErrUnauthorized
}
user, err := s.userRepo.GetUserByUsername(ctx, username)
if err != nil {
if errors.Is(err, repository.ErrNotFound) {
return nil, ErrUnauthorized
}
return nil, convertRepoError(err)
}
isVerify, err := security.VerifyPassword(password, user.PasswordHash)
if err != nil {
return nil, ErrServerError
}
if !isVerify {
return nil, ErrUnauthorized
}
return user, nil
}
type CreatedSession struct {
Token string
TokenType string
ExpiresAt time.Time
User *model.User
}
func (s *AuthService) CreateSession(ctx context.Context, username, password string) (*CreatedSession, error) {
user, err := s.Authenticate(ctx, username, password)
if err != nil {
return nil, err
}
if s.sessionTTL <= 0 {
return nil, ErrServerError
}
tokenBytes := make([]byte, 32)
_, err = rand.Read(tokenBytes)
if err != nil {
return nil, ErrServerError
}
token := base64.RawURLEncoding.EncodeToString(tokenBytes)
tokenHash := sha256.Sum256([]byte(token))
session, err := s.sessionRepo.Create(ctx, tokenHash[:], user.ID, s.sessionTTL)
if err != nil {
return nil, convertRepoError(err)
}
createdSession := &CreatedSession{
Token: token,
TokenType: tokenType,
ExpiresAt: session.ExpiresAt,
User: user,
}
return createdSession, nil
}
func (s *AuthService) ValidateSession(ctx context.Context, token string) (string, error) {
if token == "" {
return "", ErrUnauthorized
}
tokenHash := sha256.Sum256([]byte(token))
session, err := s.sessionRepo.GetSessionByTokenHash(ctx, tokenHash[:])
if err != nil {
if errors.Is(err, repository.ErrNotFound) {
return "", ErrUnauthorized
}
return "", convertRepoError(err)
}
if session.RevokedAt != nil {
return "", ErrUnauthorized
}
if !time.Now().Before(session.ExpiresAt) {
return "", ErrUnauthorized
}
return session.UserID, nil
}
func (s *AuthService) RevokeSession(ctx context.Context, token string) error {
tokenHash := sha256.Sum256([]byte(token))
_, err := s.sessionRepo.RevokeSession(ctx, tokenHash[:])
if err != nil {
return convertRepoError(err)
}
return nil
}