Files
mtusi2026lab3/internal/application/sessions.go
T

58 lines
1.7 KiB
Go

package application
import (
"context"
"errors"
"fmt"
"mtusi2026lab3/internal/domain"
"mtusi2026lab3/internal/security"
)
const dummyPasswordHash = "$argon2id$v=19$m=19456,t=2,p=1$" +
"AAAAAAAAAAAAAAAAAAAAAA$" +
"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
func (s *Service) CreateSession(ctx context.Context, command CreateSessionCommand) (domain.Session, error) {
user, passwordHash, err := s.repository.GetUserByUsername(ctx, command.Username)
userNotFound := errors.Is(err, domain.ErrNotFound)
if userNotFound {
passwordHash = dummyPasswordHash
} else if err != nil {
return domain.Session{}, err
}
passwordMatches, verifyErr := security.VerifyPassword(command.Password, passwordHash)
if verifyErr != nil {
return domain.Session{}, fmt.Errorf("%w: %v", ErrCredentialState, verifyErr)
}
if userNotFound || !passwordMatches {
return domain.Session{}, ErrInvalidCredentials
}
token, tokenHash, err := security.GenerateSessionToken()
if err != nil {
return domain.Session{}, fmt.Errorf("generate session token: %w", err)
}
expiresAt := s.now().Add(s.sessionTTL)
if err = s.repository.CreateSession(ctx, tokenHash, user.ID, expiresAt); err != nil {
return domain.Session{}, err
}
return domain.Session{
Token: token, TokenType: "Bearer", ExpiresAt: expiresAt, User: user,
}, nil
}
func (s *Service) Authenticate(ctx context.Context, token string) (domain.User, []byte, error) {
tokenHash := security.HashSessionToken(token)
user, err := s.repository.GetUserBySession(ctx, tokenHash)
if err != nil {
return domain.User{}, nil, err
}
return user, tokenHash, nil
}
func (s *Service) DeleteSession(ctx context.Context, tokenHash []byte) error {
return s.repository.DeleteSession(ctx, tokenHash)
}