159 lines
6.2 KiB
Python
159 lines
6.2 KiB
Python
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,
|
|
)
|