270 lines
10 KiB
Python
270 lines
10 KiB
Python
"""权限角色:菜单/功能权限、数据范围与成员分配。
|
||
|
||
这里的“权限角色”控制的是登录用户能看到什么菜单、能调什么接口、能看到哪些
|
||
部门的数据;审批用的岗位角色在 ``/org/roles``,两者互不影响。
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
from fastapi import APIRouter, Depends
|
||
from sqlalchemy import delete, select
|
||
from sqlalchemy.orm import Session
|
||
|
||
from .. import models, permissions, schemas, serializers
|
||
from ..db import get_db
|
||
from ..deps import CurrentUser, require_permission
|
||
from ..envelope import bad_request, not_found, ok
|
||
from ..service import org
|
||
|
||
router = APIRouter(prefix="/auth-roles", tags=["permission"])
|
||
|
||
MANAGE = require_permission("org:authrole")
|
||
|
||
|
||
def _members_map(db: Session, role_ids: list[str]) -> dict[str, list[str]]:
|
||
"""一批角色的成员一次查完:列表页逐行问成员是"角色数 × 一趟数据库来回"。
|
||
|
||
成员 id 对外统一是字符串,前端拿到的和 ``/org/persons`` 里的 id 一致。
|
||
排序显式写成 ``(role_id, person_id)``:原来逐条按 ``role_id`` 查走的是那一条二级
|
||
索引,同一个角色里天然按 ``person_id`` 出来(二级索引末段挂着主键),改成 ``IN``
|
||
之后把同样的顺序写死,免得角色之间互相插队。
|
||
"""
|
||
keys = list(dict.fromkeys(str(role_id) for role_id in role_ids if str(role_id or "")))
|
||
if not keys:
|
||
return {}
|
||
out: dict[str, list[str]] = {key: [] for key in keys}
|
||
for role_id, person_id in db.execute(
|
||
select(models.PersonAuthRole.role_id, models.PersonAuthRole.person_id)
|
||
.where(models.PersonAuthRole.role_id.in_(keys))
|
||
.order_by(models.PersonAuthRole.role_id, models.PersonAuthRole.person_id)
|
||
).all():
|
||
out.setdefault(str(role_id), []).append(str(person_id))
|
||
return out
|
||
|
||
|
||
def _members(db: Session, role_id: str) -> list[str]:
|
||
"""单个角色的成员,口径见 :func:`_members_map`。"""
|
||
return _members_map(db, [role_id]).get(str(role_id), [])
|
||
|
||
|
||
def _validate_codes(codes: list[str]) -> None:
|
||
unknown = [code for code in codes if not permissions.is_known(code)]
|
||
if unknown:
|
||
raise bad_request("未知权限码: " + ", ".join(unknown))
|
||
|
||
|
||
def _clean_units(db: Session, body: schemas.AuthRoleBody) -> list[int]:
|
||
"""自定义口径的部门白名单。
|
||
|
||
非自定义口径一律清空,免得界面上改回「本部门」之后库里还留着上一次的部门集合
|
||
(那些 id 会一直参与展示与排查,却是死数据)。自定义则要求至少圈到点东西:
|
||
要么有部门,要么勾上"包含本人数据",否则这个角色的持有人会连自己的单子都看不见。
|
||
"""
|
||
if permissions.clean_scope(body.data_scope) != permissions.SCOPE_CUSTOM:
|
||
return []
|
||
unit_ids = permissions.clean_unit_ids(body.data_unit_ids)
|
||
if unit_ids:
|
||
found = set(
|
||
db.execute(select(models.Unit.id).where(models.Unit.id.in_(unit_ids))).scalars().all()
|
||
)
|
||
missing = [str(uid) for uid in unit_ids if uid not in found]
|
||
if missing:
|
||
raise bad_request("部门不存在: " + ", ".join(missing))
|
||
elif not body.data_include_self:
|
||
raise bad_request("自定义数据范围请至少勾选一个部门,或勾选「包含本人数据」")
|
||
return unit_ids
|
||
|
||
|
||
def _unit_names(db: Session, roles: list[models.AuthRole]) -> dict[int, str]:
|
||
"""角色上勾过的部门 id 一次换成名称,供列表展示"自定义(研发中心、市场部)"。"""
|
||
wanted = {
|
||
uid
|
||
for role in roles
|
||
for uid in (models.as_id(value) for value in (role.data_unit_ids or []))
|
||
if uid is not None
|
||
}
|
||
if not wanted:
|
||
return {}
|
||
return {
|
||
row.id: row.name
|
||
for row in db.execute(
|
||
select(models.Unit.id, models.Unit.name).where(models.Unit.id.in_(wanted))
|
||
).all()
|
||
}
|
||
|
||
|
||
def _get(db: Session, role_id: str) -> models.AuthRole:
|
||
role = db.get(models.AuthRole, role_id)
|
||
if role is None:
|
||
raise not_found("权限角色不存在")
|
||
return role
|
||
|
||
|
||
@router.get("/catalog", dependencies=[Depends(MANAGE)])
|
||
def catalog() -> dict:
|
||
"""权限目录与数据范围选项,供权限矩阵渲染。"""
|
||
groups = [
|
||
{"key": key, "codes": [p.code for p in permissions.CATALOG if p.group == key]}
|
||
for key in permissions.GROUPS
|
||
]
|
||
return ok(
|
||
{
|
||
"groups": groups,
|
||
"scopes": list(permissions.SCOPES),
|
||
"all": permissions.ALL,
|
||
}
|
||
)
|
||
|
||
|
||
@router.get("/scope-units", dependencies=[Depends(MANAGE)])
|
||
def scope_units(db: Session = Depends(get_db)) -> dict:
|
||
"""自定义数据范围用的部门全集。
|
||
|
||
不按当前用户的数据范围裁剪:能配权限角色的人本来就要在整棵组织树上挑部门,
|
||
这里只给 id / 名称 / 路径,等同组织架构图上看得见的信息。已停用部门也返回并带上
|
||
状态,好让历史上勾过、如今停掉的部门在界面上露得出来、也改得掉。
|
||
"""
|
||
rows = db.execute(select(models.Unit).order_by(*org.unit_order_by())).scalars().all()
|
||
return ok(
|
||
[
|
||
{
|
||
"id": str(row.id),
|
||
"name": row.name,
|
||
"path": (row.path or row.name).rstrip("\\"),
|
||
"parent_id": str(row.parent_id) if row.parent_id else None,
|
||
"status": int(row.status),
|
||
}
|
||
for row in rows
|
||
]
|
||
)
|
||
|
||
|
||
@router.get("", dependencies=[Depends(MANAGE)])
|
||
def list_roles(db: Session = Depends(get_db)) -> dict:
|
||
rows = db.execute(
|
||
select(models.AuthRole).order_by(models.AuthRole.sort, models.AuthRole.name)
|
||
).scalars().all()
|
||
names = _unit_names(db, list(rows))
|
||
members = _members_map(db, [row.id for row in rows])
|
||
return ok([serializers.auth_role(row, members.get(row.id, []), names) for row in rows])
|
||
|
||
|
||
@router.post("", dependencies=[Depends(MANAGE)])
|
||
def save_role(body: schemas.AuthRoleBody, db: Session = Depends(get_db)) -> dict:
|
||
name = body.name.strip()
|
||
if not name:
|
||
raise bad_request("请输入角色名称")
|
||
_validate_codes(body.permissions)
|
||
scope = permissions.clean_scope(body.data_scope)
|
||
unit_ids = _clean_units(db, body)
|
||
duplicate = db.execute(
|
||
select(models.AuthRole).where(models.AuthRole.name == name)
|
||
).scalar_one_or_none()
|
||
if duplicate is not None:
|
||
raise bad_request("角色名称已存在")
|
||
role = models.AuthRole(
|
||
name=name,
|
||
description=body.description,
|
||
permissions=permissions.clean_codes(body.permissions),
|
||
data_scope=scope,
|
||
data_unit_ids=unit_ids,
|
||
data_unit_children=bool(body.data_unit_children),
|
||
data_include_self=bool(body.data_include_self),
|
||
enabled=body.enabled,
|
||
sort=body.sort,
|
||
)
|
||
db.add(role)
|
||
db.flush()
|
||
payload = serializers.auth_role(role, [], _unit_names(db, [role]))
|
||
db.commit()
|
||
return ok(payload)
|
||
|
||
|
||
@router.put("/{role_id}", dependencies=[Depends(MANAGE)])
|
||
def update_role(
|
||
role_id: str, body: schemas.AuthRoleBody, db: Session = Depends(get_db)
|
||
) -> dict:
|
||
role = _get(db, role_id)
|
||
name = body.name.strip()
|
||
duplicate = db.execute(
|
||
select(models.AuthRole).where(models.AuthRole.name == name, models.AuthRole.id != role_id)
|
||
).scalar_one_or_none()
|
||
if duplicate is not None:
|
||
raise bad_request("角色名称已存在")
|
||
if role.builtin and permissions.ALL in (role.permissions or []) and name != role.name:
|
||
raise bad_request("内置超级管理员角色不可改名")
|
||
_validate_codes(body.permissions)
|
||
scope = permissions.clean_scope(body.data_scope)
|
||
unit_ids = _clean_units(db, body)
|
||
if role.builtin and permissions.ALL in (role.permissions or []) and scope != permissions.SCOPE_ALL:
|
||
raise bad_request("内置超级管理员角色必须保持全部数据")
|
||
role.name = name
|
||
role.description = body.description
|
||
role.permissions = permissions.clean_codes(body.permissions)
|
||
role.data_scope = scope
|
||
role.data_unit_ids = unit_ids
|
||
role.data_unit_children = bool(body.data_unit_children)
|
||
role.data_include_self = bool(body.data_include_self)
|
||
role.sort = body.sort
|
||
# 内置超级管理员始终可用且始终全量,防止把自己锁死在系统外。
|
||
if not role.builtin or permissions.ALL not in (role.permissions or []):
|
||
role.enabled = body.enabled
|
||
db.commit()
|
||
return ok(serializers.auth_role(role, _members(db, role_id), _unit_names(db, [role])))
|
||
|
||
|
||
@router.delete("/{role_id}", dependencies=[Depends(MANAGE)])
|
||
def delete_role(role_id: str, db: Session = Depends(get_db)) -> dict:
|
||
role = _get(db, role_id)
|
||
if role.builtin:
|
||
raise bad_request("内置角色不可删除")
|
||
db.execute(delete(models.PersonAuthRole).where(models.PersonAuthRole.role_id == role_id))
|
||
db.delete(role)
|
||
db.commit()
|
||
return ok({"success": True})
|
||
|
||
|
||
@router.put("/{role_id}/members", dependencies=[Depends(MANAGE)])
|
||
def set_members(
|
||
role_id: str,
|
||
body: schemas.AuthRoleMembersBody,
|
||
db: Session = Depends(get_db),
|
||
user: CurrentUser = Depends(MANAGE),
|
||
) -> dict:
|
||
role = _get(db, role_id)
|
||
wanted = [pid for pid in dict.fromkeys(body.person_ids) if pid]
|
||
wanted_ids = [pid for pid in (models.as_id(value) for value in wanted) if pid is not None]
|
||
if wanted and len(wanted_ids) != len(wanted):
|
||
raise bad_request("人员不存在")
|
||
if wanted_ids:
|
||
found = set(
|
||
db.execute(select(models.User.id).where(models.User.id.in_(wanted_ids))).scalars().all()
|
||
)
|
||
if set(wanted_ids) - found:
|
||
raise bad_request("人员不存在")
|
||
current = set(_members(db, role_id))
|
||
for person_id in current - set(wanted):
|
||
db.execute(
|
||
delete(models.PersonAuthRole).where(
|
||
models.PersonAuthRole.person_id == models.as_id(person_id),
|
||
models.PersonAuthRole.role_id == role_id,
|
||
)
|
||
)
|
||
for person_id in set(wanted) - current:
|
||
db.add(models.PersonAuthRole(person_id=models.as_id(person_id), role_id=role_id))
|
||
db.add(
|
||
models.OperationLog(
|
||
action="auth_role_members",
|
||
target=role.name,
|
||
detail=f"权限角色成员调整为 {len(wanted)} 人",
|
||
person=user.person_id,
|
||
person_name=user.person.display_name,
|
||
identity=user.ref,
|
||
)
|
||
)
|
||
db.commit()
|
||
return ok(serializers.auth_role(role, _members(db, role_id), _unit_names(db, [role])))
|
||
|
||
|
||
__all__ = ["router"]
|