Files
mtusi2026lab4/src/infrastructure/services/auth_service/auth_service.py
T

93 lines
3.8 KiB
Python

from datetime import UTC, datetime
from config import LOGGER
from domain import BasicCredentialsSchema, SessionSchema, UserSchema
from domain.errors import InvalidCredentialsError, UnauthorizedError
from infrastructure.security import PasswordHasher, generate_token, hash_token
from interfaces import SessionCache, SessionRepository, UserRepository
TOKEN_MAX_LENGTH = 256
class AuthService:
"""
Basic → opaque Bearer-сессия.
Источник истины — SessionRepository (PostgreSQL), SessionCache (Valkey) —
read-through кэш: при промахе или недоступности кэша сессия читается из БД.
"""
def __init__(
self,
user_repository: UserRepository,
session_repository: SessionRepository,
session_cache: SessionCache,
hasher: PasswordHasher,
session_ttl_seconds: int,
) -> None:
self._users = user_repository
self._sessions = session_repository
self._cache = session_cache
self._hasher = hasher
self._session_ttl = session_ttl_seconds
async def login(self, credentials: BasicCredentialsSchema) -> SessionSchema:
"""
Создание сессии по username и паролю.
Raises:
InvalidCredentialsError: неизвестный username или неверный пароль —
одинаковый ответ и сопоставимое время
"""
found = await self._users.get_credentials(credentials.username)
if found is None:
await self._hasher.verify_dummy(credentials.password)
raise InvalidCredentialsError()
if not await self._hasher.verify(found.password_hash, credentials.password):
raise InvalidCredentialsError()
token = generate_token()
expires_at = await self._sessions.create(
hash_token(token), found.user.id, self._session_ttl
)
LOGGER.info(f"Создана сессия пользователя {found.user.id}")
return SessionSchema(token=token, expires_at=expires_at, user=found.user)
async def authenticate(self, token: str | None) -> UserSchema:
"""
Владелец действующей сессии.
Raises:
UnauthorizedError: токена нет, он неизвестен, истёк или отозван
UnavailableError: кэш промахнулся, а PostgreSQL недоступен
"""
if not token or len(token) > TOKEN_MAX_LENGTH:
raise UnauthorizedError()
token_hash = hash_token(token)
session = await self._cache.get(token_hash)
if session is not None and session.expires_at > datetime.now(UTC):
return session.user
session = await self._sessions.get_active(token_hash)
if session is None:
raise UnauthorizedError()
await self._cache.set(token_hash, session)
return session.user
async def logout(self, token: str | None) -> None:
"""
Отзыв в источнике истины, затем инвалидация кэша.
Raises:
UnauthorizedError: действующей сессии с таким токеном нет
"""
if not token or len(token) > TOKEN_MAX_LENGTH:
raise UnauthorizedError()
token_hash = hash_token(token)
if not await self._sessions.revoke(token_hash):
raise UnauthorizedError()
if not await self._cache.delete(token_hash):
LOGGER.warning(
"Сессия отозвана в PostgreSQL, но запись кэша не удалена: "
"она истечёт по TTL кэша"
)
LOGGER.info("Сессия отозвана")