Production
This commit is contained in:
@@ -0,0 +1,50 @@
|
||||
"""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
|
||||
@@ -0,0 +1,50 @@
|
||||
import uuid
|
||||
|
||||
from fastapi import APIRouter, Depends, Request, status
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.auth.dependencies import client_ip, get_current_user, require_role
|
||||
from app.common.enums import Role
|
||||
from app.database.session import get_db
|
||||
from app.users.models import User
|
||||
from app.users.schemas import MyProfile, UserCreate, UserRead, UserUpdate
|
||||
from app.users.service import UserService
|
||||
|
||||
router = APIRouter(prefix="/users", tags=["users"])
|
||||
|
||||
|
||||
@router.get("/me/profile", response_model=MyProfile)
|
||||
async def my_profile(
|
||||
current_user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db)
|
||||
) -> MyProfile:
|
||||
return await UserService(db).my_profile(current_user)
|
||||
|
||||
|
||||
@router.get("", response_model=list[UserRead])
|
||||
async def list_users(
|
||||
role: Role | None = None,
|
||||
current_user: User = Depends(require_role(Role.ADMIN, Role.GM)),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
) -> list[User]:
|
||||
return await UserService(db).list_users(current_user, role)
|
||||
|
||||
|
||||
@router.post("", response_model=UserRead, status_code=status.HTTP_201_CREATED)
|
||||
async def create_user(
|
||||
payload: UserCreate,
|
||||
request: Request,
|
||||
current_user: User = Depends(require_role(Role.ADMIN)),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
) -> User:
|
||||
return await UserService(db).create(payload, current_user, client_ip(request))
|
||||
|
||||
|
||||
@router.patch("/{user_id}", response_model=UserRead)
|
||||
async def update_user(
|
||||
user_id: uuid.UUID,
|
||||
payload: UserUpdate,
|
||||
request: Request,
|
||||
current_user: User = Depends(require_role(Role.ADMIN)),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
) -> User:
|
||||
return await UserService(db).update(user_id, payload, current_user, client_ip(request))
|
||||
@@ -0,0 +1,65 @@
|
||||
import uuid
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, EmailStr, Field, model_validator
|
||||
|
||||
from app.common.enums import Role
|
||||
|
||||
|
||||
class UserCreate(BaseModel):
|
||||
email: EmailStr
|
||||
password: str = Field(min_length=8, max_length=128)
|
||||
full_name: str = Field(min_length=2, max_length=200)
|
||||
employee_code: str = Field(min_length=1, max_length=50)
|
||||
role: Role
|
||||
phone: str | None = Field(default=None, max_length=20)
|
||||
#: Required for MR, forbidden for every other role (R4/R8).
|
||||
headquarters_id: uuid.UUID | None = None
|
||||
|
||||
@model_validator(mode="after")
|
||||
def check_hq_matches_role(self):
|
||||
if self.role == Role.MR and self.headquarters_id is None:
|
||||
raise ValueError("headquarters_id is required for an MR")
|
||||
if self.role != Role.MR and self.headquarters_id is not None:
|
||||
raise ValueError("headquarters_id may only be set for an MR")
|
||||
return self
|
||||
|
||||
|
||||
class UserUpdate(BaseModel):
|
||||
full_name: str | None = Field(default=None, min_length=2, max_length=200)
|
||||
#: Sign-in credentials. Admin-only (the whole endpoint is); changing them is audited.
|
||||
email: EmailStr | None = None
|
||||
employee_code: str | None = Field(default=None, min_length=1, max_length=50)
|
||||
#: A new password. Signs the user out everywhere and clears a lockout.
|
||||
password: str | None = Field(default=None, min_length=8, max_length=128)
|
||||
phone: str | None = Field(default=None, max_length=20)
|
||||
headquarters_id: uuid.UUID | None = None
|
||||
is_active: bool | None = None
|
||||
|
||||
|
||||
class UserRead(BaseModel):
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
|
||||
id: uuid.UUID
|
||||
email: str
|
||||
full_name: str
|
||||
employee_code: str
|
||||
role: Role
|
||||
phone: str | None
|
||||
headquarters_id: uuid.UUID | None
|
||||
is_active: bool
|
||||
|
||||
|
||||
class MyProfile(BaseModel):
|
||||
"""S4 — the MR profile screen. Includes the DERIVED reporting Area Manager."""
|
||||
|
||||
id: uuid.UUID
|
||||
full_name: str
|
||||
employee_code: str
|
||||
email: str
|
||||
role: Role
|
||||
phone: str | None
|
||||
headquarters_id: uuid.UUID | None
|
||||
headquarters_code: str | None
|
||||
headquarters_name: str | None
|
||||
reporting_manager_id: uuid.UUID | None
|
||||
reporting_manager_name: str | None
|
||||
@@ -0,0 +1,158 @@
|
||||
import uuid
|
||||
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.audit.service import AuditService
|
||||
from app.auth.security import hash_password
|
||||
from app.auth.service import AuthService
|
||||
from app.common.enums import AuditAction, EntityType, Role
|
||||
from app.common.exceptions import ConflictError, NotFoundError, ValidationError
|
||||
from app.common.utils import snapshot
|
||||
from app.organization.models import AMHeadquarters, Headquarters
|
||||
from app.users.models import User
|
||||
from app.users.schemas import MyProfile, UserCreate, UserUpdate
|
||||
|
||||
_AUDIT_FIELDS = ["email", "full_name", "employee_code", "role", "headquarters_id", "is_active"]
|
||||
|
||||
|
||||
class UserService:
|
||||
def __init__(self, db: AsyncSession) -> None:
|
||||
self.db = db
|
||||
self.audit = AuditService(db)
|
||||
|
||||
async def create(self, data: UserCreate, actor: User, ip: str | None = None) -> User:
|
||||
if data.headquarters_id is not None:
|
||||
hq = await self.db.get(Headquarters, data.headquarters_id)
|
||||
if hq is None:
|
||||
raise NotFoundError("Headquarters not found")
|
||||
if hq.company_id != actor.company_id:
|
||||
raise ValidationError("Headquarters belongs to another company")
|
||||
|
||||
user = User(
|
||||
company_id=actor.company_id,
|
||||
email=str(data.email).lower(),
|
||||
password_hash=hash_password(data.password),
|
||||
full_name=data.full_name,
|
||||
employee_code=data.employee_code,
|
||||
role=data.role,
|
||||
phone=data.phone,
|
||||
headquarters_id=data.headquarters_id,
|
||||
)
|
||||
self.db.add(user)
|
||||
try:
|
||||
await self.db.flush()
|
||||
except IntegrityError as exc:
|
||||
await self.db.rollback()
|
||||
raise ConflictError("A user with this email or employee code already exists") from exc
|
||||
|
||||
await self.audit.log(
|
||||
actor_user_id=actor.id,
|
||||
entity_type=EntityType.USER,
|
||||
entity_id=user.id,
|
||||
action=AuditAction.CREATE,
|
||||
after=snapshot(user, _AUDIT_FIELDS),
|
||||
ip_address=ip,
|
||||
)
|
||||
await self.db.commit()
|
||||
return user
|
||||
|
||||
async def update(
|
||||
self, user_id: uuid.UUID, data: UserUpdate, actor: User, ip: str | None = None
|
||||
) -> User:
|
||||
user = await self.db.get(User, user_id)
|
||||
if user is None:
|
||||
raise NotFoundError("User not found")
|
||||
|
||||
if user.company_id != actor.company_id:
|
||||
raise NotFoundError("User not found")
|
||||
|
||||
before = snapshot(user, _AUDIT_FIELDS)
|
||||
deactivating = data.is_active is False and user.is_active
|
||||
|
||||
changes = data.model_dump(exclude_unset=True)
|
||||
new_password = changes.pop("password", None)
|
||||
if "email" in changes:
|
||||
if changes["email"] is None:
|
||||
raise ValidationError("Email cannot be empty")
|
||||
changes["email"] = str(changes["email"]).lower()
|
||||
for field, value in changes.items():
|
||||
setattr(user, field, value)
|
||||
|
||||
password_reset = new_password is not None
|
||||
if password_reset:
|
||||
user.password_hash = hash_password(new_password)
|
||||
user.failed_login_attempts = 0 # a reset also unlocks the account
|
||||
|
||||
# An MR must keep a headquarters; nobody else may gain one (DB check mirrors this).
|
||||
if user.role == Role.MR and user.headquarters_id is None:
|
||||
raise ValidationError("An MR must have a headquarters")
|
||||
if user.role != Role.MR and user.headquarters_id is not None:
|
||||
raise ValidationError("Only an MR can have a headquarters")
|
||||
|
||||
after = snapshot(user, _AUDIT_FIELDS)
|
||||
if password_reset:
|
||||
after["password_reset"] = True # the fact is logged, never the password or its hash
|
||||
try:
|
||||
await self.audit.log(
|
||||
actor_user_id=actor.id,
|
||||
entity_type=EntityType.USER,
|
||||
entity_id=user.id,
|
||||
action=AuditAction.DEACTIVATE if deactivating else AuditAction.UPDATE,
|
||||
before=before,
|
||||
after=after,
|
||||
ip_address=ip,
|
||||
)
|
||||
await self.db.commit()
|
||||
except IntegrityError as exc:
|
||||
await self.db.rollback()
|
||||
raise ConflictError("A user with this email or employee code already exists") from exc
|
||||
|
||||
# SEC-5 — revoke refresh tokens the moment a user is deactivated, or their
|
||||
# credentials are changed, so an old session cannot outlive the old password/email.
|
||||
if deactivating or password_reset or "email" in changes:
|
||||
await AuthService(self.db).logout(user.id)
|
||||
return user
|
||||
|
||||
async def list_users(self, actor: User, role: Role | None = None) -> list[User]:
|
||||
stmt = select(User).where(User.company_id == actor.company_id)
|
||||
if role is not None:
|
||||
stmt = stmt.where(User.role == role)
|
||||
return list((await self.db.execute(stmt)).scalars().all())
|
||||
|
||||
async def my_profile(self, user: User) -> MyProfile:
|
||||
"""S4 — includes the reporting Area Manager DERIVED through the headquarters."""
|
||||
hq_code = hq_name = None
|
||||
manager_id = manager_name = None
|
||||
|
||||
if user.headquarters_id:
|
||||
hq = await self.db.get(Headquarters, user.headquarters_id)
|
||||
if hq:
|
||||
hq_code, hq_name = hq.code, hq.name
|
||||
|
||||
stmt = (
|
||||
select(User)
|
||||
.join(AMHeadquarters, AMHeadquarters.area_manager_user_id == User.id)
|
||||
.where(
|
||||
AMHeadquarters.headquarters_id == user.headquarters_id,
|
||||
AMHeadquarters.effective_to.is_(None),
|
||||
)
|
||||
)
|
||||
manager = (await self.db.execute(stmt)).scalars().first()
|
||||
if manager:
|
||||
manager_id, manager_name = manager.id, manager.full_name
|
||||
|
||||
return MyProfile(
|
||||
id=user.id,
|
||||
full_name=user.full_name,
|
||||
employee_code=user.employee_code,
|
||||
email=user.email,
|
||||
role=user.role,
|
||||
phone=user.phone,
|
||||
headquarters_id=user.headquarters_id,
|
||||
headquarters_code=hq_code,
|
||||
headquarters_name=hq_name,
|
||||
reporting_manager_id=manager_id,
|
||||
reporting_manager_name=manager_name,
|
||||
)
|
||||
Reference in New Issue
Block a user