from datetime import datetime from uuid import UUID from sqlalchemy import ( CheckConstraint, DateTime, ForeignKey, LargeBinary, UniqueConstraint, ) from sqlalchemy.orm import Mapped, mapped_column from src.infra.db.models.base import Base from src.utils.constants import TOKEN_HASH_BYTES class Session(Base): """Сессия входа. Хранится SHA-256 токена, а не токен: по таблице действующий токен не восстановить. `expires_at` фиксируется при входе. Отзыв — удаление строки. """ __tablename__ = "sessions" __table_args__ = ( UniqueConstraint("token_hash"), CheckConstraint( f"octet_length(token_hash) = {TOKEN_HASH_BYTES}", name="token_hash_length", ), CheckConstraint( "expires_at > created_at", name="expires_after_created", ), ) id: Mapped[UUID] = mapped_column(primary_key=True) user_id: Mapped[UUID] = mapped_column(ForeignKey("users.id")) token_hash: Mapped[bytes] = mapped_column(LargeBinary) expires_at: Mapped[datetime] = mapped_column(DateTime(timezone=True))