fourcal-pms/backend/app/models/permission.py

277 lines
13 KiB
Python
Raw Permalink 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.

"""菜单权限、角色权限与数据权限。
三件事分开建模,是因为它们的变更频率和负责人根本不同:
* **菜单/操作权限**(``perm_node`` + ``perm_role_node``)决定"能看见哪些菜单、能点哪些按钮、
能调哪些接口",一份权限码同时管这三层,避免菜单藏了但接口还通;
* **角色**(``perm_role``)是授权的单位,人可以有多个角色,权限取并集;
* **数据权限**(``perm_data_policy``)单独一张策略表而不是在角色上挂一个 scope 字段,
因为现实需求是"同一个人,在项目列表上看全公司,在结算列表上只看本部门,
在预算列表上看本部门及下级但金额超过 500 万要藏掉"——按模块各配一条,
还要能按角色/人/部门三种主体下发,并且支持自定义条件。详见 docs/数据权限设计.md。
"""
from __future__ import annotations
from sqlalchemy import ForeignKey, Index, Integer, String, Text, UniqueConstraint, text
from sqlalchemy.orm import Mapped, mapped_column
from .base import Base, SoftDeleteMixin, TimestampMixin, u_bigint, u_tinyint
#: 没有任何数据权限策略命中时的兜底范围,避免把人彻底锁在系统外
FALLBACK_SCOPE = "self"
class PermKind:
"""权限节点类型。"""
MENU = "menu" # 菜单节点(会出现在左侧导航里)
GROUP = "group" # 纯分组,不跳转
ACTION = "action" # 按钮/接口级操作
DATA = "data" # "数据范围"开关(界面上勾"可看全公司"这类)
ALL = (MENU, GROUP, ACTION, DATA)
LABELS = {MENU: "菜单", GROUP: "分组", ACTION: "操作", DATA: "数据范围"}
class PermNode(Base, SoftDeleteMixin):
"""权限目录树:菜单 + 操作 + 数据开关,一个 code 打天下。
``code`` 是稳定标识(如 ``project:budget:approve``),前端按钮与后端接口都按它鉴权;
``path``/``icon`` 只在 ``kind=menu`` 时有意义,前端路由直接照它生成。
"""
__tablename__ = "perm_node"
__table_args__ = (
UniqueConstraint("code", name="uk_perm_node_code"),
Index("idx_perm_node_parent", "parent_id"),
{"mysql_charset": "utf8mb4", "mysql_collate": "utf8mb4_unicode_ci"},
)
id: Mapped[int] = mapped_column(u_bigint(), primary_key=True, autoincrement=True)
code: Mapped[str] = mapped_column(String(128), nullable=False, comment="权限码,前后端共用")
name: Mapped[str] = mapped_column(String(128), nullable=False, comment="显示名称")
kind: Mapped[str] = mapped_column(String(16), default=PermKind.MENU, nullable=False)
parent_id: Mapped[int] = mapped_column(u_bigint(), default=0, server_default="0", nullable=False)
path: Mapped[str] = mapped_column(String(255), default="", nullable=False, comment="前端路由")
icon: Mapped[str] = mapped_column(String(64), default="", nullable=False)
module: Mapped[str] = mapped_column(String(64), default="", nullable=False, index=True,
comment="所属业务模块,数据权限按它匹配")
sort: Mapped[int] = mapped_column(Integer, default=100, server_default="100", nullable=False)
visible: Mapped[bool] = mapped_column(u_tinyint(), default=True, server_default="1", nullable=False,
comment="菜单是否显示(隐藏但仍可授权时用)")
enabled: Mapped[bool] = mapped_column(u_tinyint(), default=True, server_default="1", nullable=False)
remark: Mapped[str] = mapped_column(String(500), default="", nullable=False)
created_at: Mapped[str] = mapped_column(
String(32), default="", server_default=text("''"), nullable=False
)
class PermRole(Base, TimestampMixin, SoftDeleteMixin):
"""角色。
老系统用 ``sys_role.level``(1 执行董事、2 财务总监…)把"岗位级别"和"审批身份"
混在一起,改一个动两边;这里角色只负责授权,审批人解析走岗位与专门的候选人策略。
"""
__tablename__ = "perm_role"
__table_args__ = (
UniqueConstraint("code", name="uk_perm_role_code"),
{"mysql_charset": "utf8mb4", "mysql_collate": "utf8mb4_unicode_ci"},
)
id: Mapped[int] = mapped_column(u_bigint(), primary_key=True, autoincrement=True)
code: Mapped[str] = mapped_column(String(64), nullable=False)
name: Mapped[str] = mapped_column(String(128), nullable=False)
# 内置角色不允许删除,避免把自己锁在系统外
builtin: Mapped[bool] = mapped_column(u_tinyint(), default=False, server_default="0", nullable=False)
enabled: Mapped[bool] = mapped_column(u_tinyint(), default=True, server_default="1", nullable=False)
order_number: Mapped[int] = mapped_column(Integer, default=100, server_default="100", nullable=False)
remark: Mapped[str] = mapped_column(String(500), default="", nullable=False)
class PermAccountRole(Base):
"""人-角色。多角色取权限并集、数据权限并集。"""
__tablename__ = "perm_account_role"
__table_args__ = (
UniqueConstraint("account_id", "role_id", name="uk_perm_account_role"),
Index("idx_perm_account_role_role", "role_id"),
{"mysql_charset": "utf8mb4", "mysql_collate": "utf8mb4_unicode_ci"},
)
id: Mapped[int] = mapped_column(u_bigint(), primary_key=True, autoincrement=True)
account_id: Mapped[int] = mapped_column(
u_bigint(), ForeignKey("accounts.id", ondelete="CASCADE"), nullable=False, index=True
)
role_id: Mapped[int] = mapped_column(
u_bigint(), ForeignKey("perm_role.id", ondelete="CASCADE"), nullable=False, index=True
)
class PermRoleNode(Base):
"""角色-权限码。"""
__tablename__ = "perm_role_node"
__table_args__ = (
UniqueConstraint("role_id", "node_id", name="uk_perm_role_node"),
Index("idx_perm_role_node_node", "node_id"),
{"mysql_charset": "utf8mb4", "mysql_collate": "utf8mb4_unicode_ci"},
)
id: Mapped[int] = mapped_column(u_bigint(), primary_key=True, autoincrement=True)
role_id: Mapped[int] = mapped_column(
u_bigint(), ForeignKey("perm_role.id", ondelete="CASCADE"), nullable=False, index=True
)
node_id: Mapped[int] = mapped_column(
u_bigint(), ForeignKey("perm_node.id", ondelete="CASCADE"), nullable=False, index=True
)
class ScopeType:
"""数据范围类型。
刻意做得比"self/unit/all"三种多:老系统里既有"按角色和人员配置项目可见性"
(``project_visible`` 表),也有"按部门"、还有"我参与的",几种口径在同一系统里
长期共存,所以这里全部保留成可组合的范围类型,而不是逼业务二选一。
"""
ALL = "all" # 全部数据
SELF = "self" # 仅本人创建/负责
UNIT = "unit" # 本部门
UNIT_AND_BELOW = "unit_and_below" # 本部门及下级部门
ORG_LIST = "org_list" # 指定的若干部门(可含/不含下级)
IDENTITY_UNITS = "identity_units" # 本人全部身份所在部门(兼岗也算)
PARTICIPANT = "participant" # 我参与的(成员/协作/被抄送)
ACCOUNT_LIST = "account_list" # 指定的若干人
DEPT_OF_RECORD = "dept_of_record" # 按数据行上的部门字段判定(默认口径)
CUSTOM = "custom" # 只用自定义条件,不限定主体范围
ALL_TYPES = (
ALL, SELF, UNIT, UNIT_AND_BELOW, ORG_LIST,
IDENTITY_UNITS, PARTICIPANT, ACCOUNT_LIST, DEPT_OF_RECORD, CUSTOM,
)
#: 用于"取并集时谁更宽"的比较;只影响提示与冲突检查,不改变语义
RANK = {
SELF: 0,
PARTICIPANT: 1,
UNIT: 2,
IDENTITY_UNITS: 2,
UNIT_AND_BELOW: 3,
ORG_LIST: 3,
ACCOUNT_LIST: 2,
CUSTOM: 2,
DEPT_OF_RECORD: 2,
ALL: 9,
}
LABELS = {
ALL: "全部数据",
SELF: "仅本人",
UNIT: "本部门",
UNIT_AND_BELOW: "本部门及下级",
ORG_LIST: "指定部门",
IDENTITY_UNITS: "本人所属部门(含兼岗)",
PARTICIPANT: "我参与的",
ACCOUNT_LIST: "指定人员",
DEPT_OF_RECORD: "按数据归属部门",
CUSTOM: "仅自定义条件",
}
@classmethod
def label(cls, value: str) -> str:
return cls.LABELS.get(value, value)
class SubjectType:
"""数据权限策略挂在谁身上。"""
ALL = "all" # 所有人
ROLE = "role"
ACCOUNT = "account"
ORG_UNIT = "org_unit" # 挂在部门上:这个部门里的人都吃这条
POSITION = "position"
ALL_TYPES = (ALL, ROLE, ACCOUNT, ORG_UNIT, POSITION)
LABELS = {ALL: "所有人", ROLE: "按角色", ACCOUNT: "按账号",
ORG_UNIT: "按部门", POSITION: "按岗位"}
class Effect:
ALLOW = "allow"
DENY = "deny"
LABELS = {ALLOW: "允许", DENY: "排除"}
class FieldScope(Base):
"""字段级权限:某些列对某些角色隐藏(如成本单价、供应商名称)。"""
__tablename__ = "perm_field_scope"
__table_args__ = (
UniqueConstraint("module", "field", "role_id", name="uk_perm_field_scope"),
{"mysql_charset": "utf8mb4", "mysql_collate": "utf8mb4_unicode_ci"},
)
id: Mapped[int] = mapped_column(u_bigint(), primary_key=True, autoincrement=True)
module: Mapped[str] = mapped_column(String(64), nullable=False, index=True)
field: Mapped[str] = mapped_column(String(64), nullable=False)
role_id: Mapped[int] = mapped_column(
u_bigint(), ForeignKey("perm_role.id", ondelete="CASCADE"), nullable=False, index=True
)
mode: Mapped[str] = mapped_column(
String(16), default="hidden", server_default="hidden", nullable=False,
comment="hidden=不返回 masked=打码 readonly=只读",
)
class PermDataPolicy(Base, TimestampMixin, SoftDeleteMixin):
"""一条数据权限策略。
求值方式(见 ``app.service.data_scope``):
1. 找出所有命中当前人的策略(主体 = 全部 / 我的任一角色 / 我本人 / 我任一部门 /
我的任一岗位,且模块对得上);
2. 每条 allow 策略 = ``范围谓词 AND 自定义条件``,多条之间取 **OR**;
3. 每条 deny 策略同样算出谓词,多条之间取 OR,最后 **AND NOT** 掉;
4. 一条 allow 都没命中时用兜底范围 ``self``,不会把人锁死。
``conditions_json`` 是一棵可嵌套的条件树,因此能表达"金额≥500 万 且(状态=通过 或
部门∈{财务…})"这类自定义规则,而不必为每种组合加代码。
"""
__tablename__ = "perm_data_policy"
__table_args__ = (
Index("idx_perm_data_policy_module", "module", "enabled"),
Index("idx_perm_data_policy_subject", "subject_type", "subject_id"),
{"mysql_charset": "utf8mb4", "mysql_collate": "utf8mb4_unicode_ci"},
)
id: Mapped[int] = mapped_column(u_bigint(), primary_key=True, autoincrement=True)
name: Mapped[str] = mapped_column(String(128), nullable=False)
module: Mapped[str] = mapped_column(
String(64), nullable=False, comment="业务模块:project/estimate/budget/settlement/final/approval"
)
subject_type: Mapped[str] = mapped_column(String(16), default=SubjectType.ROLE, nullable=False)
subject_id: Mapped[int] = mapped_column(u_bigint(), default=0, server_default="0", nullable=False)
effect: Mapped[str] = mapped_column(String(8), default=Effect.ALLOW, nullable=False)
scope_type: Mapped[str] = mapped_column(String(32), default=ScopeType.SELF, nullable=False)
# scope_type=org_list/account_list 时用的 id 列表,JSON 数组
target_ids_json: Mapped[str] = mapped_column(Text, default="[]", nullable=False)
# 是否把指定部门的下级也算进来
include_children: Mapped[bool] = mapped_column(
u_tinyint(), default=True, server_default="1", nullable=False
)
# 自定义条件树:{"op":"and","items":[{"field":..,"op":..,"value":..}]}
conditions_json: Mapped[str] = mapped_column(Text, default="", nullable=False)
# 同一模块内多条策略的评估顺序;deny 先于 allow 生效,priority 只影响同种效果内部的顺序
priority: Mapped[int] = mapped_column(Integer, default=100, server_default="100", nullable=False)
enabled: Mapped[bool] = mapped_column(u_tinyint(), default=True, server_default="1", nullable=False)
# 临时策略:到期自动失效,用于"项目交接期间临时授权"
valid_from: Mapped[str] = mapped_column(String(32), default="", nullable=False)
valid_to: Mapped[str] = mapped_column(String(32), default="", nullable=False)
remark: Mapped[str] = mapped_column(String(500), default="", nullable=False)