51 lines
2.2 KiB
Python
51 lines
2.2 KiB
Python
"""The single `user` table for every role.
|
|
|
|
`mr_profile` and `area_manager_profile` were merged in (report §13.2): both would
|
|
have held the same columns as `user`, and the only MR-specific payload is
|
|
`headquarters_id`.
|
|
"""
|
|
|
|
import uuid
|
|
|
|
from sqlalchemy import Boolean, CheckConstraint, Enum, ForeignKey, String, UniqueConstraint
|
|
from sqlalchemy.dialects.postgresql import UUID as PGUUID
|
|
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
|
|
|
from app.common.enums import Role
|
|
from app.database.base import Base, TimestampMixin, UUIDMixin
|
|
|
|
|
|
class User(Base, UUIDMixin, TimestampMixin):
|
|
__tablename__ = "user"
|
|
__table_args__ = (
|
|
UniqueConstraint("company_id", "email", name="uq_user_company_email"),
|
|
UniqueConstraint("company_id", "employee_code", name="uq_user_company_empcode"),
|
|
# An MR must have a headquarters; nobody else may have one (R4, R8).
|
|
CheckConstraint(
|
|
"(role = 'MR' AND headquarters_id IS NOT NULL) "
|
|
"OR (role <> 'MR' AND headquarters_id IS NULL)",
|
|
name="ck_user_mr_requires_hq",
|
|
),
|
|
)
|
|
|
|
company_id: Mapped[uuid.UUID] = mapped_column(
|
|
PGUUID(as_uuid=True), ForeignKey("company.id", ondelete="RESTRICT"), nullable=False
|
|
)
|
|
email: Mapped[str] = mapped_column(String(255), nullable=False)
|
|
password_hash: Mapped[str] = mapped_column(String(255), nullable=False)
|
|
full_name: Mapped[str] = mapped_column(String(200), nullable=False)
|
|
employee_code: Mapped[str] = mapped_column(String(50), nullable=False)
|
|
phone: Mapped[str | None] = mapped_column(String(20))
|
|
role: Mapped[Role] = mapped_column(
|
|
Enum(Role, name="role_enum", native_enum=False, length=10), nullable=False
|
|
)
|
|
#: MR only — the one headquarters this MR belongs to (R4).
|
|
headquarters_id: Mapped[uuid.UUID | None] = mapped_column(
|
|
PGUUID(as_uuid=True), ForeignKey("headquarters.id", ondelete="RESTRICT")
|
|
)
|
|
#: Checked on EVERY request, not only at login (SEC-5).
|
|
is_active: Mapped[bool] = mapped_column(Boolean, default=True, nullable=False)
|
|
failed_login_attempts: Mapped[int] = mapped_column(default=0, nullable=False)
|
|
|
|
headquarters: Mapped["Headquarters | None"] = relationship() # noqa: F821
|