from __future__ import annotations import uuid from datetime import datetime from sqlalchemy import Boolean, DateTime, ForeignKey, String, Table, Text, func from sqlalchemy.dialects.postgresql import UUID from sqlalchemy.orm import Mapped, mapped_column, relationship from app.core.database import Base from app.models.base import TimestampMixin, UUIDPrimaryKeyMixin user_roles_table = Table( "user_roles", Base.metadata, mapped_column("user_id", UUID(as_uuid=True), ForeignKey("users.id", ondelete="CASCADE"), primary_key=True), mapped_column("role_id", UUID(as_uuid=True), ForeignKey("roles.id", ondelete="CASCADE"), primary_key=True), ) class User(Base, UUIDPrimaryKeyMixin, TimestampMixin): """User account model.""" __tablename__ = "users" username: Mapped[str] = mapped_column(String(150), unique=True, nullable=False, index=True) email: Mapped[str] = mapped_column(String(255), unique=True, nullable=False, index=True) hashed_password: Mapped[str] = mapped_column(String(255), nullable=False) full_name: Mapped[str | None] = mapped_column(String(255), nullable=True) is_active: Mapped[bool] = mapped_column(Boolean, default=True, nullable=False) is_superuser: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False) last_login: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True) roles: Mapped[list[Role]] = relationship( "Role", secondary=user_roles_table, back_populates="users", lazy="joined", ) refresh_tokens: Mapped[list[RefreshToken]] = relationship( "RefreshToken", back_populates="user", cascade="all, delete-orphan", lazy="dynamic", ) audit_logs: Mapped[list[AuditLog]] = relationship( "AuditLog", back_populates="user", lazy="dynamic", ) def __repr__(self) -> str: return f"" class Role(Base, UUIDPrimaryKeyMixin): """User role model.""" __tablename__ = "roles" name: Mapped[str] = mapped_column(String(50), unique=True, nullable=False, index=True) description: Mapped[str | None] = mapped_column(Text, nullable=True) created_at: Mapped[datetime] = mapped_column( DateTime(timezone=True), default=func.now(), server_default=func.now(), nullable=False, ) users: Mapped[list[User]] = relationship( "User", secondary=user_roles_table, back_populates="roles", lazy="dynamic", ) def __repr__(self) -> str: return f"" class RefreshToken(Base, UUIDPrimaryKeyMixin): """JWT refresh token storage.""" __tablename__ = "refresh_tokens" user_id: Mapped[uuid.UUID] = mapped_column( UUID(as_uuid=True), ForeignKey("users.id", ondelete="CASCADE"), nullable=False, index=True, ) token: Mapped[str] = mapped_column(String(512), unique=True, nullable=False, index=True) expires_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False) revoked: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False) created_at: Mapped[datetime] = mapped_column( DateTime(timezone=True), default=func.now(), server_default=func.now(), nullable=False, ) user: Mapped[User] = relationship("User", back_populates="refresh_tokens") def __repr__(self) -> str: return f"" class AuditLog(Base, UUIDPrimaryKeyMixin): """Audit trail for user actions.""" __tablename__ = "audit_logs" user_id: Mapped[uuid.UUID | None] = mapped_column( UUID(as_uuid=True), ForeignKey("users.id", ondelete="SET NULL"), nullable=True, index=True, ) action: Mapped[str] = mapped_column(String(100), nullable=False, index=True) resource_type: Mapped[str] = mapped_column(String(100), nullable=False, index=True) resource_id: Mapped[str | None] = mapped_column(String(255), nullable=True) details: Mapped[dict | None] = mapped_column(type_=Text, nullable=True) ip_address: Mapped[str | None] = mapped_column(String(45), nullable=True) user_agent: Mapped[str | None] = mapped_column(String(512), nullable=True) created_at: Mapped[datetime] = mapped_column( DateTime(timezone=True), default=func.now(), server_default=func.now(), nullable=False, index=True, ) user: Mapped[User | None] = relationship("User", back_populates="audit_logs") def __repr__(self) -> str: return f""