unis-oa/backend/app/deps.py

207 lines
8.9 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

"""FastAPI dependencies: authentication and the acting identity."""
from __future__ import annotations
from dataclasses import dataclass, field
from fastapi import Depends, Header, Request
from jose import ExpiredSignatureError, JWTError
from sqlalchemy.orm import Session, joinedload
from . import models
from . import permissions as perm
from .db import get_db
from .envelope import forbidden, unauthorized
from .security import decode_token
from .service import personref
@dataclass
class CurrentUser:
"""Acting identity, resolved on every request.
Permissions live in the database (not in the token) so that granting or
revoking a role takes effect immediately, without waiting for a re-login.
``ref`` is how this request addresses the person everywhere in storage: the
login account (see :mod:`app.service.personref`). It used to be an O2OA
identity DN, which drifted every time a unit was renamed or a person moved
units -- and drifted silently, because the runtime tables were never in the
sync side's reference-carrying list. 那套"一人多身份"的口径连同 ``oa_identity``
表一起在 2026-10 下线,这里只剩账号一条路。
"""
person: models.User
ref: str
is_admin: bool
permissions: tuple[str, ...] = ()
data_scope: str = perm.SCOPE_SELF
#: ``data_scope`` 的可执行版本(含自定义部门集合),过滤条件都从它算
data_grant: perm.DataGrant = field(default_factory=perm.DataGrant)
role_names: tuple[str, ...] = ()
#: 统一身份权限那一层的口径(没启用时是空字典),见 service/hub_perm.py
hub_permission: dict = field(default_factory=dict)
@property
def person_id(self) -> str:
"""用户主键的字符串形式,用于 ``person`` 这类字符串型业务列。"""
return str(self.person.id)
@property
def display_name(self) -> str:
return self.person.display_name
@property
def account(self) -> str:
"""``ref`` 的另一个读法:这一列存的就是登录账号,读成 account 更不容易误解。"""
return self.ref
def can(self, code: str) -> bool:
return self.is_admin or code in self.permissions
def apply_scope(self, scope: str, *, union: bool = True) -> None:
"""换口径时连数据授权一起换,别让两者各说一套。
``union=True``(合并模式)是把新口径并进已有授权,自定义角色勾的部门保留;
``union=False``(以统一身份为准)是整体覆盖,本地角色勾的部门一律作废。
"""
fresh = perm.grant_for_scope(scope)
self.data_grant = perm.merge_grant(self.data_grant, fresh) if union else fresh
self.data_scope = self.data_grant.scope
@classmethod
def resolve(
cls,
db: Session,
person: models.User,
ref: str,
roles: list[models.AuthRole] | None = None,
) -> "CurrentUser":
# ``roles`` 是随人员行一起取回来的那批权限角色;没给就现查(口径见 resolve_grant)。
# 权限每次现查这件事不变:改了角色立刻生效,这里少的只是排队。
codes, grant, names = perm.resolve_grant(db, person.id, roles=roles)
is_admin = person.role == models.ROLE_ADMIN or perm.ALL in codes
if is_admin:
grant = perm.DataGrant(scope=perm.SCOPE_ALL, unit_persons=True)
user = cls(
person=person,
ref=ref,
is_admin=is_admin,
permissions=tuple(codes),
data_scope=grant.scope,
data_grant=grant,
role_names=tuple(names),
)
# 统一身份权限(可选的一层):从 Hub 取角色/权限码/数据范围,按配置决定只对照
# 还是真参与判定。没启用时这里只是一个布尔判断,不碰网络。
from .service import hub_perm
user.hub_permission = hub_perm.resolve_for(user)
return user
def bearer_token(authorization: str | None = Header(default=None)) -> str:
if not authorization:
raise unauthorized("缺少 Authorization 头")
scheme, _, value = authorization.partition(" ")
if scheme.lower() != "bearer" or not value.strip():
raise unauthorized("Authorization 头格式错误")
return value.strip()
def current_user(
db: Session = Depends(get_db),
token: str = Depends(bearer_token),
) -> CurrentUser:
try:
payload = decode_token(token)
except ExpiredSignatureError:
# 到点与"签名认不出"是两回事,查的方向也相反:前者是页面挂着过了
# ``access_token_minutes``(正常,前端拿刷新令牌静默续回来),后者多半是
# ``jwt_secret`` 变了(换配置档、换环境重启,全站的旧令牌一起作废)。
# 访问日志里两种都只有一行 401,不分开写就分不出来。
raise unauthorized("登录已过期,请重新登录", reason="TOKEN_EXPIRED") from None
except JWTError:
raise unauthorized(reason="TOKEN_INVALID") from None
if payload.get("type") != "access":
raise unauthorized("登录凭证不对,请重新登录", reason="TOKEN_TYPE")
# 部门跟着用户一起取:只要一个 JOIN,不多一次来回,却替后面省掉一整趟。
# ``actor_of`` 与发起/打印那几处取值都要读 ``person.organization_path``,那是
# ``User.unit`` 上的 lazy 关系——不预先带上,每个要搭 Actor 的请求(发起、审批、
# 转办、评论、试跑……)都会在业务代码中途偷偷再问一次 ``oa_unit``,整行连
# ``description`` 一起搬回来(实测 POST /draft 干跑就多这一条)。
# 以前这里 join 的是 ``oa_identity``:认人只用登录账号(见 service/personref.py),
# 「一人多身份、以哪个身份操作」那套口径已经退役,那张表也跟着下线了。
# 权限角色也跟着 JOIN 进来:认人是每个请求的第一件事,人员与角色分两趟问就是请求
# 开头白排一次队(本部署一趟 9~18ms);但权限照旧每次现查,改角色立刻生效不动。
person = db.get(
models.User,
models.as_id(payload.get("sub")),
options=[joinedload(models.User.unit), joinedload(models.User.auth_roles)],
)
if person is None or not person.can_login:
# 令牌本身没问题,是令牌里那个人不在了:停用,或者人员表被人清空重灌之后主键
# 换了(Hub 全量重建就是这种:JWT 的 sub 还是旧 id)。前端两种都只能重新登录,
# 但日志里分得开——整屏 401 到底是没人登录,还是人没了。
raise unauthorized("账号不存在或已停用", reason="ACCOUNT_UNAVAILABLE")
# 这一趟是全站第一个问 ``users`` 的,报给认人的共用装载器(``personref.rows_for``):
# 发起人/办理人随后还要被姓名、状态、部门各问一遍,别再排三次队。
personref.note_row(db, person)
# 老前端与老令牌可能还带着 ``X-Identity`` 头与 ``identity`` 声明:那是"以哪个身份
# 操作"那套 O2OA 口径留下来的,本部署不用多身份,DN 又跟着部门改名漂,所以这一层
# 整个退役,收了也不参与判定——传什么都不会把列表筛成空,也不会把别人的待办筛进来。
return CurrentUser.resolve(db, person, personref.ref_of(person), roles=list(person.auth_roles))
def require_permission(code: str):
"""Route guard for a single permission code from the catalog."""
def dependency(user: CurrentUser = Depends(current_user)) -> CurrentUser:
if not user.can(code):
raise forbidden("无权限执行该操作")
return user
return dependency
def require_admin(user: CurrentUser = Depends(current_user)) -> CurrentUser:
if not user.is_admin:
raise forbidden("需要管理员权限")
return user
def actor_of(user: CurrentUser):
"""把当前请求折成引擎的 :class:`~app.engine.engine.Actor`。
``ref`` 是账号;部门直接读人员表,不再从 DN 里拆——拆出来那份是"这个 DN 当初挂在
哪个部门下",而发起人换部门之后要看的是他现在在哪个部门。
"""
from .engine.engine import Actor
return Actor(
person_id=user.person_id,
person_name=user.person.display_name,
ref=user.ref,
unit=user.person.organization_path,
unit_name=user.person.organization_name,
is_admin=user.is_admin,
)
def client_ip(request: Request) -> str:
forwarded = request.headers.get("x-forwarded-for")
if forwarded:
return forwarded.split(",")[0].strip()
return request.client.host if request.client else ""
__all__ = [
"CurrentUser",
"actor_of",
"client_ip",
"current_user",
"require_admin",
"require_permission",
]