import uuid from datetime import datetime from sqlalchemy import CheckConstraint, DateTime, ForeignKey, String, Text, UniqueConstraint from sqlalchemy.dialects.postgresql import UUID from sqlalchemy.orm import Mapped, mapped_column from app.common.base_model import Base, CreatedAtMixin, IdMixin def _account_id() -> Mapped[uuid.UUID]: return mapped_column(UUID(as_uuid=True), ForeignKey("accounts.id", ondelete="CASCADE"), index=True) class RefreshToken(IdMixin, CreatedAtMixin, Base): """Rotated on every use. Reusing a revoked token revokes its whole family (theft detection).""" __tablename__ = "refresh_tokens" account_id: Mapped[uuid.UUID] = _account_id() token_hash: Mapped[str] = mapped_column(String(64), unique=True) family_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), index=True) expires_at: Mapped[datetime] = mapped_column(DateTime(timezone=True)) revoked_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True)) class PasswordReset(IdMixin, CreatedAtMixin, Base): __tablename__ = "password_resets" account_id: Mapped[uuid.UUID] = _account_id() token_hash: Mapped[str] = mapped_column(String(64), unique=True) expires_at: Mapped[datetime] = mapped_column(DateTime(timezone=True)) used_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True)) class AuthIdentity(IdMixin, CreatedAtMixin, Base): """A linked Apple or Google sign-in.""" __tablename__ = "auth_identities" __table_args__ = ( UniqueConstraint("provider", "subject"), CheckConstraint("provider IN ('apple', 'google')", name="provider"), ) account_id: Mapped[uuid.UUID] = _account_id() provider: Mapped[str] = mapped_column(String(8)) subject: Mapped[str] = mapped_column(Text)