File size: 1,797 Bytes
2756f0f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
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)