266 lines
8.9 KiB
Python
266 lines
8.9 KiB
Python
"""角色解析、菜单树与权限判定。
|
||
|
||
一份权限码同时管三层:菜单可见性、按钮可用性、接口放行。老系统 ``sys_permission``
|
||
的 ``url`` 与 ``permission`` 是两个独立字段,菜单按 url 过滤、接口按 permission 过滤,
|
||
两边靠人工保持一致,实际线上出现过"菜单藏了但直接敲 URL 还能进"的情况。这里只认
|
||
``code``,接口声明需要什么码就查什么码。
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
from dataclasses import dataclass, field
|
||
from typing import Any, Iterable
|
||
|
||
from sqlalchemy import select
|
||
from sqlalchemy.orm import Session
|
||
|
||
from ..models import Account, PermAccountRole, PermDataPolicy, PermNode, PermRole, PermRoleNode
|
||
|
||
ALL = "*"
|
||
|
||
|
||
@dataclass
|
||
class RoleView:
|
||
id: int
|
||
code: str
|
||
name: str
|
||
builtin: bool = False
|
||
|
||
|
||
@dataclass
|
||
class PermissionContext:
|
||
"""一个人登录后的全部授权视图,随令牌缓存。"""
|
||
|
||
account_id: int
|
||
roles: list[RoleView] = field(default_factory=list)
|
||
codes: frozenset[str] = frozenset()
|
||
is_system_admin: bool = False
|
||
field_masks: dict[str, dict[str, str]] = field(default_factory=dict)
|
||
|
||
def can(self, code: str) -> bool:
|
||
return self.is_system_admin or ALL in self.codes or code in self.codes
|
||
|
||
def can_any(self, codes: Iterable[str]) -> bool:
|
||
wanted = set(codes)
|
||
return self.is_system_admin or ALL in self.codes or bool(wanted & self.codes)
|
||
|
||
def can_all(self, codes: Iterable[str]) -> bool:
|
||
if self.is_system_admin or ALL in self.codes:
|
||
return True
|
||
return wanted_subset(self.codes, codes)
|
||
|
||
|
||
def wanted_subset(codes: frozenset[str], wanted: Iterable[str]) -> bool:
|
||
return set(wanted).issubset(codes)
|
||
|
||
|
||
def account_roles(db: Session, account_id: int) -> list[RoleView]:
|
||
rows = db.execute(
|
||
select(PermRole)
|
||
.join(PermAccountRole, PermAccountRole.role_id == PermRole.id)
|
||
.where(
|
||
PermAccountRole.account_id == account_id,
|
||
PermRole.enabled.is_(True),
|
||
PermRole.is_deleted.is_(False),
|
||
)
|
||
.order_by(PermRole.order_number, PermRole.id)
|
||
).scalars().all()
|
||
return [RoleView(role.id, role.code, role.name, role.builtin) for role in rows]
|
||
|
||
|
||
def permission_codes(db: Session, role_ids: list[int]) -> frozenset[str]:
|
||
if not role_ids:
|
||
return frozenset()
|
||
rows = db.execute(
|
||
select(PermNode.code)
|
||
.join(PermRoleNode, PermRoleNode.node_id == PermNode.id)
|
||
.where(
|
||
PermRoleNode.role_id.in_(role_ids),
|
||
PermNode.enabled.is_(True),
|
||
PermNode.is_deleted.is_(False),
|
||
)
|
||
.distinct()
|
||
).scalars().all()
|
||
return frozenset(rows)
|
||
|
||
|
||
def build_context(db: Session, account: Account) -> PermissionContext:
|
||
roles = account_roles(db, account.id)
|
||
codes = permission_codes(db, [role.id for role in roles])
|
||
return PermissionContext(
|
||
account_id=account.id,
|
||
roles=roles,
|
||
codes=codes,
|
||
is_system_admin=bool(account.is_system_admin),
|
||
field_masks=field_masks(db, [role.id for role in roles]),
|
||
)
|
||
|
||
|
||
def field_masks(db: Session, role_ids: list[int]) -> dict[str, dict[str, str]]:
|
||
"""字段级权限:多角色取最宽松的一种(hidden < masked < readonly < 可见)。"""
|
||
from ..models import FieldScope
|
||
|
||
if not role_ids:
|
||
return {}
|
||
rank = {"hidden": 0, "masked": 1, "readonly": 2}
|
||
best: dict[tuple[str, str], int] = {}
|
||
rows = db.execute(
|
||
select(FieldScope).where(FieldScope.role_id.in_(role_ids))
|
||
).scalars().all()
|
||
for row in rows:
|
||
key = (row.module, row.field)
|
||
best[key] = max(best.get(key, 99), rank.get(row.mode, 0))
|
||
out: dict[str, dict[str, str]] = {}
|
||
inverse = {value: key for key, value in rank.items()}
|
||
for (module, field_name), level in best.items():
|
||
out.setdefault(module, {})[field_name] = inverse.get(level, "hidden")
|
||
return out
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# 菜单树
|
||
# ---------------------------------------------------------------------------
|
||
|
||
|
||
def menu_tree(db: Session, context: PermissionContext) -> list[dict[str, Any]]:
|
||
"""按权限过滤后的菜单树。父节点只要有任何一个可见子节点就保留。"""
|
||
nodes = db.execute(
|
||
select(PermNode)
|
||
.where(
|
||
PermNode.kind.in_(("menu", "group")),
|
||
PermNode.enabled.is_(True),
|
||
PermNode.visible.is_(True),
|
||
PermNode.is_deleted.is_(False),
|
||
)
|
||
.order_by(PermNode.sort, PermNode.id)
|
||
).scalars().all()
|
||
|
||
by_id: dict[int, dict[str, Any]] = {}
|
||
for node in nodes:
|
||
by_id[node.id] = {
|
||
"id": node.id,
|
||
"code": node.code,
|
||
"name": node.name,
|
||
"path": node.path,
|
||
"icon": node.icon,
|
||
"kind": node.kind,
|
||
"module": node.module,
|
||
"parentId": node.parent_id,
|
||
"children": [],
|
||
"allowed": context.can(node.code),
|
||
}
|
||
|
||
roots: list[dict[str, Any]] = []
|
||
for node in by_id.values():
|
||
parent = by_id.get(node["parentId"])
|
||
if parent is not None:
|
||
parent["children"].append(node)
|
||
else:
|
||
roots.append(node)
|
||
|
||
return [prune(root) for root in roots if prune(root) is not None]
|
||
|
||
|
||
def prune(node: dict[str, Any]) -> dict[str, Any] | None:
|
||
"""自底向上剪枝:没权限的叶子去掉,子全被剪光的分组也去掉。"""
|
||
kept_children = [child for child in (prune(item) for item in node["children"]) if child]
|
||
if kept_children:
|
||
node["children"] = kept_children
|
||
return node
|
||
if node["allowed"]:
|
||
node["children"] = []
|
||
return node
|
||
return None
|
||
|
||
|
||
def permission_catalog(db: Session) -> list[dict[str, Any]]:
|
||
"""授权矩阵用的全量目录(含按钮级),不做权限过滤。
|
||
|
||
返回成树,前端矩阵就能直接渲染;勾选父节点要不要联动子节点,
|
||
交给界面决定,后端不预设这个策略。
|
||
"""
|
||
rows = db.execute(
|
||
select(PermNode).where(PermNode.is_deleted.is_(False)).order_by(PermNode.sort, PermNode.id)
|
||
).scalars().all()
|
||
nodes = {
|
||
row.id: {
|
||
"id": row.id,
|
||
"code": row.code,
|
||
"name": row.name,
|
||
"kind": row.kind,
|
||
"parentId": row.parent_id,
|
||
"module": row.module,
|
||
"path": row.path,
|
||
"icon": row.icon,
|
||
"sort": row.sort,
|
||
"enabled": row.enabled,
|
||
"children": [],
|
||
}
|
||
for row in rows
|
||
}
|
||
roots: list[dict[str, Any]] = []
|
||
for row in rows:
|
||
node = nodes[row.id]
|
||
parent = nodes.get(row.parent_id)
|
||
(parent["children"] if parent else roots).append(node)
|
||
return roots
|
||
|
||
|
||
def role_permission_ids(db: Session, role_id: int) -> list[int]:
|
||
return list(
|
||
db.execute(
|
||
select(PermRoleNode.node_id).where(PermRoleNode.role_id == role_id)
|
||
).scalars().all()
|
||
)
|
||
|
||
|
||
def set_role_permissions(db: Session, role_id: int, node_ids: list[int]) -> int:
|
||
from ..models import PermRoleNode as Link
|
||
|
||
existing = set(role_permission_ids(db, role_id))
|
||
wanted = set(node_ids)
|
||
for node_id in existing - wanted:
|
||
row = db.execute(
|
||
select(Link).where(Link.role_id == role_id, Link.node_id == node_id)
|
||
).scalar_one_or_none()
|
||
if row:
|
||
db.delete(row)
|
||
for node_id in wanted - existing:
|
||
db.add(Link(role_id=role_id, node_id=node_id))
|
||
db.flush()
|
||
return len(wanted)
|
||
|
||
|
||
def data_policies_for(db: Session, account_id: int, role_ids: list[int], org_unit_ids: list[int],
|
||
position_ids: list[int]) -> list[PermDataPolicy]:
|
||
"""捞出所有命中这个人的数据权限策略(含"挂在他所在部门/岗位上"的)。
|
||
|
||
这里只按主体粗筛,效果与模块过滤留给 :mod:`app.service.data_scope`,这样主体
|
||
解析只写一遍。
|
||
"""
|
||
from ..models import Effect, SubjectType
|
||
|
||
conditions = [
|
||
(PermDataPolicy.subject_type == SubjectType.ALL),
|
||
]
|
||
if role_ids:
|
||
conditions.append((PermDataPolicy.subject_type == SubjectType.ROLE) & PermDataPolicy.subject_id.in_(role_ids))
|
||
conditions.append((PermDataPolicy.subject_type == SubjectType.ACCOUNT) & (PermDataPolicy.subject_id == account_id))
|
||
if org_unit_ids:
|
||
conditions.append((PermDataPolicy.subject_type == SubjectType.ORG_UNIT) & PermDataPolicy.subject_id.in_(org_unit_ids))
|
||
if position_ids:
|
||
conditions.append((PermDataPolicy.subject_type == SubjectType.POSITION) & PermDataPolicy.subject_id.in_(position_ids))
|
||
|
||
from sqlalchemy import or_
|
||
|
||
rows = db.execute(
|
||
select(PermDataPolicy)
|
||
.where(
|
||
PermDataPolicy.is_deleted.is_(False),
|
||
PermDataPolicy.enabled.is_(True),
|
||
or_(*conditions),
|
||
)
|
||
.order_by(PermDataPolicy.effect, PermDataPolicy.priority, PermDataPolicy.id)
|
||
).scalars().all()
|
||
return [row for row in rows if row.effect in (Effect.ALLOW, Effect.DENY)]
|