Files
mtusi2026lab3/internal/service/authentication/service.go
T

124 lines
4.0 KiB
Go

// Package authentication validates credentials and owns the session lifecycle.
package authentication
import (
"context"
"crypto/rand"
"crypto/sha256"
"encoding/base64"
"encoding/hex"
"errors"
"fmt"
"time"
"unicode/utf8"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/model/dto"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/service"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/service/production"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/store"
)
const (
minimumPasswordRunes = 12
maximumPasswordRunes = 128
tokenBytes = 32
)
// Service performs password and session operations through explicit boundaries.
type Service struct {
accounts service.Accounts
passwords service.Passwords
ttl time.Duration
dummyHash string
}
// New validates dependencies and prepares the unknown-account verification hash.
func New(accounts service.Accounts, passwords service.Passwords, ttl time.Duration) (*Service, error) {
if accounts == nil || passwords == nil || ttl <= 0 {
return nil, fmt.Errorf("accounts, passwords and positive session TTL are required")
}
dummyHash, err := passwords.Hash("unknown-account-dummy-password")
if err != nil {
return nil, err
}
return &Service{accounts: accounts, passwords: passwords, ttl: ttl, dummyHash: dummyHash}, nil
}
// Register checks profile and Unicode password bounds before hashing and persistence.
func (s *Service) Register(ctx context.Context, request dto.UsersCreateRequestDTO, password string) (dto.UserDTO, error) {
user, err := production.PrepareUser(request)
if err != nil || !validPassword(password) {
return dto.UserDTO{}, service.ErrInvalid
}
hash, err := s.passwords.Hash(password)
if err != nil {
return dto.UserDTO{}, err
}
user, err = s.accounts.Register(ctx, user, hash)
if errors.Is(err, store.ErrConflict) {
return dto.UserDTO{}, service.ErrConflict
}
return user, err
}
// Login verifies credentials uniformly and persists a new session before returning its token.
func (s *Service) Login(ctx context.Context, username, password string) (dto.SessionDTO, error) {
if !validPassword(password) {
return dto.SessionDTO{}, service.ErrUnauthorized
}
user, hash, err := s.accounts.Credentials(ctx, username)
if err != nil && !errors.Is(err, store.ErrNotFound) {
return dto.SessionDTO{}, err
}
missing := errors.Is(err, store.ErrNotFound)
if missing {
hash = s.dummyHash
}
if !s.passwords.Verify(hash, password) || missing {
return dto.SessionDTO{}, service.ErrUnauthorized
}
random := make([]byte, tokenBytes)
if _, err := rand.Read(random); err != nil {
return dto.SessionDTO{}, err
}
token := base64.RawURLEncoding.EncodeToString(random)
expiry := time.Now().UTC().Add(s.ttl)
if err := s.accounts.SaveSession(ctx, digest(token), user.ID, expiry); err != nil {
return dto.SessionDTO{}, err
}
return dto.SessionDTO{Token: token, ExpiresAt: expiry, User: user}, nil
}
// Authenticate checks absolute expiry in the source of truth on every request.
func (s *Service) Authenticate(ctx context.Context, token string) (string, error) {
decoded, err := base64.RawURLEncoding.DecodeString(token)
if err != nil || len(decoded) != tokenBytes {
return "", service.ErrUnauthorized
}
id, err := s.accounts.SessionUser(ctx, digest(token))
if errors.Is(err, store.ErrNotFound) {
return "", service.ErrUnauthorized
}
if err != nil {
return "", err
}
return id.String(), nil
}
// Logout removes the current session from the authoritative store.
func (s *Service) Logout(ctx context.Context, token string) error {
return s.accounts.RevokeSession(ctx, digest(token))
}
// digest produces the storage key without persisting the bearer secret.
func digest(token string) string {
hash := sha256.Sum256([]byte(token))
return hex.EncodeToString(hash[:])
}
// validPassword enforces the contract in Unicode code points without truncation.
func validPassword(password string) bool {
count := utf8.RuneCountInString(password)
return utf8.ValidString(password) && count >= minimumPasswordRunes && count <= maximumPasswordRunes
}