unis-oa/backend/app/permissions.py

451 lines
17 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.

"""权限目录、数据范围与角色解析。
菜单可见性、接口访问、列表数据过滤都读这里,所以一次角色授权就能同时改变
“能看到哪些菜单 / 能调哪些接口 / 能看到哪些数据”。
"""
from __future__ import annotations
from dataclasses import dataclass
from typing import Iterable
from sqlalchemy import select
from sqlalchemy.orm import Session
from . import models
from .service import org
ALL = "*"
SCOPE_SELF = "self"
SCOPE_UNIT = "unit"
SCOPE_UNIT_AND_BELOW = "unit_and_below"
SCOPE_CUSTOM = "custom"
SCOPE_ALL = "all"
SCOPES = (SCOPE_SELF, SCOPE_UNIT, SCOPE_UNIT_AND_BELOW, SCOPE_CUSTOM, SCOPE_ALL)
#: 只用来给"最宽一档"排序展示;真正的可见范围按 DataGrant 求并集,不看这个名次
_SCOPE_RANK = {SCOPE_SELF: 0, SCOPE_UNIT: 1, SCOPE_UNIT_AND_BELOW: 2, SCOPE_CUSTOM: 3, SCOPE_ALL: 4}
# 没有任何权限角色时使用的兜底范围,避免把人彻底锁在系统外。
FALLBACK_SCOPE = SCOPE_SELF
FALLBACK_ROLE = "普通员工"
@dataclass(frozen=True)
class Permission:
code: str
group: str
def _group(group: str, codes: Iterable[str]) -> tuple[Permission, ...]:
return tuple(Permission(code, group) for code in codes)
# 目录顺序即权限矩阵里的展示顺序。菜单权限与操作权限混编在同一分组里。
CATALOG: tuple[Permission, ...] = (
*_group(
"work",
(
"work:workbench",
"work:start",
"work:todo",
"work:done",
"work:created",
"work:read",
"work:draft",
"work:agent",
"work:handover",
"work:profile",
# 外部核验闸门的应急放行:单开一档,不给普通审批人。放行会把"外部没审过"
# 这件事变成一次有名字的人工背书,能按这个钮的人必须是少数几个人
"work:gatePass",
),
),
*_group("portal", ("portal:home", "portal:document", "portal:meeting", "portal:schedule", "portal:file", "portal:manage")),
*_group(
"design",
(
"design:process",
"design:form",
"design:category",
"design:quota",
"design:datasource",
"design:integration",
# 开放平台:应用凭证、事件订阅、调用留痕。给的是"往外发数据的手",
# 和写回集成同组同权重——泄露一把 app_secret 与泄露一个集成账号是一回事
"design:openapi",
),
),
*_group("org", ("org:unit", "org:person", "org:role", "org:authrole")),
*_group("system", ("monitor:work", "statistics:view", "log:view", "system:setting",
# 消息渠道:配 SMTP / 群机器人,看投递记录(里面有收件人邮箱)
"system:notify")),
)
GROUPS: tuple[str, ...] = tuple(dict.fromkeys(p.group for p in CATALOG))
CODES: frozenset[str] = frozenset(p.code for p in CATALOG)
PERSONAL_CODES: tuple[str, ...] = tuple(p.code for p in CATALOG if p.group in ("work", "portal"))
PORTAL_CODES: tuple[str, ...] = tuple(p.code for p in CATALOG if p.group == "portal")
WORK_CODES: tuple[str, ...] = tuple(p.code for p in CATALOG if p.group == "work")
def is_known(code: str) -> bool:
return code == ALL or code in CODES
def clean_codes(codes: Iterable[str]) -> list[str]:
"""Keep known codes only, preserving the catalog order; ``*`` wins everything."""
wanted = {str(code) for code in codes or ()}
if ALL in wanted:
return [ALL]
return [p.code for p in CATALOG if p.code in wanted]
def clean_scope(scope: str) -> str:
value = (scope or "").strip()
return value if value in SCOPES else FALLBACK_SCOPE
def clean_unit_ids(unit_ids: Iterable[object]) -> list[int]:
"""去重保序的部门 id 列表。
存进 ``oa_auth_role.data_unit_ids`` 前一律过这一道:前端传的是字符串 id
(接口层的 id 统一是字符串),库里存 BIGINT 才和 ``oa_unit.id`` 对得上,
脏值(改名、误传、部门已删)直接丢掉而不是让查询炸掉。
"""
result: list[int] = []
for value in unit_ids or ():
key = models.as_id(value)
if key is not None and key not in result:
result.append(key)
return result
# --------------------------------------------------------------------------
# 数据授权
# --------------------------------------------------------------------------
@dataclass(frozen=True)
class DataGrant:
"""多角色合并后的数据可见口径。
``scope`` 只是对外播报的"最宽一档"(登录响应、权限角色列表读它),真正决定
where 条件的是后面几块:按自己部门展开的口径、自定义勾选的部门集合、以及要不要
带上本人。多角色取并集,所以「自定义[研发中心] + 本部门」这种组合两边都看得见,
不会因为名次比较把其中一边挤掉。
"""
scope: str = SCOPE_SELF
#: 有角色选了自定义口径;哪怕还没勾部门,也要按自定义的规矩解释
custom: bool = False
#: 按登录人自己的部门展开:``""`` / ``unit`` / ``unit_and_below``
own_unit: str = ""
#: 自定义口径勾选的部门 id
custom_units: tuple[int, ...] = ()
#: 自定义勾选的部门是否连带下级
custom_children: bool = True
#: 除部门之外要不要始终带上本人数据
include_self: bool = True
#: 人员/身份口径:按部门圈人,还是只看本人
unit_persons: bool = False
@property
def unrestricted(self) -> bool:
return self.scope == SCOPE_ALL
def grant_for_scope(scope: str) -> DataGrant:
"""把一个光秃秃的口径换成授权(统一身份给的、老代码里的 ``data_scope``)。"""
value = clean_scope(scope)
if value == SCOPE_ALL:
return DataGrant(scope=value, unit_persons=True)
if value == SCOPE_CUSTOM:
# 没带部门集合的自定义只能按"只有本人"解释,等角色配置补齐再收紧
return DataGrant(scope=value, custom=True)
own = SCOPE_UNIT_AND_BELOW if value == SCOPE_UNIT_AND_BELOW else SCOPE_UNIT
# 「仅本人」在部门类列表(组织树、部门列表)里仍然看得见自己那棵树,
# 但人员与身份口径只到本人,这是接数据范围以来一贯的行为。
return DataGrant(scope=value, own_unit=own, unit_persons=value != SCOPE_SELF)
def grant_for_role(role) -> DataGrant:
"""单个权限角色 -> 授权;自定义口径要连角色上挂的部门集合一起读。"""
scope = clean_scope(getattr(role, "data_scope", ""))
if scope != SCOPE_CUSTOM:
return grant_for_scope(scope)
return DataGrant(
scope=scope,
custom=True,
custom_units=tuple(clean_unit_ids(getattr(role, "data_unit_ids", ()) or ())),
custom_children=bool(getattr(role, "data_unit_children", True)),
include_self=bool(getattr(role, "data_include_self", True)),
unit_persons=True,
)
def merge_grant(left: DataGrant, right: DataGrant) -> DataGrant:
"""两个授权求并集:多角色合并、统一身份权限叠加都走这一道。"""
units = tuple(dict.fromkeys((*left.custom_units, *right.custom_units)))
custom = left.custom or right.custom
if left.unrestricted or right.unrestricted:
return DataGrant(scope=SCOPE_ALL, custom=custom, custom_units=units, unit_persons=True)
own_unit = next(
(candidate for candidate in (SCOPE_UNIT_AND_BELOW, SCOPE_UNIT) if candidate in (left.own_unit, right.own_unit)),
"",
)
widest = left.scope if _SCOPE_RANK.get(left.scope, 0) >= _SCOPE_RANK.get(right.scope, 0) else right.scope
return DataGrant(
scope=SCOPE_CUSTOM if custom else widest,
custom=custom,
own_unit=own_unit,
custom_units=units,
custom_children=left.custom_children or right.custom_children,
# 只要有一边给了部门口径,本人数据就跑不掉
include_self=left.include_self or right.include_self or bool(own_unit),
unit_persons=left.unit_persons or right.unit_persons,
)
def grant_of(user) -> DataGrant:
"""取当前用户的授权。
正常路径是 ``CurrentUser.data_grant``(角色解析时就算好了);没有带授权的对象
(手写测试桩、只塞了 ``data_scope`` 的旧代码)按口径兜一份,语义退化成"没有自定义部门"。
"""
grant = getattr(user, "data_grant", None)
if isinstance(grant, DataGrant) and grant.scope == clean_scope(getattr(user, "data_scope", "")):
return grant
return grant_for_scope(getattr(user, "data_scope", FALLBACK_SCOPE))
@dataclass(frozen=True)
class BuiltinRole:
name: str
description: str
permissions: tuple[str, ...]
data_scope: str
sort: int
BUILTIN_ROLES: tuple[BuiltinRole, ...] = (
BuiltinRole("超级管理员", "系统内置,拥有全部菜单与全部数据", (ALL,), SCOPE_ALL, 0),
BuiltinRole(
"部门负责人",
"本人及下属部门的流程监控与统计",
clean_codes((*WORK_CODES, "portal:home", "portal:document", "portal:meeting", "portal:schedule", "portal:file", "monitor:work", "statistics:view")),
SCOPE_UNIT_AND_BELOW,
10,
),
BuiltinRole(
"普通员工",
"日常办公与自助门户",
clean_codes((*WORK_CODES, "portal:home", "portal:document", "portal:meeting", "portal:schedule", "portal:file")),
SCOPE_SELF,
20,
),
)
# --------------------------------------------------------------------------
# 角色解析
# --------------------------------------------------------------------------
def roles_of(db: Session, person_id: int | str) -> list[models.AuthRole]:
rows = db.execute(
select(models.AuthRole)
.join(models.PersonAuthRole, models.PersonAuthRole.role_id == models.AuthRole.id)
.where(
models.PersonAuthRole.person_id == models.as_id(person_id),
models.AuthRole.enabled.is_(True),
)
.order_by(models.AuthRole.sort, models.AuthRole.name)
).scalars().all()
return list(rows)
def resolve(db: Session, person_id: int | str) -> tuple[list[str], str, list[str]]:
"""Return ``(permissions, data_scope, role_names)`` for a person."""
codes, grant, names = resolve_grant(db, person_id)
return codes, grant.scope, names
def resolve_grant(
db: Session, person_id: int | str, roles: list[models.AuthRole] | None = None
) -> tuple[list[str], DataGrant, list[str]]:
"""Return ``(permissions, data_grant, role_names)`` for a person.
Multiple roles merge: permissions are unioned and so are the data scopes,
so granting a second role can only widen what a person can do. Unioning
(rather than "widest wins") is what keeps a ``custom`` role stackable with a
plain ``unit`` one instead of silently replacing it.
``roles`` 给成调用方已经取好的那批(登录/鉴权这一路是随人员行一起 JOIN 出来的
``users.auth_roles``),就不再回库问第二次。给的必须是与 :func:`roles_of` 同一个
口径:只认启用的、按 ``sort, name`` 排——顺序会进到 ``role_names`` 报文里。
"""
roles = roles_of(db, person_id) if roles is None else list(roles)
if not roles:
fallback = next((r for r in BUILTIN_ROLES if r.name == FALLBACK_ROLE), None)
if fallback is None:
return [], DataGrant(), []
return list(fallback.permissions), grant_for_scope(fallback.data_scope), []
permissions: set[str] = set()
grant: DataGrant | None = None
for role in roles:
permissions.update(role.permissions or [])
role_grant = grant_for_role(role)
grant = role_grant if grant is None else merge_grant(grant, role_grant)
if grant is None:
grant = DataGrant()
if ALL in permissions:
grant = merge_grant(grant, DataGrant(scope=SCOPE_ALL, unit_persons=True))
return clean_codes(permissions), grant, [r.name for r in roles]
# --------------------------------------------------------------------------
# 数据范围过滤
# --------------------------------------------------------------------------
def unrestricted(user) -> bool:
return user.is_admin or grant_of(user).unrestricted
def scope_unit_ids(db: Session, user) -> list[int] | None:
"""可见部门 id;返回 ``None`` 表示不限制。"""
if unrestricted(user):
return None
grant = grant_of(user)
own_unit = user.person.organization_id
if grant.own_unit == SCOPE_UNIT_AND_BELOW and own_unit:
units = org.descendant_unit_ids(db, own_unit)
elif grant.own_unit == SCOPE_UNIT and own_unit:
units = [own_unit]
else:
units = []
# 自定义勾选逐颗展开:"含下级"是一个总开关,勾中的部门整棵子树都要
if grant.custom:
for unit_id in grant.custom_units:
if unit_id in units:
continue
if grant.custom_children:
units.extend(uid for uid in org.descendant_unit_ids(db, unit_id) if uid not in units)
else:
units.append(unit_id)
return units
def scope_person_ids(db: Session, user) -> list[int] | None:
"""可见人员 id;返回 ``None`` 表示不限制。"""
if unrestricted(user):
return None
grant = grant_of(user)
wanted: list[object] = [user.person_id] if grant.include_self else []
unit_ids = scope_unit_ids(db, user) if grant.unit_persons else []
if unit_ids:
wanted.extend(
db.execute(
select(models.User.id).where(models.User.organization_id.in_(unit_ids))
).scalars().all()
)
result: list[int] = []
seen: set[int] = set()
for value in wanted:
# ``user.person_id`` 是字符串、``users.id`` 是 BIGINT,一份白名单里两种都有
key = models.as_id(value)
if key is not None and key not in seen:
seen.add(key)
result.append(key)
return result
def scope_person_refs(db: Session, user) -> list[str] | None:
"""可见人员的账号清单;返回 ``None`` 表示不限制。
待办、流程实例这些表存的是人员引用(账号,见 :mod:`app.service.personref`),所以
先把部门换算成人员集合再过滤,避免用 ``LIKE`` 前缀匹配时把同名前缀的兄弟部门一起
捞出来。以前这一份换算是身份 DN:部门一改名,白名单里全是新 DN,历史单据的列里
还是旧 DN,主管手一伸就把自己部门改名前的单子全筛没了。
"""
if unrestricted(user):
return None
grant = grant_of(user)
unit_ids = scope_unit_ids(db, user) if (grant.unit_persons or grant.custom) else []
# scope_unit_ids 已经把下级展开完了,这里不能再用 contains_sub 展开一遍
values = org.identities_for_unit(db, unit_ids, contains_sub=False) if unit_ids else []
if grant.include_self and user.ref and user.ref not in values:
values.append(user.ref)
return values
#: 旧名字留给还没跟上的调用方;新代码用 :func:`scope_person_refs`。
scope_identity_values = scope_person_refs
def scope_values(column, values: list) -> list:
"""把白名单换算成目标列的类型:``users.id`` 是 BIGINT,而流程表里的
``person`` 列存的是 id 字符串,同一个白名单不能原样塞进两种列。"""
from sqlalchemy import BigInteger, Integer, String, Text # noqa: PLC0415
if isinstance(column.type, (String, Text)):
return [str(v) for v in values]
if isinstance(column.type, (Integer, BigInteger)):
return [v for v in (models.as_id(value) for value in values) if v is not None]
return list(values)
def in_scope_clause(column, values: list[str] | None):
"""把白名单翻译成 where 条件;白名单为 ``None`` 时不加条件。"""
from sqlalchemy import Integer, String, Text # noqa: PLC0415
if values is None:
return None
if values:
return column.in_(scope_values(column, values))
empty = [-1] if isinstance(column.type, (Integer,)) else ["__none__"]
return column.in_(empty)
def scoped(stmt, user, column, values: list[str] | None):
clause = in_scope_clause(column, values)
return stmt if clause is None else stmt.where(clause)
__all__ = [
"ALL",
"BUILTIN_ROLES",
"CATALOG",
"CODES",
"FALLBACK_ROLE",
"GROUPS",
"PERSONAL_CODES",
"SCOPES",
"SCOPE_ALL",
"SCOPE_CUSTOM",
"SCOPE_SELF",
"SCOPE_UNIT",
"SCOPE_UNIT_AND_BELOW",
"WORK_CODES",
"DataGrant",
"clean_codes",
"clean_scope",
"clean_unit_ids",
"grant_for_role",
"grant_for_scope",
"grant_of",
"in_scope_clause",
"is_known",
"merge_grant",
"resolve",
"resolve_grant",
"roles_of",
"scoped",
"scope_identity_values",
"scope_person_refs",
"scope_person_ids",
"scope_unit_ids",
"unrestricted",
]