"""Authentication / authorisation dependencies (RBAC enforcement).""" from __future__ import annotations from dataclasses import dataclass, field from typing import Annotated import jwt from fastapi import Depends, Request, status from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer from sqlalchemy import select from sqlalchemy.ext.asyncio import AsyncSession from ..db.session import get_session from ..models.org import Department from ..models.rbac import Permission, Role, User, RolePermission, UserRole from .errors import AppError from .security import decode_token bearer = HTTPBearer(auto_error=False) Session = Annotated[AsyncSession, Depends(get_session)] SCOPE_RANK = {"self": 0, "dept": 1, "dept_tree": 2, "all": 3} @dataclass class AuthContext: user: User permissions: set[str] = field(default_factory=set) role_codes: list[str] = field(default_factory=list) data_scope: str = "self" employee_id: int | None = None department_id: int | None = None # ---- permission checks ------------------------------------------------ def can(self, code: str) -> bool: if self.user.is_superuser or "*:*:*" in self.permissions: return True if code in self.permissions: return True module, resource, action = code.split(":") wildcards = {f"{module}:{resource}:*", f"{module}:*:{action}", f"{module}:*:*", "*:*:*"} return bool(wildcards & self.permissions) def can_any(self, codes: list[str]) -> bool: return any(self.can(c) for c in codes) @property def is_staff(self) -> bool: return self.data_scope != "self" or self.user.is_superuser async def load_user_context(session: AsyncSession, user: User) -> AuthContext: rows = ( await session.execute( select(Role, Permission.code) .join(UserRole, UserRole.role_id == Role.id) .join(RolePermission, RolePermission.role_id == Role.id) .join(Permission, Permission.id == RolePermission.permission_id) .where(UserRole.user_id == user.id, Role.is_active.is_(True)) ) ).all() ctx = AuthContext( user=user, permissions={code for _role, code in rows}, role_codes=sorted({role.code for role, _ in rows}), ) ctx.data_scope = max((role.data_scope for role, _ in rows), key=lambda s: SCOPE_RANK.get(s, 0), default="self") if user.is_superuser: ctx.data_scope = "all" ctx.permissions.add("*:*:*") ctx.employee_id = user.employee_id if user.employee_id: from ..models.employee import Employee emp = await session.get(Employee, user.employee_id) if emp: ctx.department_id = emp.department_id return ctx async def get_auth_context( request: Request, session: Session, creds: Annotated[HTTPAuthorizationCredentials | None, Depends(bearer)] = None, ) -> AuthContext: token = creds.credentials if creds else request.headers.get("x-hrms-token") if not token: raise AppError("请先登录", "unauthorized", status.HTTP_401_UNAUTHORIZED) try: payload = decode_token(token, "access") except jwt.ExpiredSignatureError: raise AppError("登录已过期,请重新登录", "token_expired", status.HTTP_401_UNAUTHORIZED) except jwt.InvalidTokenError: raise AppError("登录凭证无效", "token_invalid", status.HTTP_401_UNAUTHORIZED) user = await session.get(User, int(payload["sub"])) if not user or not user.is_active: raise AppError("账号已被停用", "user_inactive", status.HTTP_401_UNAUTHORIZED) request.state.auth_context = getattr(request.state, "auth_context", None) or user ctx = await load_user_context(session, user) request.state.auth_context = ctx return ctx AuthCtx = Annotated[AuthContext, Depends(get_auth_context)] def require_perm(*codes: str): """Dependency factory: the caller needs *any* of the given permission codes.""" async def _dep(auth: AuthCtx) -> AuthContext: if not auth.can_any(list(codes)): raise AppError( f"没有权限执行该操作(需要 {', '.join(codes)})", "forbidden", status.HTTP_403_FORBIDDEN, ) return auth return _dep RequirePerm = require_perm async def department_subtree(session: AsyncSession, department_id: int | None) -> list[int]: """All department ids inside the given node (self included).""" if not department_id: return [] # 必须按 parent_id 逐层展开,**不能**拿 dep_path 做前缀匹配: # 这张表的 dep_path 历史上有两套写法(播种写 /UNIS/RD,页面新增与导入写 # .0 / .0.3),顶层部门一律是 .0,`LIKE '.0%'` 会把全公司部门都命中, # 于是「只选一个部门」实际捞出全部员工,看起来就像筛选完全没生效。 rows = (await session.execute(select(Department.id, Department.parent_id))).all() known = {row[0] for row in rows} if department_id not in known: return [department_id] children: dict[int, list[int]] = {} for dept_id, parent_id in rows: children.setdefault(parent_id or 0, []).append(dept_id) out: list[int] = [department_id] seen = {department_id} stack = [department_id] while stack: for child in children.get(stack.pop(), []): if child in seen: # 脏数据里的循环引用不能把这里绕成死循环 continue seen.add(child) out.append(child) stack.append(child) return out async def scope_employee_ids(session: AsyncSession, auth: AuthContext) -> list[int] | None: """Employee ids visible for the current user; ``None`` means unrestricted.""" from ..models.employee import Employee if auth.data_scope == "all": return None if auth.data_scope == "dept_tree" and auth.department_id: dept_ids = await department_subtree(session, auth.department_id) rows = ( await session.execute(select(Employee.id).where(Employee.department_id.in_(dept_ids))) ).all() ids = [r[0] for r in rows] if auth.employee_id: ids.append(auth.employee_id) return ids if auth.data_scope == "dept" and auth.department_id: rows = ( await session.execute( select(Employee.id).where(Employee.department_id == auth.department_id) ) ).all() return [r[0] for r in rows] return [auth.employee_id] if auth.employee_id else [] async def apply_employee_scope(session: AsyncSession, stmt, auth: AuthContext, column): ids = await scope_employee_ids(session, auth) if ids is None: return stmt if not ids: return stmt.where(column == -1) return stmt.where(column.in_(ids)) async def scope_department_ids(session: AsyncSession, auth: AuthContext) -> list[int] | None: """Department ids visible for the current user; ``None`` means unrestricted. Used by records that exist before an employee is attached to them (recruitment offers, job postings), where there is no ``employee_id`` to scope by. """ if auth.data_scope == "all": return None if auth.data_scope == "dept_tree" and auth.department_id: return await department_subtree(session, auth.department_id) if auth.data_scope == "dept" and auth.department_id: return [auth.department_id] return [] async def can_see_employee(session: AsyncSession, auth: AuthContext, employee_id: int | None) -> bool: """``True`` when ``employee_id`` sits inside the caller's data scope.""" ids = await scope_employee_ids(session, auth) return ids is None or (employee_id is not None and employee_id in ids) async def ensure_employee_scope(session: AsyncSession, auth: AuthContext, employee_id: int | None, action: str = "查看") -> None: """403 unless the caller may ``action`` the dossier of ``employee_id``. 列表接口由 ``apply_employee_scope`` 过滤,单条读取 / 写操作必须显式调用本函数, 否则「有模块读权限但数据范围有限」的角色(部门经理、招聘经理、人事专员) 可以凭 id 直接拿到范围外的员工全量档案。 """ if not await can_see_employee(session, auth, employee_id): raise AppError(f"没有权限{action}该员工", "forbidden", 403) def ensure(cond: bool, message: str, code: str = "business_error", status_code: int = 400) -> None: """Guard a business rule; ``status_code`` picks the HTTP status (403/404/409...).""" if not cond: raise AppError(message, code, status_code)