完全移除模块级权限系统,迁移至接口级权限
后端: - 删除 StudyRolePermission 模型和 project_permissions API 文件 - 重写 project_permissions.py core,移除所有模块级权限函数 - 重写 permission_cache.py,移除模块级权限缓存逻辑 - 新增权限模板功能(PermissionTemplate 模型、API、服务层) - 新增 permission_templates 数据库迁移 - 迁移 8 个模块(attachments、audit_logs、dashboard、faqs、 faq_categories、fees_attachments、knowledge_notes、 material_equipments、overview、subject_histories、subject_pds) 至接口级权限检查 - 删除所有模块级权限相关测试文件,新增权限模板测试 前端: - 删除 ProjectPermissions.vue 和 ProjectPermissionsModule.vue - 重写 projectRoutePermissions.ts,改为基于接口级权限格式 - 更新 store/study.ts、router/index.ts、AuditLogs.vue、Projects.vue 中的权限 API 调用,从 fetchProjectRolePermissions 改为 fetchApiEndpointPermissions - 清理 types/api.ts 中的旧模块级权限类型定义 - 新增 PermissionTemplateSelector.vue 组件 - 更新权限管理页面,移除模块级权限 tab Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -677,6 +677,213 @@ API_ENDPOINT_PERMISSIONS = {
|
||||
"description": "更新项目里程碑",
|
||||
"default_roles": ["PM"],
|
||||
},
|
||||
# 附件管理
|
||||
"attachments:create": {
|
||||
"module": "attachments",
|
||||
"action": "write",
|
||||
"description": "创建附件",
|
||||
"default_roles": ["PM", "CRA", "PV"],
|
||||
},
|
||||
"attachments:read": {
|
||||
"module": "attachments",
|
||||
"action": "read",
|
||||
"description": "查询附件",
|
||||
"default_roles": ["PM", "CRA", "PV", "MEDICAL_REVIEW", "IMP", "QA"],
|
||||
},
|
||||
"attachments:update": {
|
||||
"module": "attachments",
|
||||
"action": "write",
|
||||
"description": "更新附件",
|
||||
"default_roles": ["PM", "CRA"],
|
||||
},
|
||||
"attachments:delete": {
|
||||
"module": "attachments",
|
||||
"action": "write",
|
||||
"description": "删除附件",
|
||||
"default_roles": ["PM", "CRA"],
|
||||
},
|
||||
# 费用附件管理
|
||||
"fees_attachments:create": {
|
||||
"module": "fees",
|
||||
"action": "write",
|
||||
"description": "创建费用附件",
|
||||
"default_roles": ["PM", "CRA"],
|
||||
},
|
||||
"fees_attachments:read": {
|
||||
"module": "fees",
|
||||
"action": "read",
|
||||
"description": "查询费用附件",
|
||||
"default_roles": ["PM", "CRA", "PV"],
|
||||
},
|
||||
"fees_attachments:delete": {
|
||||
"module": "fees",
|
||||
"action": "write",
|
||||
"description": "删除费用附件",
|
||||
"default_roles": ["PM", "CRA"],
|
||||
},
|
||||
# FAQ管理
|
||||
"faq:create": {
|
||||
"module": "faq",
|
||||
"action": "write",
|
||||
"description": "创建FAQ",
|
||||
"default_roles": ["PM"],
|
||||
},
|
||||
"faq:read": {
|
||||
"module": "faq",
|
||||
"action": "read",
|
||||
"description": "查询FAQ",
|
||||
"default_roles": ["PM", "CRA", "PV", "MEDICAL_REVIEW", "IMP", "QA"],
|
||||
},
|
||||
"faq:update": {
|
||||
"module": "faq",
|
||||
"action": "write",
|
||||
"description": "更新FAQ",
|
||||
"default_roles": ["PM"],
|
||||
},
|
||||
"faq:delete": {
|
||||
"module": "faq",
|
||||
"action": "write",
|
||||
"description": "删除FAQ",
|
||||
"default_roles": ["PM"],
|
||||
},
|
||||
# FAQ分类管理
|
||||
"faq_category:create": {
|
||||
"module": "faq",
|
||||
"action": "write",
|
||||
"description": "创建FAQ分类",
|
||||
"default_roles": ["PM"],
|
||||
},
|
||||
"faq_category:read": {
|
||||
"module": "faq",
|
||||
"action": "read",
|
||||
"description": "查询FAQ分类",
|
||||
"default_roles": ["PM", "CRA", "PV", "MEDICAL_REVIEW", "IMP", "QA"],
|
||||
},
|
||||
"faq_category:update": {
|
||||
"module": "faq",
|
||||
"action": "write",
|
||||
"description": "更新FAQ分类",
|
||||
"default_roles": ["PM"],
|
||||
},
|
||||
"faq_category:delete": {
|
||||
"module": "faq",
|
||||
"action": "write",
|
||||
"description": "删除FAQ分类",
|
||||
"default_roles": ["PM"],
|
||||
},
|
||||
# FAQ回复管理
|
||||
"faq_reply:create": {
|
||||
"module": "faq",
|
||||
"action": "write",
|
||||
"description": "创建FAQ回复",
|
||||
"default_roles": ["PM", "CRA", "PV", "MEDICAL_REVIEW"],
|
||||
},
|
||||
"faq_reply:delete": {
|
||||
"module": "faq",
|
||||
"action": "write",
|
||||
"description": "删除FAQ回复",
|
||||
"default_roles": ["PM"],
|
||||
},
|
||||
# 仪表板管理
|
||||
"dashboard:read": {
|
||||
"module": "dashboard",
|
||||
"action": "read",
|
||||
"description": "查询仪表板",
|
||||
"default_roles": ["PM", "CRA", "PV", "MEDICAL_REVIEW", "IMP", "QA"],
|
||||
"prerequisite_permissions": ["sites:read", "subjects:read"],
|
||||
},
|
||||
# 参与者历史管理
|
||||
"subject_histories:create": {
|
||||
"module": "subject_histories",
|
||||
"action": "write",
|
||||
"description": "创建参与者历史",
|
||||
"default_roles": ["PM", "CRA"],
|
||||
"prerequisite_permissions": ["subjects:read"],
|
||||
},
|
||||
"subject_histories:list": {
|
||||
"module": "subject_histories",
|
||||
"action": "read",
|
||||
"description": "查询参与者历史列表",
|
||||
"default_roles": ["PM", "CRA", "PV", "MEDICAL_REVIEW", "IMP", "QA"],
|
||||
"prerequisite_permissions": [],
|
||||
},
|
||||
"subject_histories:read": {
|
||||
"module": "subject_histories",
|
||||
"action": "read",
|
||||
"description": "查询参与者历史详情",
|
||||
"default_roles": ["PM", "CRA", "PV", "MEDICAL_REVIEW", "IMP", "QA"],
|
||||
"prerequisite_permissions": [],
|
||||
},
|
||||
"subject_histories:update": {
|
||||
"module": "subject_histories",
|
||||
"action": "write",
|
||||
"description": "更新参与者历史",
|
||||
"default_roles": ["PM", "CRA"],
|
||||
"prerequisite_permissions": ["subjects:read"],
|
||||
},
|
||||
"subject_histories:delete": {
|
||||
"module": "subject_histories",
|
||||
"action": "write",
|
||||
"description": "删除参与者历史",
|
||||
"default_roles": ["PM"],
|
||||
"prerequisite_permissions": ["subjects:read"],
|
||||
},
|
||||
# 物资设备管理
|
||||
"material_equipments:create": {
|
||||
"module": "material_equipments",
|
||||
"action": "write",
|
||||
"description": "创建物资设备",
|
||||
"default_roles": ["PM", "CRA"],
|
||||
},
|
||||
"material_equipments:list": {
|
||||
"module": "material_equipments",
|
||||
"action": "read",
|
||||
"description": "查询物资设备列表",
|
||||
"default_roles": ["PM", "CRA", "PV", "MEDICAL_REVIEW", "IMP", "QA"],
|
||||
},
|
||||
"material_equipments:read": {
|
||||
"module": "material_equipments",
|
||||
"action": "read",
|
||||
"description": "查询物资设备详情",
|
||||
"default_roles": ["PM", "CRA", "PV", "MEDICAL_REVIEW", "IMP", "QA"],
|
||||
},
|
||||
"material_equipments:update": {
|
||||
"module": "material_equipments",
|
||||
"action": "write",
|
||||
"description": "更新物资设备",
|
||||
"default_roles": ["PM", "CRA"],
|
||||
},
|
||||
"material_equipments:delete": {
|
||||
"module": "material_equipments",
|
||||
"action": "write",
|
||||
"description": "删除物资设备",
|
||||
"default_roles": ["PM"],
|
||||
},
|
||||
# 文档管理
|
||||
"documents:create": {
|
||||
"module": "documents",
|
||||
"action": "write",
|
||||
"description": "创建文档",
|
||||
"default_roles": ["PM", "CRA"],
|
||||
},
|
||||
"documents:read": {
|
||||
"module": "documents",
|
||||
"action": "read",
|
||||
"description": "查询文档",
|
||||
"default_roles": ["PM", "CRA", "PV", "MEDICAL_REVIEW", "IMP", "QA"],
|
||||
},
|
||||
"documents:update": {
|
||||
"module": "documents",
|
||||
"action": "write",
|
||||
"description": "更新文档",
|
||||
"default_roles": ["PM", "CRA"],
|
||||
},
|
||||
"documents:delete": {
|
||||
"module": "documents",
|
||||
"action": "write",
|
||||
"description": "删除文档",
|
||||
"default_roles": ["PM"],
|
||||
},
|
||||
}
|
||||
|
||||
# 向后兼容:业务操作名到接口级权限的映射
|
||||
@@ -842,6 +1049,38 @@ OPERATION_TO_ENDPOINTS: dict[str, dict[str, list[str]]] = {
|
||||
"knowledge_notes:delete",
|
||||
],
|
||||
},
|
||||
"subject_histories": {
|
||||
"read": [
|
||||
"subject_histories:list",
|
||||
"subject_histories:read",
|
||||
],
|
||||
"write": [
|
||||
"subject_histories:create",
|
||||
"subject_histories:update",
|
||||
"subject_histories:delete",
|
||||
],
|
||||
},
|
||||
"material_equipments": {
|
||||
"read": [
|
||||
"material_equipments:list",
|
||||
"material_equipments:read",
|
||||
],
|
||||
"write": [
|
||||
"material_equipments:create",
|
||||
"material_equipments:update",
|
||||
"material_equipments:delete",
|
||||
],
|
||||
},
|
||||
"documents": {
|
||||
"read": [
|
||||
"documents:read",
|
||||
],
|
||||
"write": [
|
||||
"documents:create",
|
||||
"documents:update",
|
||||
"documents:delete",
|
||||
],
|
||||
},
|
||||
"project_milestones": {
|
||||
"read": [
|
||||
"milestones:list",
|
||||
@@ -892,6 +1131,11 @@ OPERATION_PREREQUISITES: dict[str, list[str]] = {
|
||||
"subject_pds:create": ["subjects:read", "sites:read"],
|
||||
"subject_pds:update": ["subjects:read", "sites:read"],
|
||||
|
||||
# 参与者历史
|
||||
"subject_histories:create": ["subjects:read"],
|
||||
"subject_histories:update": ["subjects:read"],
|
||||
"subject_histories:delete": ["subjects:read"],
|
||||
|
||||
# 监查访视问题
|
||||
"monitoring_audit:create": ["sites:read"],
|
||||
"monitoring_audit:update": ["sites:read"],
|
||||
|
||||
@@ -10,7 +10,7 @@ from app.core.security import decode_token, oauth2_scheme
|
||||
from app.crud import user as user_crud
|
||||
from app.crud import member as member_crud
|
||||
from app.crud import site as site_crud
|
||||
from app.core.project_permissions import role_has_project_permission, role_has_api_permission, get_missing_prerequisites
|
||||
from app.core.project_permissions import role_has_api_permission, get_missing_prerequisites
|
||||
from app.db.session import SessionLocal
|
||||
from app.schemas.user import TokenPayload
|
||||
|
||||
@@ -119,33 +119,6 @@ def require_study_roles(roles: Iterable[str], *, allow_system_admin: bool = True
|
||||
return dependency
|
||||
|
||||
|
||||
def require_study_permission(module: str, action: str, *, allow_system_admin: bool = True):
|
||||
async def dependency(
|
||||
study_id: uuid.UUID,
|
||||
current_user=Depends(get_current_user),
|
||||
db: AsyncSession = Depends(get_db_session),
|
||||
):
|
||||
role_value = current_user.role.value if hasattr(current_user.role, "value") else current_user.role
|
||||
if allow_system_admin and role_value == "ADMIN":
|
||||
return current_user
|
||||
membership = await member_crud.get_member(db, study_id, current_user.id)
|
||||
if not membership or not membership.is_active:
|
||||
raise AppException(
|
||||
code="FORBIDDEN",
|
||||
message="不是该项目成员",
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
)
|
||||
allowed = await role_has_project_permission(db, study_id, membership.role_in_study, module, action)
|
||||
if not allowed:
|
||||
raise AppException(
|
||||
code="FORBIDDEN",
|
||||
message="项目权限不足",
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
)
|
||||
return current_user
|
||||
|
||||
return dependency
|
||||
|
||||
|
||||
def require_api_permission(endpoint_key: str, *, allow_system_admin: bool = True, check_prerequisites: bool = True):
|
||||
"""基于接口的权限检查(包含前置权限检查)
|
||||
|
||||
@@ -1,8 +1,4 @@
|
||||
"""权限缓存管理器
|
||||
|
||||
实现权限矩阵和成员身份的缓存,以提高权限检查性能。
|
||||
采用内存缓存 + TTL 的方式,避免权限检查的 N+1 查询问题。
|
||||
"""
|
||||
"""权限缓存管理器"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -14,71 +10,22 @@ from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
|
||||
class PermissionCache:
|
||||
"""权限缓存管理器
|
||||
|
||||
使用内存缓存存储权限矩阵和成员身份信息,减少数据库查询。
|
||||
每个缓存项都有 TTL(生存时间),过期后自动失效。
|
||||
"""
|
||||
"""权限缓存管理器"""
|
||||
|
||||
def __init__(self, default_ttl: int = 300):
|
||||
"""初始化缓存管理器
|
||||
|
||||
Args:
|
||||
default_ttl: 默认缓存生存时间(秒),默认5分钟
|
||||
"""
|
||||
self.default_ttl = default_ttl
|
||||
self._project_permissions_cache: dict[str, tuple[Any, float]] = {}
|
||||
self._member_role_cache: dict[str, tuple[str | None, float]] = {}
|
||||
|
||||
def _is_expired(self, timestamp: float, ttl: int) -> bool:
|
||||
"""检查缓存是否已过期"""
|
||||
return time.time() - timestamp > ttl
|
||||
|
||||
def _make_project_cache_key(self, study_id: uuid.UUID) -> str:
|
||||
"""生成项目权限缓存键"""
|
||||
return f"project_permissions:{study_id}"
|
||||
|
||||
def _make_member_cache_key(self, study_id: uuid.UUID, user_id: uuid.UUID) -> str:
|
||||
"""生成成员角色缓存键"""
|
||||
return f"member_role:{study_id}:{user_id}"
|
||||
|
||||
async def get_project_role_permissions(
|
||||
self,
|
||||
db: AsyncSession,
|
||||
study_id: uuid.UUID,
|
||||
ttl: int | None = None,
|
||||
) -> dict[str, dict[str, dict[str, bool]]]:
|
||||
"""获取项目权限矩阵(带缓存)
|
||||
|
||||
Args:
|
||||
db: 数据库会话
|
||||
study_id: 项目ID
|
||||
ttl: 缓存生存时间(秒),默认使用 default_ttl
|
||||
|
||||
Returns:
|
||||
权限矩阵:{role: {module: {action: bool}}}
|
||||
"""
|
||||
from app.core.project_permissions import get_project_role_permissions as _get_project_role_permissions
|
||||
|
||||
if ttl is None:
|
||||
ttl = self.default_ttl
|
||||
|
||||
cache_key = self._make_project_cache_key(study_id)
|
||||
|
||||
# 检查缓存
|
||||
if cache_key in self._project_permissions_cache:
|
||||
cached_data, timestamp = self._project_permissions_cache[cache_key]
|
||||
if not self._is_expired(timestamp, ttl):
|
||||
return cached_data
|
||||
|
||||
# 缓存未命中,从数据库查询
|
||||
permissions = await _get_project_role_permissions(db, study_id)
|
||||
|
||||
# 存储到缓存
|
||||
self._project_permissions_cache[cache_key] = (permissions, time.time())
|
||||
|
||||
return permissions
|
||||
|
||||
async def get_member_role(
|
||||
self,
|
||||
db: AsyncSession,
|
||||
@@ -86,72 +33,34 @@ class PermissionCache:
|
||||
user_id: uuid.UUID,
|
||||
ttl: int | None = None,
|
||||
) -> str | None:
|
||||
"""获取成员角色(带缓存)
|
||||
|
||||
Args:
|
||||
db: 数据库会话
|
||||
study_id: 项目ID
|
||||
user_id: 用户ID
|
||||
ttl: 缓存生存时间(秒),默认使用 default_ttl
|
||||
|
||||
Returns:
|
||||
成员在项目中的角色,如果不是成员则返回 None
|
||||
"""
|
||||
from app.core.project_permissions import get_member_role as _get_member_role
|
||||
"""获取成员角色(带缓存)"""
|
||||
from app.crud import member as member_crud
|
||||
|
||||
if ttl is None:
|
||||
ttl = self.default_ttl
|
||||
|
||||
cache_key = self._make_member_cache_key(study_id, user_id)
|
||||
|
||||
# 检查缓存
|
||||
if cache_key in self._member_role_cache:
|
||||
cached_role, timestamp = self._member_role_cache[cache_key]
|
||||
if not self._is_expired(timestamp, ttl):
|
||||
return cached_role
|
||||
|
||||
# 缓存未命中,从数据库查询
|
||||
role = await _get_member_role(db, study_id, user_id)
|
||||
membership = await member_crud.get_member(db, study_id, user_id)
|
||||
role = membership.role_in_study if membership and membership.is_active else None
|
||||
|
||||
# 存储到缓存
|
||||
self._member_role_cache[cache_key] = (role, time.time())
|
||||
|
||||
return role
|
||||
|
||||
def invalidate_project_permissions(self, study_id: uuid.UUID) -> None:
|
||||
"""失效项目权限缓存
|
||||
|
||||
当项目权限被修改时调用此方法,清除相关的缓存。
|
||||
|
||||
Args:
|
||||
study_id: 项目ID
|
||||
"""
|
||||
cache_key = self._make_project_cache_key(study_id)
|
||||
if cache_key in self._project_permissions_cache:
|
||||
del self._project_permissions_cache[cache_key]
|
||||
self._project_permissions_cache.pop(cache_key, None)
|
||||
|
||||
def invalidate_member_role(self, study_id: uuid.UUID, user_id: uuid.UUID) -> None:
|
||||
"""失效成员角色缓存
|
||||
|
||||
当成员角色被修改时调用此方法,清除相关的缓存。
|
||||
|
||||
Args:
|
||||
study_id: 项目ID
|
||||
user_id: 用户ID
|
||||
"""
|
||||
cache_key = self._make_member_cache_key(study_id, user_id)
|
||||
if cache_key in self._member_role_cache:
|
||||
del self._member_role_cache[cache_key]
|
||||
self._member_role_cache.pop(cache_key, None)
|
||||
|
||||
def invalidate_all_member_roles(self, study_id: uuid.UUID) -> None:
|
||||
"""失效项目中所有成员的角色缓存
|
||||
|
||||
当项目权限矩阵被修改时调用此方法,清除项目中所有成员的缓存。
|
||||
|
||||
Args:
|
||||
study_id: 项目ID
|
||||
"""
|
||||
# 清除所有包含该项目ID的成员角色缓存
|
||||
keys_to_delete = [
|
||||
key for key in self._member_role_cache.keys()
|
||||
if key.startswith(f"member_role:{study_id}:")
|
||||
@@ -160,23 +69,10 @@ class PermissionCache:
|
||||
del self._member_role_cache[key]
|
||||
|
||||
def clear_all(self) -> None:
|
||||
"""清除所有缓存
|
||||
|
||||
用于测试或系统重启时清除所有缓存。
|
||||
"""
|
||||
self._project_permissions_cache.clear()
|
||||
self._member_role_cache.clear()
|
||||
|
||||
def get_cache_stats(self) -> dict[str, Any]:
|
||||
"""获取缓存统计信息
|
||||
|
||||
Returns:
|
||||
缓存统计信息:{
|
||||
'project_permissions_count': 项目权限缓存数,
|
||||
'member_role_count': 成员角色缓存数,
|
||||
'total_count': 总缓存数,
|
||||
}
|
||||
"""
|
||||
return {
|
||||
"project_permissions_count": len(self._project_permissions_cache),
|
||||
"member_role_count": len(self._member_role_cache),
|
||||
@@ -184,12 +80,10 @@ class PermissionCache:
|
||||
}
|
||||
|
||||
|
||||
# 全局缓存实例
|
||||
_permission_cache: PermissionCache | None = None
|
||||
|
||||
|
||||
def get_permission_cache() -> PermissionCache:
|
||||
"""获取全局权限缓存实例"""
|
||||
global _permission_cache
|
||||
if _permission_cache is None:
|
||||
_permission_cache = PermissionCache()
|
||||
@@ -197,6 +91,5 @@ def get_permission_cache() -> PermissionCache:
|
||||
|
||||
|
||||
def set_permission_cache(cache: PermissionCache) -> None:
|
||||
"""设置全局权限缓存实例(用于测试)"""
|
||||
global _permission_cache
|
||||
_permission_cache = cache
|
||||
|
||||
@@ -1,265 +1,14 @@
|
||||
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.api_permissions import API_ENDPOINT_PERMISSIONS, 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,
|
||||
@@ -268,17 +17,10 @@ async def role_has_api_permission(
|
||||
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,
|
||||
@@ -287,22 +29,12 @@ async def role_has_api_permission(
|
||||
)
|
||||
)
|
||||
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:
|
||||
if perm is None:
|
||||
return False
|
||||
|
||||
if not perm.allowed:
|
||||
return False
|
||||
|
||||
# 3. 检查前置权限
|
||||
if check_prerequisites:
|
||||
prerequisites = OPERATION_PREREQUISITES.get(endpoint_key, [])
|
||||
for prereq_endpoint in prerequisites:
|
||||
@@ -352,17 +84,14 @@ async def get_api_endpoint_permissions(
|
||||
)
|
||||
rows = result.scalars().all()
|
||||
|
||||
# 初始化矩阵,包含所有角色和端点的默认权限
|
||||
roles = ["PM", "CRA", "PV", "MEDICAL_REVIEW", "IMP", "QA"]
|
||||
matrix: dict[str, dict[str, dict[str, bool]]] = {}
|
||||
for role in PROJECT_PERMISSION_ROLES:
|
||||
if role == "ADMIN":
|
||||
continue
|
||||
for role in roles:
|
||||
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] = {}
|
||||
@@ -376,21 +105,13 @@ async def replace_api_endpoint_permissions(
|
||||
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
|
||||
@@ -408,7 +129,6 @@ async def replace_api_endpoint_permissions(
|
||||
|
||||
await db.commit()
|
||||
|
||||
# 失效缓存
|
||||
cache = get_permission_cache()
|
||||
cache.invalidate_project_permissions(study_id)
|
||||
cache.invalidate_all_member_roles(study_id)
|
||||
|
||||
Reference in New Issue
Block a user