Source code for app.db.models._user

from __future__ import annotations

from datetime import UTC, date, datetime
from pathlib import PurePosixPath
from typing import TYPE_CHECKING

from advanced_alchemy.base import UUIDv7AuditBase
from advanced_alchemy.types import Bool, DateTimeUTC
from advanced_alchemy.types.file_object import FileObject, StoredObject
from sqlalchemy import Integer, String, inspect
from sqlalchemy.orm import Mapped, column_property, mapped_column, relationship

from app.lib.storage import STORAGE_BACKEND_KEY

if TYPE_CHECKING:
    from app.db.models._oauth_account import UserOAuthAccount
    from app.db.models._security import APIKey, UserMFAFactor, UserPasskey, UserSession
    from app.db.models._team_member import TeamMember
    from app.db.models._user_role import UserRole

_OWNED_CASCADE = "all, delete-orphan"


class User(UUIDv7AuditBase):
    """Application user account model."""

    __tablename__ = "user_account"
    __table_args__ = {"comment": "User accounts for application access"}
    __pii_columns__ = {"name", "email", "username", "phone", "avatar"}

    email: Mapped[str] = mapped_column(unique=True, index=True, nullable=False)
    name: Mapped[str | None] = mapped_column(nullable=True, default=None)
    username: Mapped[str | None] = mapped_column(
        String(length=30), unique=True, index=True, nullable=True, default=None
    )
    phone: Mapped[str | None] = mapped_column(String(length=20), nullable=True, default=None)
    hashed_password: Mapped[str | None] = mapped_column(
        String(length=255),
        nullable=True,
        default=None,
        deferred=True,
        deferred_group="security_sensitive",
    )
    has_password: Mapped[bool] = column_property(hashed_password.is_not(None))
    """Whether the account has a password, computed by the database every time the user is loaded.

    The hash itself stays deferred, so this is the way to ask without loading it.
    """
    avatar: Mapped[FileObject | None] = mapped_column(
        StoredObject(backend=STORAGE_BACKEND_KEY), nullable=True, default=None
    )
    """Uploaded profile picture; the metadata lives in this column and the bytes in object storage."""
    is_active: Mapped[bool] = mapped_column(Bool, default=True, nullable=False)
    is_superuser: Mapped[bool] = mapped_column(Bool, default=False, nullable=False)
    is_verified: Mapped[bool] = mapped_column(Bool, default=False, nullable=False)
    security_epoch: Mapped[int] = mapped_column(Integer, default=1, nullable=False)
    verified_at: Mapped[date | None] = mapped_column(nullable=True, default=None)
    joined_at: Mapped[date] = mapped_column(default=lambda: datetime.now(UTC).date())
    login_count: Mapped[int] = mapped_column(default=0)
    password_reset_at: Mapped[datetime | None] = mapped_column(DateTimeUTC(timezone=True), nullable=True, default=None)
    failed_reset_attempts: Mapped[int] = mapped_column(default=0, nullable=False)
    reset_locked_until: Mapped[datetime | None] = mapped_column(DateTimeUTC(timezone=True), nullable=True, default=None)

    roles: Mapped[list[UserRole]] = relationship(
        back_populates="user",
        lazy="selectin",
        uselist=True,
        cascade="all, delete",
    )
    teams: Mapped[list[TeamMember]] = relationship(
        back_populates="user",
        lazy="selectin",
        uselist=True,
        cascade="all, delete",
        viewonly=True,
    )
    oauth_accounts: Mapped[list[UserOAuthAccount]] = relationship(
        back_populates="user",
        lazy="noload",
        cascade=_OWNED_CASCADE,
        uselist=True,
    )
    sessions: Mapped[list[UserSession]] = relationship(
        back_populates="user",
        lazy="noload",
        cascade=_OWNED_CASCADE,
        uselist=True,
    )
    mfa_factors: Mapped[list[UserMFAFactor]] = relationship(
        back_populates="user",
        lazy="noload",
        cascade=_OWNED_CASCADE,
        uselist=True,
    )
    passkeys: Mapped[list[UserPasskey]] = relationship(
        back_populates="user",
        lazy="noload",
        cascade=_OWNED_CASCADE,
        uselist=True,
    )
    api_keys: Mapped[list[APIKey]] = relationship(
        back_populates="user",
        lazy="noload",
        cascade=_OWNED_CASCADE,
        uselist=True,
    )

    @property
    def avatar_url(self) -> str | None:
        """Path the user fetches their own avatar from, versioned by upload so a replacement is never cached."""
        if self.avatar is None:
            return None
        return f"/api/me/avatar?v={PurePosixPath(self.avatar.path).stem}"

    @property
    def has_mfa(self) -> bool:
        """Whether an eager-loaded confirmed MFA factor exists without triggering lazy I/O."""
        if "mfa_factors" in inspect(self).unloaded:
            return False
        return any(factor.is_confirmed for factor in self.mfa_factors)

    @property
    def is_two_factor_enabled(self) -> bool:
        """Compatibility alias indicating whether the user has confirmed MFA enabled."""
        return self.has_mfa

    @property
    def totp_method_id(self) -> str | None:
        """Active confirmed TOTP factor identifier when MFA factors are loaded."""
        if "mfa_factors" in inspect(self).unloaded:
            return None
        for factor in self.mfa_factors:
            if factor.is_confirmed and factor.kind == "totp":
                return factor.method_id
        return None

    def __eq__(self, other: object) -> bool:
        """Compare persisted user records by primary key and core account state.

        Returns:
            ``True`` if both instances represent the same persisted user state.
        """
        if isinstance(other, User):
            self_id = inspect(self).identity
            other_id = inspect(other).identity
            if self_id is not None and other_id is not None:
                return (
                    self_id == other_id
                    and self.email == other.email
                    and self.name == other.name
                    and self.is_active == other.is_active
                    and self.is_verified == other.is_verified
                    and self.security_epoch == other.security_epoch
                )
        return super().__eq__(other)

    def __hash__(self) -> int:
        """Hash persisted users stably by SQLAlchemy identity key.

        Returns:
            Hash of the SQLAlchemy identity key, or the base object hash if transient.
        """
        identity = inspect(self).identity
        return hash(identity) if identity is not None else super().__hash__()