3630b9000f
## 核心改进
- 完全迁移到接口级权限(68个API端点)
- 实现前置权限检查机制,解决跨模块数据访问权限问题
- 添加权限管理API端点,支持前置权限查询
## 关键变更
1. 权限配置系统
- 添加OPERATION_PREREQUISITES映射表
- 所有操作配置前置权限依赖
2. 权限检查函数
- role_has_api_permission()支持前置权限检查
- get_missing_prerequisites()获取缺失权限列表
3. 权限管理API
- GET /api-permissions/operations - 获取所有操作及前置权限
- GET /api-permissions/operations/prerequisites - 获取前置权限依赖
- GET /api-permissions/{endpoint_key}/prerequisites - 检查缺失权限
4. API端点迁移
- 第1批:subjects, visits, aes, monitoring_visit_issues (23个)
- 第2批:members, sites, project_milestones (11个)
- 第3批:finance_contracts, fees_contracts, drug_shipments (15个)
- 第4批:startup endpoints (19个)
## 测试验证
- 单元测试:24个测试全部通过
- 集成测试:22个迁移端点测试通过
- 前置权限测试:12个测试全部通过
- 总计:46个测试全部通过
## 向后兼容性
- 模块级权限表保留用于历史数据
- 接口级权限未配置时自动回退到模块级权限
- 现有权限配置继续有效
Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com>
417 lines
16 KiB
Python
417 lines
16 KiB
Python
from __future__ import annotations
|
|
|
|
import json
|
|
import uuid
|
|
|
|
from sqlalchemy import delete, select
|
|
from sqlalchemy.ext.asyncio import AsyncSession
|
|
|
|
from app.models.study_role_permission import StudyRolePermission
|
|
from app.models.api_endpoint_permission import ApiEndpointPermission
|
|
from app.core.api_permissions import API_ENDPOINT_PERMISSIONS, OPERATION_TO_ENDPOINTS, OPERATION_PREREQUISITES
|
|
from app.core.permission_cache import get_permission_cache
|
|
|
|
PROJECT_PERMISSION_ROLES = ("ADMIN", "PM", "CRA", "PV", "MEDICAL_REVIEW", "IMP", "QA")
|
|
|
|
PROJECT_PERMISSION_MODULES = (
|
|
{"key": "project_members", "label": "项目成员", "description": "维护项目账号、成员角色与启停状态"},
|
|
{"key": "sites", "label": "中心管理", "description": "维护中心资料与 CRA 绑定"},
|
|
{"key": "audit_export", "label": "审计日志导出", "description": "导出项目审计日志"},
|
|
{"key": "project_overview", "label": "项目总览", "description": "查看项目整体进度与中心概览", "writable": False},
|
|
{"key": "project_milestones", "label": "项目里程碑", "description": "维护项目级里程碑"},
|
|
{"key": "fees", "label": "合同费用管理", "description": "维护合同、费用与付款"},
|
|
{"key": "materials", "label": "物资管理", "description": "维护药品出入库与物资设备"},
|
|
{"key": "file_versions", "label": "文件版本管理", "description": "维护文件版本、分发与确认"},
|
|
{"key": "startup_ethics", "label": "立项与伦理", "description": "维护立项、可行性与伦理资料"},
|
|
{"key": "startup_auth", "label": "启动与授权", "description": "维护启动会、培训与授权"},
|
|
{"key": "subjects", "label": "参与者管理", "description": "维护参与者、访视与 PD"},
|
|
{"key": "risk_issues", "label": "风险问题", "description": "维护 SAE、PD 与监查问题"},
|
|
{"key": "monitoring_audit", "label": "监查稽查", "description": "维护监查稽查记录"},
|
|
{"key": "etmf", "label": "eTMF", "description": "维护 eTMF 文件"},
|
|
{"key": "faq", "label": "FAQ", "description": "维护项目 FAQ 分类、问题与回复"},
|
|
{"key": "shared_library", "label": "共享库", "description": "维护注意事项、支持性文件与说明文件"},
|
|
)
|
|
MANAGEMENT_BACKEND_PERMISSION_MODULES = {"project_members", "sites", "audit_export"}
|
|
READ_ONLY_PERMISSION_MODULES = {
|
|
module["key"]
|
|
for module in PROJECT_PERMISSION_MODULES
|
|
if module.get("writable") is False
|
|
}
|
|
|
|
DEFAULT_PROJECT_ROLE_PERMISSIONS: dict[str, dict[str, dict[str, bool]]] = {
|
|
"ADMIN": {
|
|
module["key"]: {"read": True, "write": module["key"] not in READ_ONLY_PERMISSION_MODULES}
|
|
for module in PROJECT_PERMISSION_MODULES
|
|
},
|
|
"PM": {
|
|
"project_overview": {"read": True, "write": False},
|
|
"project_milestones": {"read": True, "write": True},
|
|
"fees": {"read": True, "write": True},
|
|
"materials": {"read": True, "write": True},
|
|
"file_versions": {"read": True, "write": True},
|
|
"startup_ethics": {"read": True, "write": True},
|
|
"startup_auth": {"read": True, "write": True},
|
|
"subjects": {"read": True, "write": True},
|
|
"risk_issues": {"read": True, "write": True},
|
|
"monitoring_audit": {"read": True, "write": True},
|
|
"etmf": {"read": True, "write": True},
|
|
"faq": {"read": True, "write": True},
|
|
"shared_library": {"read": True, "write": True},
|
|
"project_members": {"read": True, "write": True},
|
|
"sites": {"read": True, "write": True},
|
|
"audit_export": {"read": True, "write": False},
|
|
},
|
|
"CRA": {
|
|
"project_overview": {"read": True, "write": False},
|
|
"project_milestones": {"read": True, "write": True},
|
|
"fees": {"read": True, "write": True},
|
|
"materials": {"read": True, "write": True},
|
|
"file_versions": {"read": True, "write": True},
|
|
"startup_ethics": {"read": True, "write": True},
|
|
"startup_auth": {"read": True, "write": True},
|
|
"subjects": {"read": True, "write": True},
|
|
"risk_issues": {"read": True, "write": True},
|
|
"monitoring_audit": {"read": True, "write": True},
|
|
"etmf": {"read": True, "write": True},
|
|
"faq": {"read": True, "write": True},
|
|
"shared_library": {"read": True, "write": True},
|
|
"project_members": {"read": False, "write": False},
|
|
"sites": {"read": False, "write": False},
|
|
"audit_export": {"read": True, "write": False},
|
|
},
|
|
"PV": {
|
|
"project_overview": {"read": True, "write": False},
|
|
"project_milestones": {"read": True, "write": False},
|
|
"fees": {"read": True, "write": False},
|
|
"materials": {"read": True, "write": False},
|
|
"file_versions": {"read": True, "write": False},
|
|
"startup_ethics": {"read": True, "write": False},
|
|
"startup_auth": {"read": True, "write": False},
|
|
"subjects": {"read": True, "write": False},
|
|
"risk_issues": {"read": True, "write": True},
|
|
"monitoring_audit": {"read": True, "write": True},
|
|
"etmf": {"read": True, "write": False},
|
|
"faq": {"read": True, "write": True},
|
|
"shared_library": {"read": True, "write": True},
|
|
"project_members": {"read": False, "write": False},
|
|
"sites": {"read": False, "write": False},
|
|
"audit_export": {"read": False, "write": False},
|
|
},
|
|
"MEDICAL_REVIEW": {
|
|
"project_overview": {"read": True, "write": False},
|
|
"project_milestones": {"read": False, "write": False},
|
|
"fees": {"read": False, "write": False},
|
|
"materials": {"read": False, "write": False},
|
|
"file_versions": {"read": False, "write": False},
|
|
"startup_ethics": {"read": False, "write": False},
|
|
"startup_auth": {"read": False, "write": False},
|
|
"subjects": {"read": True, "write": False},
|
|
"risk_issues": {"read": True, "write": True},
|
|
"monitoring_audit": {"read": True, "write": False},
|
|
"etmf": {"read": False, "write": False},
|
|
"faq": {"read": True, "write": True},
|
|
"shared_library": {"read": True, "write": True},
|
|
"project_members": {"read": False, "write": False},
|
|
"sites": {"read": False, "write": False},
|
|
"audit_export": {"read": False, "write": False},
|
|
},
|
|
"IMP": {
|
|
"project_overview": {"read": True, "write": False},
|
|
"project_milestones": {"read": True, "write": False},
|
|
"fees": {"read": True, "write": False},
|
|
"materials": {"read": True, "write": True},
|
|
"file_versions": {"read": True, "write": True},
|
|
"startup_ethics": {"read": True, "write": False},
|
|
"startup_auth": {"read": True, "write": True},
|
|
"subjects": {"read": True, "write": False},
|
|
"risk_issues": {"read": True, "write": False},
|
|
"monitoring_audit": {"read": True, "write": False},
|
|
"etmf": {"read": True, "write": False},
|
|
"faq": {"read": True, "write": True},
|
|
"shared_library": {"read": True, "write": True},
|
|
"project_members": {"read": False, "write": False},
|
|
"sites": {"read": False, "write": False},
|
|
"audit_export": {"read": False, "write": False},
|
|
},
|
|
"QA": {
|
|
"project_overview": {"read": True, "write": False},
|
|
"project_milestones": {"read": True, "write": False},
|
|
"fees": {"read": True, "write": False},
|
|
"materials": {"read": True, "write": False},
|
|
"file_versions": {"read": True, "write": False},
|
|
"startup_ethics": {"read": True, "write": False},
|
|
"startup_auth": {"read": True, "write": False},
|
|
"subjects": {"read": True, "write": False},
|
|
"risk_issues": {"read": True, "write": False},
|
|
"monitoring_audit": {"read": True, "write": True},
|
|
"etmf": {"read": True, "write": False},
|
|
"faq": {"read": True, "write": False},
|
|
"shared_library": {"read": True, "write": True},
|
|
"project_members": {"read": False, "write": False},
|
|
"sites": {"read": False, "write": False},
|
|
"audit_export": {"read": False, "write": False},
|
|
},
|
|
}
|
|
|
|
|
|
def _empty_action_state() -> dict[str, bool]:
|
|
return {"read": False, "write": False}
|
|
|
|
|
|
def _normalize_action_state(value: dict | None, role: str) -> dict[str, bool]:
|
|
if role == "ADMIN":
|
|
return {"read": True, "write": True}
|
|
read = bool((value or {}).get("read", False))
|
|
write = bool((value or {}).get("write", False))
|
|
if write:
|
|
read = True
|
|
return {"read": read, "write": write}
|
|
|
|
|
|
def _normalize_module_action_state(value: dict | None, role: str, module: str) -> dict[str, bool]:
|
|
if role == "ADMIN":
|
|
return {"read": True, "write": module not in READ_ONLY_PERMISSION_MODULES}
|
|
if module in MANAGEMENT_BACKEND_PERMISSION_MODULES and role != "PM":
|
|
return _empty_action_state()
|
|
if module in READ_ONLY_PERMISSION_MODULES:
|
|
return {"read": bool((value or {}).get("read", False) or (value or {}).get("write", False)), "write": False}
|
|
return _normalize_action_state(value, role)
|
|
|
|
|
|
def normalize_permission_matrix(matrix: dict | None = None) -> dict[str, dict[str, dict[str, bool]]]:
|
|
normalized: dict[str, dict[str, dict[str, bool]]] = {}
|
|
matrix = matrix or {}
|
|
for role in PROJECT_PERMISSION_ROLES:
|
|
normalized[role] = {}
|
|
role_matrix = matrix.get(role) or DEFAULT_PROJECT_ROLE_PERMISSIONS.get(role, {})
|
|
for module in PROJECT_PERMISSION_MODULES:
|
|
module_key = module["key"]
|
|
normalized[role][module_key] = _normalize_module_action_state(
|
|
role_matrix.get(module_key, _empty_action_state()),
|
|
role,
|
|
module_key,
|
|
)
|
|
return normalized
|
|
|
|
|
|
async def get_project_role_permissions(db: AsyncSession, study_id: uuid.UUID) -> dict[str, dict[str, dict[str, bool]]]:
|
|
result = await db.execute(select(StudyRolePermission).where(StudyRolePermission.study_id == study_id))
|
|
rows = result.scalars().all()
|
|
if not rows:
|
|
return normalize_permission_matrix(DEFAULT_PROJECT_ROLE_PERMISSIONS)
|
|
matrix = normalize_permission_matrix(DEFAULT_PROJECT_ROLE_PERMISSIONS)
|
|
for row in rows:
|
|
if row.role not in PROJECT_PERMISSION_ROLES:
|
|
continue
|
|
if row.module not in matrix[row.role]:
|
|
continue
|
|
matrix[row.role][row.module] = _normalize_module_action_state(
|
|
{"read": row.can_read, "write": row.can_write},
|
|
row.role,
|
|
row.module,
|
|
)
|
|
return matrix
|
|
|
|
|
|
async def replace_project_role_permissions(
|
|
db: AsyncSession,
|
|
study_id: uuid.UUID,
|
|
payload: dict[str, dict[str, dict[str, bool]]],
|
|
) -> dict[str, dict[str, dict[str, bool]]]:
|
|
matrix = normalize_permission_matrix(payload)
|
|
await db.execute(delete(StudyRolePermission).where(StudyRolePermission.study_id == study_id))
|
|
for role, role_matrix in matrix.items():
|
|
if role == "ADMIN":
|
|
continue
|
|
for module, actions in role_matrix.items():
|
|
db.add(
|
|
StudyRolePermission(
|
|
study_id=study_id,
|
|
role=role,
|
|
module=module,
|
|
can_read=actions["read"],
|
|
can_write=actions["write"],
|
|
)
|
|
)
|
|
await db.commit()
|
|
|
|
# 失效缓存
|
|
cache = get_permission_cache()
|
|
cache.invalidate_project_permissions(study_id)
|
|
cache.invalidate_all_member_roles(study_id)
|
|
|
|
return matrix
|
|
|
|
|
|
async def role_has_project_permission(
|
|
db: AsyncSession,
|
|
study_id: uuid.UUID,
|
|
role: str | None,
|
|
module: str,
|
|
action: str,
|
|
) -> bool:
|
|
if role == "ADMIN":
|
|
return True
|
|
matrix = await get_project_role_permissions(db, study_id)
|
|
actions = matrix.get(role or "", {}).get(module)
|
|
if not actions:
|
|
return False
|
|
if action == "write":
|
|
return bool(actions["write"])
|
|
return bool(actions["read"])
|
|
|
|
|
|
async def role_has_api_permission(
|
|
db: AsyncSession,
|
|
study_id: uuid.UUID,
|
|
role: str | None,
|
|
endpoint_key: str,
|
|
check_prerequisites: bool = True,
|
|
) -> bool:
|
|
"""检查角色是否有权访问特定接口
|
|
|
|
权限检查优先级:
|
|
1. 接口级权限(如果已配置)
|
|
2. 模块级权限(向后兼容)
|
|
3. 前置权限检查(如果启用)
|
|
"""
|
|
if role == "ADMIN":
|
|
return True
|
|
|
|
# 1. 先查询接口级权限
|
|
result = await db.execute(
|
|
select(ApiEndpointPermission).where(
|
|
ApiEndpointPermission.study_id == study_id,
|
|
ApiEndpointPermission.role == role,
|
|
ApiEndpointPermission.endpoint_key == endpoint_key,
|
|
)
|
|
)
|
|
perm = result.scalar_one_or_none()
|
|
if perm is not None:
|
|
has_main_permission = perm.allowed
|
|
else:
|
|
# 2. 如果没有接口级权限,回退到模块级权限(向后兼容)
|
|
endpoint_config = API_ENDPOINT_PERMISSIONS.get(endpoint_key)
|
|
if not endpoint_config:
|
|
return False
|
|
|
|
module = endpoint_config["module"]
|
|
action = endpoint_config["action"]
|
|
has_main_permission = await role_has_project_permission(db, study_id, role, module, action)
|
|
|
|
if not has_main_permission:
|
|
return False
|
|
|
|
# 3. 检查前置权限
|
|
if check_prerequisites:
|
|
prerequisites = OPERATION_PREREQUISITES.get(endpoint_key, [])
|
|
for prereq_endpoint in prerequisites:
|
|
has_prereq = await role_has_api_permission(
|
|
db, study_id, role, prereq_endpoint, check_prerequisites=False
|
|
)
|
|
if not has_prereq:
|
|
return False
|
|
|
|
return True
|
|
|
|
|
|
async def get_missing_prerequisites(
|
|
db: AsyncSession,
|
|
study_id: uuid.UUID,
|
|
role: str | None,
|
|
endpoint_key: str,
|
|
) -> list[str]:
|
|
"""获取缺失的前置权限列表"""
|
|
if role == "ADMIN":
|
|
return []
|
|
|
|
missing = []
|
|
prerequisites = OPERATION_PREREQUISITES.get(endpoint_key, [])
|
|
for prereq_endpoint in prerequisites:
|
|
has_prereq = await role_has_api_permission(
|
|
db, study_id, role, prereq_endpoint, check_prerequisites=False
|
|
)
|
|
if not has_prereq:
|
|
missing.append(prereq_endpoint)
|
|
|
|
return missing
|
|
|
|
|
|
async def get_api_endpoint_permissions(
|
|
db: AsyncSession,
|
|
study_id: uuid.UUID,
|
|
) -> dict[str, dict[str, dict[str, bool]]]:
|
|
"""获取项目的接口级权限矩阵
|
|
|
|
返回格式: {role: {endpoint_key: {allowed: bool}}}
|
|
"""
|
|
result = await db.execute(
|
|
select(ApiEndpointPermission).where(
|
|
ApiEndpointPermission.study_id == study_id,
|
|
)
|
|
)
|
|
rows = result.scalars().all()
|
|
|
|
# 初始化矩阵,包含所有角色和端点的默认权限
|
|
matrix: dict[str, dict[str, dict[str, bool]]] = {}
|
|
for role in PROJECT_PERMISSION_ROLES:
|
|
if role == "ADMIN":
|
|
continue
|
|
matrix[role] = {}
|
|
for endpoint_key, config in API_ENDPOINT_PERMISSIONS.items():
|
|
default_allowed = role in config.get("default_roles", [])
|
|
matrix[role][endpoint_key] = {"allowed": default_allowed}
|
|
|
|
# 覆盖自定义权限
|
|
for row in rows:
|
|
if row.role not in matrix:
|
|
matrix[row.role] = {}
|
|
matrix[row.role][row.endpoint_key] = {"allowed": row.allowed}
|
|
|
|
return matrix
|
|
|
|
|
|
async def replace_api_endpoint_permissions(
|
|
db: AsyncSession,
|
|
study_id: uuid.UUID,
|
|
payload: dict[str, dict[str, bool]],
|
|
) -> dict[str, dict[str, dict[str, bool]]]:
|
|
"""替换项目的接口级权限矩阵
|
|
|
|
参数:
|
|
payload: {role: {endpoint_key: allowed}}
|
|
|
|
返回格式: {role: {endpoint_key: {allowed: bool}}}
|
|
"""
|
|
# 删除该项目的所有接口级权限
|
|
await db.execute(
|
|
delete(ApiEndpointPermission).where(
|
|
ApiEndpointPermission.study_id == study_id,
|
|
)
|
|
)
|
|
|
|
# 插入新的权限配置
|
|
for role, endpoints in payload.items():
|
|
if role == "ADMIN":
|
|
continue
|
|
for endpoint_key, allowed in endpoints.items():
|
|
if endpoint_key not in API_ENDPOINT_PERMISSIONS:
|
|
continue
|
|
db.add(
|
|
ApiEndpointPermission(
|
|
study_id=study_id,
|
|
role=role,
|
|
endpoint_key=endpoint_key,
|
|
allowed=allowed,
|
|
)
|
|
)
|
|
|
|
await db.commit()
|
|
|
|
# 失效缓存
|
|
cache = get_permission_cache()
|
|
cache.invalidate_project_permissions(study_id)
|
|
cache.invalidate_all_member_roles(study_id)
|
|
|
|
return await get_api_endpoint_permissions(db, study_id)
|