Files
mtusi2026lab7-safronov/src/core/services/session.py
T
ricoromaandClaude Opus 5.5 089d78609d chore: port lab 6 solution into the lab 7 skeleton
Source: mtusi2026lab6-safronov, solution/bvt2301-safronov, 6c6a065.
Files follow AGENTS.md, "Переход в следующую лабу". Contracts, public
tests, README, REPORT and evidence of lab 6 are not carried over; infra
and scripts of the lab 7 skeleton stay as they are.
Makefile is the lab 6 one with the lab 7 skeleton part restored
(HTTPS BASE_URL on 8443, test-security); .gitignore and .dockerignore
are taken from lab 6 because both skeletons have the same files;
.env.example is the lab 6 one without changes.
The compose project, image and CI prefix are renamed to lab7, and
references to the previous lab now name lab6.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 03:59:04 +03:00

116 lines
4.5 KiB
Python

import hashlib
import secrets
from datetime import timedelta
from uuid import UUID, uuid4
from src.config import settings
from src.core import exceptions
from src.core.ports.uow import AbstractUnitOfWork
from src.infra.logger import AbstractLogger, get_logger
from src.infra.password import verify_password
from src.schemas import dataclasses
from src.utils.constants import SESSION_TOKEN_BYTES
from src.utils.utc import utcnow
logger: AbstractLogger = get_logger().bind(module="session_service")
def hash_token(token: str) -> bytes:
"""SHA-256 токена: в БД хранится он, а не токен.
Быстрого хэша хватает: у токена 256 бит случайности, перебирать
нечего. Медленный KDF нужен паролю, который выбирает человек.
"""
return hashlib.sha256(token.encode()).digest()
class SessionService:
def __init__(self, uow: AbstractUnitOfWork) -> None:
self.uow = uow
async def login(
self,
*,
username: str,
password: str,
) -> dataclasses.SessionTokenDTO:
"""Вход: проверка пароля и новая сессия.
Два блока: чтение хэша заканчивается до KDF, чтобы соединение пула
не ждало хэш и очередь лимита (design change `session-auth`,
решение 3). Пароли и пользователи не меняются, поэтому между
блоками проверять нечего.
"""
log = logger.bind(method="login")
async with self.uow:
credentials = await self.uow.users.get_user_credentials(
username=username,
)
# неизвестный username проверяется против фиктивного хэша: время
# ответа то же, что у неверного пароля
valid = await verify_password(
password=password,
password_hash=credentials.password_hash if credentials else None,
)
if credentials is None or not valid:
# без username и пароля: по журналу не перебрать имена
log.warning("Login failed")
raise exceptions.InvalidCredentials
token = secrets.token_urlsafe(SESSION_TOKEN_BYTES)
now = utcnow()
async with self.uow:
session = await self.uow.sessions.insert_session(
session=dataclasses.SessionFullDTO(
id=uuid4(),
user_id=credentials.user.id,
token_hash=hash_token(token),
expires_at=now
+ timedelta(seconds=settings.auth.session_ttl_seconds),
created_at=now,
),
)
await self.uow.commit()
log.info(
"Created session",
user_id=session.user_id,
session_id=session.id,
ttl_seconds=settings.auth.session_ttl_seconds,
)
return dataclasses.SessionTokenDTO(
token=token,
expires_at=session.expires_at,
user=credentials.user,
)
async def authenticate(
self,
*,
token: str | None,
) -> dataclasses.CurrentSessionDTO:
"""Действующая сессия по Bearer-токену; иначе `Unauthenticated`.
Ошибка БД сюда не превращается: её переводит в 503 единица работы,
недоступность хранилища не делает токен недействительным.
"""
if not token:
raise exceptions.Unauthenticated
async with self.uow:
current = await self.uow.sessions.get_current_session(
token_hash=hash_token(token),
now=utcnow(),
)
if current is None:
raise exceptions.Unauthenticated
return current
async def revoke(self, *, session_id: UUID) -> None:
log = logger.bind(method="revoke", session_id=session_id)
async with self.uow:
deleted = await self.uow.sessions.delete_session(
session_id=session_id,
)
await self.uow.commit()
# False — параллельный выход тем же токеном уже удалил сессию
log.info("Revoked session", already_revoked=not deleted)