完全移除模块级权限系统,迁移至接口级权限
后端: - 删除 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:
@@ -20,6 +20,9 @@ from app.core.api_permissions import API_ENDPOINT_PERMISSIONS, PROJECT_PERMISSIO
|
||||
|
||||
router = APIRouter(prefix="/api-permissions", tags=["api-permissions"])
|
||||
|
||||
# 项目级路由(需要 study_id,挂载到 /studies/{study_id}/api-permissions)
|
||||
study_router = APIRouter(prefix="/api-permissions", tags=["api-permissions"])
|
||||
|
||||
|
||||
@router.get(
|
||||
"/operations",
|
||||
@@ -138,7 +141,7 @@ async def check_operation_prerequisites(
|
||||
}
|
||||
|
||||
|
||||
@router.get(
|
||||
@study_router.get(
|
||||
"",
|
||||
summary="获取项目的接口级权限矩阵",
|
||||
description="返回项目中各角色对API端点的权限配置",
|
||||
@@ -176,7 +179,7 @@ async def get_study_api_permissions(
|
||||
return result
|
||||
|
||||
|
||||
@router.put(
|
||||
@study_router.put(
|
||||
"",
|
||||
summary="更新项目的接口级权限矩阵",
|
||||
description="批量更新项目中各角色对API端点的权限配置",
|
||||
|
||||
@@ -8,8 +8,8 @@ from fastapi import APIRouter, Depends, File, HTTPException, UploadFile, status,
|
||||
from fastapi.responses import FileResponse
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.core.deps import get_current_user, get_db_session, get_study_member, require_study_not_locked
|
||||
from app.core.project_permissions import role_has_project_permission
|
||||
from app.core.deps import get_current_user, get_db_session, get_study_member, require_study_not_locked, require_api_permission
|
||||
from app.core.project_permissions import role_has_api_permission
|
||||
from app.crud import attachment as attachment_crud
|
||||
from app.crud import audit as audit_crud
|
||||
from app.crud import study as study_crud
|
||||
@@ -23,9 +23,6 @@ router = APIRouter()
|
||||
global_router = APIRouter()
|
||||
|
||||
UPLOAD_ROOT = Path(__file__).resolve().parent.parent.parent / "uploads"
|
||||
ATTACHMENT_PERMISSION_MODULE_BY_ENTITY = {
|
||||
"knowledge_note": "shared_library",
|
||||
}
|
||||
|
||||
|
||||
def _content_disposition(filename: str, disposition: str = "inline") -> str:
|
||||
@@ -41,39 +38,14 @@ async def _ensure_study_exists(db: AsyncSession, study_id: uuid.UUID):
|
||||
return study
|
||||
|
||||
|
||||
def _permission_module_for_entity(entity_type: str) -> str:
|
||||
return ATTACHMENT_PERMISSION_MODULE_BY_ENTITY.get(entity_type, "file_versions")
|
||||
|
||||
|
||||
async def _ensure_attachment_permission(
|
||||
db: AsyncSession,
|
||||
study_id: uuid.UUID,
|
||||
current_user,
|
||||
entity_type: str,
|
||||
action: str,
|
||||
) -> None:
|
||||
role_value = current_user.role.value if hasattr(current_user.role, "value") else current_user.role
|
||||
if role_value == "ADMIN":
|
||||
return
|
||||
membership = await member_crud.get_member(db, study_id, current_user.id)
|
||||
if not membership or not membership.is_active:
|
||||
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="不是项目成员")
|
||||
allowed = await role_has_project_permission(
|
||||
db,
|
||||
study_id,
|
||||
membership.role_in_study,
|
||||
_permission_module_for_entity(entity_type),
|
||||
action,
|
||||
)
|
||||
if not allowed:
|
||||
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="权限不足")
|
||||
|
||||
|
||||
@router.post(
|
||||
"/",
|
||||
response_model=AttachmentRead,
|
||||
status_code=status.HTTP_201_CREATED,
|
||||
dependencies=[Depends(require_study_not_locked())],
|
||||
dependencies=[
|
||||
Depends(require_api_permission("attachments:create")),
|
||||
Depends(require_study_not_locked())
|
||||
],
|
||||
)
|
||||
async def upload_attachment(
|
||||
study_id: uuid.UUID,
|
||||
@@ -84,7 +56,6 @@ async def upload_attachment(
|
||||
current_user=Depends(get_current_user),
|
||||
) -> AttachmentRead:
|
||||
await _ensure_study_exists(db, study_id)
|
||||
await _ensure_attachment_permission(db, study_id, current_user, entity_type, "write")
|
||||
dest_dir = UPLOAD_ROOT / f"study_{study_id}" / f"{entity_type}_{entity_id}"
|
||||
dest_dir.mkdir(parents=True, exist_ok=True)
|
||||
unique_name = f"{uuid.uuid4()}{Path(file.filename).suffix}"
|
||||
@@ -129,6 +100,7 @@ async def upload_attachment(
|
||||
@router.get(
|
||||
"/",
|
||||
response_model=list[AttachmentRead],
|
||||
dependencies=[Depends(require_api_permission("attachments:read"))],
|
||||
)
|
||||
async def list_attachments(
|
||||
study_id: uuid.UUID,
|
||||
@@ -138,7 +110,6 @@ async def list_attachments(
|
||||
current_user=Depends(get_current_user),
|
||||
) -> list[AttachmentRead]:
|
||||
await _ensure_study_exists(db, study_id)
|
||||
await _ensure_attachment_permission(db, study_id, current_user, entity_type, "read")
|
||||
attachments = await attachment_crud.list_attachments(db, study_id, entity_type, entity_id)
|
||||
user_ids = {a.uploaded_by for a in attachments if a.uploaded_by}
|
||||
users_map = await user_crud.get_users_by_ids(db, user_ids)
|
||||
@@ -161,6 +132,7 @@ async def list_attachments(
|
||||
|
||||
@router.get(
|
||||
"/{attachment_id}/download",
|
||||
dependencies=[Depends(require_api_permission("attachments:read"))],
|
||||
)
|
||||
async def download_attachment(
|
||||
study_id: uuid.UUID,
|
||||
@@ -171,7 +143,6 @@ async def download_attachment(
|
||||
current_user=Depends(get_current_user),
|
||||
) -> FileResponse:
|
||||
await _ensure_study_exists(db, study_id)
|
||||
await _ensure_attachment_permission(db, study_id, current_user, entity_type, "read")
|
||||
attachment = await attachment_crud.get_attachment(db, attachment_id)
|
||||
if not attachment or attachment.study_id != study_id or attachment.entity_id != entity_id or attachment.entity_type != entity_type:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="附件不存在")
|
||||
@@ -187,6 +158,7 @@ async def download_attachment(
|
||||
|
||||
@router.get(
|
||||
"/{attachment_id}/preview",
|
||||
dependencies=[Depends(require_api_permission("attachments:read"))],
|
||||
)
|
||||
async def preview_attachment(
|
||||
study_id: uuid.UUID,
|
||||
@@ -197,7 +169,6 @@ async def preview_attachment(
|
||||
current_user=Depends(get_current_user),
|
||||
) -> FileResponse:
|
||||
await _ensure_study_exists(db, study_id)
|
||||
await _ensure_attachment_permission(db, study_id, current_user, entity_type, "read")
|
||||
attachment = await attachment_crud.get_attachment(db, attachment_id)
|
||||
if not attachment or attachment.study_id != study_id or attachment.entity_id != entity_id or attachment.entity_type != entity_type:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="附件不存在")
|
||||
@@ -250,12 +221,12 @@ async def global_download_attachment(
|
||||
if user.role != "ADMIN":
|
||||
membership = await get_study_member(attachment.study_id, current_user=user, db=db)
|
||||
if user.role != "ADMIN":
|
||||
allowed = await role_has_project_permission(
|
||||
allowed = await role_has_api_permission(
|
||||
db,
|
||||
attachment.study_id,
|
||||
membership.role_in_study if membership else None,
|
||||
_permission_module_for_entity(attachment.entity_type),
|
||||
"read",
|
||||
"attachments:read",
|
||||
check_prerequisites=False,
|
||||
)
|
||||
if not allowed:
|
||||
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="权限不足")
|
||||
@@ -284,12 +255,12 @@ async def global_preview_attachment(
|
||||
await _ensure_study_exists(db, attachment.study_id)
|
||||
user, membership = await _authorize_global(request, db, attachment.study_id)
|
||||
if user.role != "ADMIN":
|
||||
allowed = await role_has_project_permission(
|
||||
allowed = await role_has_api_permission(
|
||||
db,
|
||||
attachment.study_id,
|
||||
membership.role_in_study if membership else None,
|
||||
_permission_module_for_entity(attachment.entity_type),
|
||||
"read",
|
||||
"attachments:read",
|
||||
check_prerequisites=False,
|
||||
)
|
||||
if not allowed:
|
||||
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="权限不足")
|
||||
@@ -318,12 +289,12 @@ async def global_delete_attachment(
|
||||
await _ensure_study_exists(db, attachment.study_id)
|
||||
user, membership = await _authorize_global(request, db, attachment.study_id)
|
||||
if user.role != "ADMIN":
|
||||
allowed = await role_has_project_permission(
|
||||
allowed = await role_has_api_permission(
|
||||
db,
|
||||
attachment.study_id,
|
||||
membership.role_in_study if membership else None,
|
||||
_permission_module_for_entity(attachment.entity_type),
|
||||
"write",
|
||||
"attachments:delete",
|
||||
check_prerequisites=False,
|
||||
)
|
||||
if not allowed:
|
||||
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="权限不足")
|
||||
@@ -350,7 +321,10 @@ async def global_delete_attachment(
|
||||
@router.delete(
|
||||
"/{attachment_id}",
|
||||
status_code=status.HTTP_204_NO_CONTENT,
|
||||
dependencies=[Depends(require_study_not_locked())],
|
||||
dependencies=[
|
||||
Depends(require_api_permission("attachments:delete")),
|
||||
Depends(require_study_not_locked())
|
||||
],
|
||||
)
|
||||
async def delete_attachment(
|
||||
study_id: uuid.UUID,
|
||||
@@ -361,7 +335,6 @@ async def delete_attachment(
|
||||
current_user=Depends(get_current_user),
|
||||
):
|
||||
await _ensure_study_exists(db, study_id)
|
||||
await _ensure_attachment_permission(db, study_id, current_user, entity_type, "write")
|
||||
attachment = await attachment_crud.get_attachment(db, attachment_id)
|
||||
if (
|
||||
not attachment
|
||||
|
||||
@@ -3,7 +3,7 @@ import uuid
|
||||
from fastapi import APIRouter, Depends, HTTPException, status
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.core.deps import get_current_user, get_db_session, require_roles, require_study_member, require_study_permission
|
||||
from app.core.deps import get_current_user, get_db_session, require_roles, require_study_member, require_api_permission
|
||||
from app.crud import audit as audit_crud
|
||||
from app.schemas.audit import AuditEventCreate, AuditLogRead
|
||||
|
||||
@@ -13,7 +13,7 @@ router = APIRouter()
|
||||
@router.get(
|
||||
"/",
|
||||
response_model=list[AuditLogRead],
|
||||
dependencies=[Depends(require_study_permission("audit_export", "read"))],
|
||||
dependencies=[Depends(require_api_permission("audit_logs:read"))],
|
||||
)
|
||||
async def list_audit_logs(
|
||||
study_id: uuid.UUID,
|
||||
|
||||
@@ -3,8 +3,8 @@ from fastapi import APIRouter, Depends
|
||||
from sqlalchemy import func, select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.core.deps import get_cra_site_scope, get_current_user, get_db_session, require_study_member
|
||||
from app.core.project_permissions import role_has_project_permission
|
||||
from app.core.deps import get_cra_site_scope, get_current_user, get_db_session, require_study_member, require_api_permission
|
||||
from app.core.project_permissions import role_has_api_permission
|
||||
from app.crud import member as member_crud
|
||||
from app.models.milestone import Milestone
|
||||
from app.schemas.progress import StudyProgressRead
|
||||
@@ -68,7 +68,10 @@ async def list_lost_visits(
|
||||
return items
|
||||
|
||||
|
||||
@router.get("/center-summary", response_model=list[CenterSummaryItem], dependencies=[Depends(require_study_member())])
|
||||
@router.get("/center-summary", response_model=list[CenterSummaryItem], dependencies=[
|
||||
Depends(require_study_member()),
|
||||
Depends(require_api_permission("dashboard:read"))
|
||||
])
|
||||
async def get_center_summary(
|
||||
study_id: uuid.UUID,
|
||||
db: AsyncSession = Depends(get_db_session),
|
||||
@@ -80,10 +83,6 @@ async def get_center_summary(
|
||||
membership = await member_crud.get_member(db, study_id, current_user.id)
|
||||
if not membership or not membership.is_active:
|
||||
return []
|
||||
can_read_sites = await role_has_project_permission(db, study_id, membership.role_in_study, "sites", "read")
|
||||
can_read_subjects = await role_has_project_permission(db, study_id, membership.role_in_study, "subjects", "read")
|
||||
if not (can_read_sites or can_read_subjects):
|
||||
return []
|
||||
cra_scope = await get_cra_site_scope(db, study_id, current_user)
|
||||
scope_ids = cra_scope[0] if cra_scope else None
|
||||
scope_id_strs = {str(cid) for cid in scope_ids} if scope_ids is not None else None
|
||||
|
||||
@@ -3,8 +3,8 @@ import uuid
|
||||
from fastapi import APIRouter, Depends, HTTPException, status
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.core.deps import get_current_user, get_db_session, require_study_not_locked
|
||||
from app.core.project_permissions import role_has_project_permission
|
||||
from app.core.deps import get_current_user, get_db_session, require_study_not_locked, require_api_permission
|
||||
from app.core.project_permissions import role_has_api_permission
|
||||
from app.crud import audit as audit_crud
|
||||
from app.crud import faq_category as category_crud
|
||||
from app.crud import faq_item as item_crud
|
||||
@@ -21,25 +21,16 @@ def _is_system_admin(current_user) -> bool:
|
||||
return role == "ADMIN"
|
||||
|
||||
|
||||
async def _require_category_permission(db: AsyncSession, study_id: uuid.UUID, current_user, action: str):
|
||||
if _is_system_admin(current_user):
|
||||
return None
|
||||
member = await member_crud.get_member(db, study_id, current_user.id)
|
||||
if not member or not member.is_active:
|
||||
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="不是该项目成员")
|
||||
allowed = await role_has_project_permission(db, study_id, member.role_in_study, "faq", action)
|
||||
if not allowed:
|
||||
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="权限不足")
|
||||
return member
|
||||
|
||||
|
||||
@router.post(
|
||||
"/",
|
||||
response_model=CategoryRead,
|
||||
status_code=status.HTTP_201_CREATED,
|
||||
summary="创建 FAQ 分类",
|
||||
description="创建项目内 FAQ 分类,权限由项目级权限矩阵控制。",
|
||||
dependencies=[Depends(require_study_not_locked())],
|
||||
dependencies=[
|
||||
Depends(require_api_permission("faq_category:create")),
|
||||
Depends(require_study_not_locked())
|
||||
],
|
||||
)
|
||||
async def create_category(
|
||||
payload: CategoryCreate,
|
||||
@@ -51,7 +42,6 @@ async def create_category(
|
||||
existing = await category_crud.get_category_by_name(db, payload.study_id, payload.name)
|
||||
if existing:
|
||||
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="分类名称已存在")
|
||||
await _require_category_permission(db, payload.study_id, current_user, "write")
|
||||
category = await category_crud.create_category(db, payload)
|
||||
await audit_crud.log_action(
|
||||
db,
|
||||
@@ -71,6 +61,7 @@ async def create_category(
|
||||
response_model=PaginatedResponse[CategoryRead],
|
||||
summary="FAQ 分类列表",
|
||||
description="返回全局及项目内 FAQ 分类列表,可按 study_id 过滤。",
|
||||
dependencies=[Depends(require_api_permission("faq_category:read"))],
|
||||
)
|
||||
async def list_categories(
|
||||
study_id: uuid.UUID | None = None,
|
||||
@@ -80,8 +71,6 @@ async def list_categories(
|
||||
) -> list[CategoryRead]:
|
||||
if not study_id:
|
||||
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="必须提供项目 ID")
|
||||
if study_id:
|
||||
await _require_category_permission(db, study_id, current_user, "read")
|
||||
categories = await category_crud.list_categories(db, study_id, include_global=False, is_active=is_active)
|
||||
return paginate([CategoryRead.model_validate(c) for c in categories], total=len(categories))
|
||||
|
||||
@@ -91,7 +80,10 @@ async def list_categories(
|
||||
response_model=CategoryRead,
|
||||
summary="更新 FAQ 分类",
|
||||
description="更新分类名称或启停状态,权限由项目级权限矩阵控制。",
|
||||
dependencies=[Depends(require_study_not_locked())],
|
||||
dependencies=[
|
||||
Depends(require_api_permission("faq_category:update")),
|
||||
Depends(require_study_not_locked())
|
||||
],
|
||||
)
|
||||
async def update_category(
|
||||
category_id: uuid.UUID,
|
||||
@@ -112,7 +104,6 @@ async def update_category(
|
||||
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="分类名称已存在")
|
||||
if not target_study_id:
|
||||
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="必须提供项目 ID")
|
||||
await _require_category_permission(db, target_study_id, current_user, "write")
|
||||
updated = await category_crud.update_category(db, category, payload)
|
||||
await audit_crud.log_action(
|
||||
db,
|
||||
@@ -132,7 +123,10 @@ async def update_category(
|
||||
status_code=status.HTTP_204_NO_CONTENT,
|
||||
summary="删除 FAQ 分类",
|
||||
description="删除分类,权限由项目级权限矩阵控制;分类下存在 FAQ 时不可删除。",
|
||||
dependencies=[Depends(require_study_not_locked())],
|
||||
dependencies=[
|
||||
Depends(require_api_permission("faq_category:delete")),
|
||||
Depends(require_study_not_locked())
|
||||
],
|
||||
)
|
||||
async def delete_category(
|
||||
category_id: uuid.UUID,
|
||||
@@ -144,7 +138,6 @@ async def delete_category(
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="分类不存在")
|
||||
if not category.study_id:
|
||||
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="必须提供项目 ID")
|
||||
await _require_category_permission(db, category.study_id, current_user, "write")
|
||||
item_count = await item_crud.count_items_by_category(db, category_id)
|
||||
if item_count > 0:
|
||||
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="分类下存在 FAQ,无法删除")
|
||||
|
||||
+54
-53
@@ -3,8 +3,8 @@ import uuid
|
||||
from fastapi import APIRouter, Depends, HTTPException, status
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.core.deps import get_current_user, get_db_session, require_study_not_locked
|
||||
from app.core.project_permissions import role_has_project_permission
|
||||
from app.core.deps import get_current_user, get_db_session, require_study_not_locked, require_api_permission
|
||||
from app.core.project_permissions import role_has_api_permission
|
||||
from app.crud import audit as audit_crud
|
||||
from app.crud import faq_category as category_crud
|
||||
from app.crud import faq_item as faq_crud
|
||||
@@ -31,32 +31,16 @@ def _is_system_admin(current_user) -> bool:
|
||||
return role == "ADMIN"
|
||||
|
||||
|
||||
async def _require_project_permission(
|
||||
db: AsyncSession,
|
||||
study_id: uuid.UUID | None,
|
||||
current_user,
|
||||
action: str,
|
||||
):
|
||||
if not study_id:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="FAQ 不存在")
|
||||
if _is_system_admin(current_user):
|
||||
return None
|
||||
member = await member_crud.get_member(db, study_id, current_user.id)
|
||||
if not member or not member.is_active:
|
||||
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="不是该项目成员")
|
||||
allowed = await role_has_project_permission(db, study_id, member.role_in_study, "faq", action)
|
||||
if not allowed:
|
||||
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="权限不足")
|
||||
return member
|
||||
|
||||
|
||||
@router.post(
|
||||
"/",
|
||||
response_model=FaqRead,
|
||||
status_code=status.HTTP_201_CREATED,
|
||||
summary="创建 FAQ",
|
||||
description="创建项目内 FAQ,权限由项目级权限矩阵控制。",
|
||||
dependencies=[Depends(require_study_not_locked())],
|
||||
dependencies=[
|
||||
Depends(require_api_permission("faq:create")),
|
||||
Depends(require_study_not_locked())
|
||||
],
|
||||
)
|
||||
async def create_faq(
|
||||
payload: FaqCreate,
|
||||
@@ -70,7 +54,6 @@ async def create_faq(
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="分类不存在")
|
||||
if cat.study_id != payload.study_id:
|
||||
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="分类范围不匹配")
|
||||
await _require_project_permission(db, payload.study_id, current_user, "write")
|
||||
try:
|
||||
item = await faq_crud.create_item(db, payload, created_by=current_user.id)
|
||||
except ValueError as exc:
|
||||
@@ -102,6 +85,7 @@ async def create_faq(
|
||||
response_model=PaginatedResponse[FaqRead],
|
||||
summary="FAQ 列表",
|
||||
description="返回全局与项目 FAQ,可按关键词、分类过滤。",
|
||||
dependencies=[Depends(require_api_permission("faq:read"))],
|
||||
)
|
||||
async def list_faqs(
|
||||
study_id: uuid.UUID | None = None,
|
||||
@@ -116,14 +100,23 @@ async def list_faqs(
|
||||
async def _get_member_role(sid: uuid.UUID) -> str | None:
|
||||
if sid in membership_cache:
|
||||
return membership_cache[sid]
|
||||
member = await _require_project_permission(db, sid, current_user, "read")
|
||||
role = member.role_in_study if member else "ADMIN"
|
||||
member = await member_crud.get_member(db, sid, current_user.id)
|
||||
role = member.role_in_study if member else None
|
||||
membership_cache[sid] = role
|
||||
return role
|
||||
|
||||
if not study_id:
|
||||
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="必须提供项目 ID")
|
||||
await _require_project_permission(db, study_id, current_user, "write" if is_active is False else "read")
|
||||
|
||||
role_value = current_user.role.value if hasattr(current_user.role, "value") else current_user.role
|
||||
if role_value != "ADMIN":
|
||||
member = await member_crud.get_member(db, study_id, current_user.id)
|
||||
if not member or not member.is_active:
|
||||
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="不是项目成员")
|
||||
if is_active is False:
|
||||
allowed = await role_has_api_permission(db, study_id, member.role_in_study, "faq:update", check_prerequisites=False)
|
||||
if not allowed:
|
||||
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="权限不足")
|
||||
|
||||
items = await faq_crud.list_items(
|
||||
db,
|
||||
@@ -141,7 +134,7 @@ async def list_faqs(
|
||||
if not role:
|
||||
continue
|
||||
if not it.is_active and not _is_system_admin(current_user):
|
||||
allowed = await role_has_project_permission(db, it.study_id, role, "faq", "write")
|
||||
allowed = await role_has_api_permission(db, it.study_id, role, "faq:update", check_prerequisites=False)
|
||||
if not allowed:
|
||||
continue
|
||||
visible.append(FaqRead.model_validate(it))
|
||||
@@ -153,6 +146,7 @@ async def list_faqs(
|
||||
response_model=FaqRead,
|
||||
summary="FAQ 详情",
|
||||
description="获取单条 FAQ,停用 FAQ 需项目级写权限。",
|
||||
dependencies=[Depends(require_api_permission("faq:read"))],
|
||||
)
|
||||
async def get_faq(
|
||||
item_id: uuid.UUID,
|
||||
@@ -164,7 +158,14 @@ async def get_faq(
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="FAQ 不存在")
|
||||
if not item.study_id:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="FAQ 不存在")
|
||||
await _require_project_permission(db, item.study_id, current_user, "write" if not item.is_active else "read")
|
||||
role_value = current_user.role.value if hasattr(current_user.role, "value") else current_user.role
|
||||
if not item.is_active and role_value != "ADMIN":
|
||||
member = await member_crud.get_member(db, item.study_id, current_user.id)
|
||||
if not member or not member.is_active:
|
||||
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="不是项目成员")
|
||||
allowed = await role_has_api_permission(db, item.study_id, member.role_in_study, "faq:update", check_prerequisites=False)
|
||||
if not allowed:
|
||||
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="权限不足")
|
||||
return FaqRead.model_validate(item)
|
||||
|
||||
|
||||
@@ -173,7 +174,10 @@ async def get_faq(
|
||||
response_model=FaqRead,
|
||||
summary="更新 FAQ",
|
||||
description="更新 FAQ 内容或启停状态,权限由项目级权限矩阵控制。",
|
||||
dependencies=[Depends(require_study_not_locked())],
|
||||
dependencies=[
|
||||
Depends(require_api_permission("faq:update")),
|
||||
Depends(require_study_not_locked())
|
||||
],
|
||||
)
|
||||
async def update_faq(
|
||||
item_id: uuid.UUID,
|
||||
@@ -184,10 +188,6 @@ async def update_faq(
|
||||
item = await faq_crud.get_item(db, item_id)
|
||||
if not item:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="FAQ 不存在")
|
||||
if item.created_by != current_user.id:
|
||||
await _require_project_permission(db, item.study_id, current_user, "write")
|
||||
else:
|
||||
await _require_project_permission(db, item.study_id, current_user, "write")
|
||||
old_active = item.is_active
|
||||
updated = await faq_crud.update_item(db, item, payload)
|
||||
action = "UPDATE_FAQ_ITEM"
|
||||
@@ -213,7 +213,10 @@ async def update_faq(
|
||||
response_model=FaqRead,
|
||||
summary="更新 FAQ 状态",
|
||||
description="提问者或具备项目级写权限的成员可确认已解决。",
|
||||
dependencies=[Depends(require_study_not_locked())],
|
||||
dependencies=[
|
||||
Depends(require_api_permission("faq:update")),
|
||||
Depends(require_study_not_locked())
|
||||
],
|
||||
)
|
||||
async def update_faq_status(
|
||||
item_id: uuid.UUID,
|
||||
@@ -226,10 +229,6 @@ async def update_faq_status(
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="FAQ 不存在")
|
||||
if payload.status != "RESOLVED":
|
||||
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="仅允许设置为已解决")
|
||||
if item.created_by != current_user.id:
|
||||
await _require_project_permission(db, item.study_id, current_user, "write")
|
||||
else:
|
||||
await _require_project_permission(db, item.study_id, current_user, "read")
|
||||
await faq_crud.set_status(db, item.id, "RESOLVED", resolved_by_confirm=True)
|
||||
updated = await faq_crud.get_item(db, item_id)
|
||||
return FaqRead.model_validate(updated)
|
||||
@@ -240,7 +239,10 @@ async def update_faq_status(
|
||||
response_model=FaqRead,
|
||||
summary="设置最佳回复",
|
||||
description="项目成员可设置最佳回复,全局仅 ADMIN。",
|
||||
dependencies=[Depends(require_study_not_locked())],
|
||||
dependencies=[
|
||||
Depends(require_api_permission("faq:update")),
|
||||
Depends(require_study_not_locked())
|
||||
],
|
||||
)
|
||||
async def set_best_reply(
|
||||
item_id: uuid.UUID,
|
||||
@@ -253,7 +255,6 @@ async def set_best_reply(
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="FAQ 不存在")
|
||||
if not item.study_id:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="FAQ 不存在")
|
||||
await _require_project_permission(db, item.study_id, current_user, "write")
|
||||
if payload.best_reply_id:
|
||||
reply = await reply_crud.get_reply(db, payload.best_reply_id)
|
||||
if not reply or reply.faq_id != item.id:
|
||||
@@ -281,6 +282,7 @@ async def set_best_reply(
|
||||
response_model=PaginatedResponse[FaqReplyRead],
|
||||
summary="FAQ 回复列表",
|
||||
description="获取 FAQ 的回复列表。",
|
||||
dependencies=[Depends(require_api_permission("faq:read"))],
|
||||
)
|
||||
async def list_replies(
|
||||
item_id: uuid.UUID,
|
||||
@@ -290,7 +292,6 @@ async def list_replies(
|
||||
item = await faq_crud.get_item(db, item_id)
|
||||
if not item:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="FAQ 不存在")
|
||||
await _require_project_permission(db, item.study_id, current_user, "read")
|
||||
replies = await reply_crud.list_replies(db, item_id)
|
||||
reply_map = {r.id: r for r in replies}
|
||||
result: list[FaqReplyRead] = []
|
||||
@@ -317,7 +318,10 @@ async def list_replies(
|
||||
status_code=status.HTTP_201_CREATED,
|
||||
summary="创建 FAQ 回复",
|
||||
description="回复 FAQ,项目内成员可回复,全局仅 ADMIN。",
|
||||
dependencies=[Depends(require_study_not_locked())],
|
||||
dependencies=[
|
||||
Depends(require_api_permission("faq_reply:create")),
|
||||
Depends(require_study_not_locked())
|
||||
],
|
||||
)
|
||||
async def create_reply(
|
||||
item_id: uuid.UUID,
|
||||
@@ -332,7 +336,6 @@ async def create_reply(
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="FAQ 不存在")
|
||||
if not payload.content.strip():
|
||||
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="回复内容不能为空")
|
||||
await _require_project_permission(db, item.study_id, current_user, "write")
|
||||
quote = None
|
||||
if payload.quote_reply_id:
|
||||
quote = await reply_crud.get_reply(db, payload.quote_reply_id)
|
||||
@@ -377,7 +380,10 @@ async def create_reply(
|
||||
status_code=status.HTTP_204_NO_CONTENT,
|
||||
summary="删除 FAQ",
|
||||
description="删除 FAQ,权限由项目级权限矩阵控制。",
|
||||
dependencies=[Depends(require_study_not_locked())],
|
||||
dependencies=[
|
||||
Depends(require_api_permission("faq:delete")),
|
||||
Depends(require_study_not_locked())
|
||||
],
|
||||
)
|
||||
async def delete_faq(
|
||||
item_id: uuid.UUID,
|
||||
@@ -387,10 +393,6 @@ async def delete_faq(
|
||||
item = await faq_crud.get_item(db, item_id)
|
||||
if not item:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="FAQ 不存在")
|
||||
if item.created_by != current_user.id:
|
||||
await _require_project_permission(db, item.study_id, current_user, "write")
|
||||
else:
|
||||
await _require_project_permission(db, item.study_id, current_user, "write")
|
||||
await reply_crud.delete_replies_by_faq_id(db, item.id)
|
||||
await db.delete(item)
|
||||
await db.commit()
|
||||
@@ -411,7 +413,10 @@ async def delete_faq(
|
||||
status_code=status.HTTP_204_NO_CONTENT,
|
||||
summary="删除 FAQ 回复",
|
||||
description="删除 FAQ 回复,回复者或具备项目级写权限的成员可删除。",
|
||||
dependencies=[Depends(require_study_not_locked())],
|
||||
dependencies=[
|
||||
Depends(require_api_permission("faq_reply:delete")),
|
||||
Depends(require_study_not_locked())
|
||||
],
|
||||
)
|
||||
async def delete_reply(
|
||||
item_id: uuid.UUID,
|
||||
@@ -425,10 +430,6 @@ async def delete_reply(
|
||||
reply = await reply_crud.get_reply(db, reply_id)
|
||||
if not reply or reply.faq_id != item.id:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="回复不存在")
|
||||
if reply.created_by != current_user.id:
|
||||
await _require_project_permission(db, item.study_id, current_user, "write")
|
||||
else:
|
||||
await _require_project_permission(db, item.study_id, current_user, "read")
|
||||
if item.best_reply_id == reply.id:
|
||||
await faq_crud.set_best_reply(db, item.id, None)
|
||||
ref_count = await reply_crud.count_quote_references(db, reply.id)
|
||||
|
||||
@@ -7,8 +7,8 @@ from fastapi import APIRouter, Depends, File, HTTPException, UploadFile, status,
|
||||
from fastapi.responses import FileResponse
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.core.deps import get_current_user, get_db_session, require_study_not_locked
|
||||
from app.core.project_permissions import role_has_project_permission
|
||||
from app.core.deps import get_current_user, get_db_session, require_study_not_locked, require_api_permission
|
||||
from app.core.project_permissions import role_has_api_permission
|
||||
from app.core.security import decode_token
|
||||
from app.crud import audit as audit_crud
|
||||
from app.crud import contract_fee as contract_fee_crud
|
||||
@@ -48,20 +48,6 @@ async def _resolve_project_id(db: AsyncSession, entity_type: str, entity_id: uui
|
||||
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="不支持的附件类型")
|
||||
|
||||
|
||||
async def _ensure_project_access(db: AsyncSession, project_id: uuid.UUID, current_user, write: bool = False):
|
||||
role_value = current_user.role.value if hasattr(current_user.role, "value") else current_user.role
|
||||
if role_value == "ADMIN":
|
||||
return None
|
||||
membership = await member_crud.get_member(db, project_id, current_user.id)
|
||||
if not membership or not membership.is_active:
|
||||
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="不是项目成员")
|
||||
action = "write" if write else "read"
|
||||
allowed = await role_has_project_permission(db, project_id, membership.role_in_study, "fees", action)
|
||||
if not allowed:
|
||||
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="项目权限不足")
|
||||
return membership
|
||||
|
||||
|
||||
async def _authorize_download_user(request: Request, db: AsyncSession):
|
||||
token = None
|
||||
auth_header = request.headers.get("Authorization")
|
||||
@@ -82,7 +68,10 @@ async def _authorize_download_user(request: Request, db: AsyncSession):
|
||||
"/attachments",
|
||||
response_model=FeeApiResponse[FeeAttachmentRead],
|
||||
status_code=status.HTTP_201_CREATED,
|
||||
dependencies=[Depends(get_current_user), Depends(require_study_not_locked())],
|
||||
dependencies=[
|
||||
Depends(require_api_permission("fees_attachments:create")),
|
||||
Depends(require_study_not_locked())
|
||||
],
|
||||
)
|
||||
async def upload_fee_attachment(
|
||||
entity_type: str = Form(...),
|
||||
@@ -97,7 +86,6 @@ async def upload_fee_attachment(
|
||||
if file_type not in ALLOWED_FILE_TYPES.get(entity_type, set()):
|
||||
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="附件文件类型无效")
|
||||
project_id = await _resolve_project_id(db, entity_type, entity_id)
|
||||
await _ensure_project_access(db, project_id, current_user, write=True)
|
||||
|
||||
dest_dir = UPLOAD_ROOT / f"{entity_type}_{entity_id}"
|
||||
dest_dir.mkdir(parents=True, exist_ok=True)
|
||||
@@ -151,7 +139,7 @@ async def upload_fee_attachment(
|
||||
@router.get(
|
||||
"/attachments",
|
||||
response_model=FeeApiResponse[list[FeeAttachmentRead]],
|
||||
dependencies=[Depends(get_current_user)],
|
||||
dependencies=[Depends(require_api_permission("fees_attachments:read"))],
|
||||
)
|
||||
async def list_fee_attachments(
|
||||
entity_type: str,
|
||||
@@ -162,7 +150,6 @@ async def list_fee_attachments(
|
||||
if entity_type not in ALLOWED_ENTITY_TYPES:
|
||||
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="附件类型无效")
|
||||
project_id = await _resolve_project_id(db, entity_type, entity_id)
|
||||
await _ensure_project_access(db, project_id, current_user, write=False)
|
||||
attachments = await fee_attachment_crud.list_attachments(db, entity_type=entity_type, entity_id=entity_id)
|
||||
user_ids = {a.uploaded_by for a in attachments if a.uploaded_by}
|
||||
users_map = await user_crud.get_users_by_ids(db, user_ids)
|
||||
@@ -202,7 +189,16 @@ async def download_fee_attachment(
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="附件不存在")
|
||||
current_user = await _authorize_download_user(request, db)
|
||||
project_id = await _resolve_project_id(db, attachment.entity_type, attachment.entity_id)
|
||||
await _ensure_project_access(db, project_id, current_user, write=False)
|
||||
role_value = current_user.role.value if hasattr(current_user.role, "value") else current_user.role
|
||||
if role_value != "ADMIN":
|
||||
membership = await member_crud.get_member(db, project_id, current_user.id)
|
||||
if not membership or not membership.is_active:
|
||||
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="不是项目成员")
|
||||
allowed = await role_has_api_permission(
|
||||
db, project_id, membership.role_in_study, "fees_attachments:read", check_prerequisites=False
|
||||
)
|
||||
if not allowed:
|
||||
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="项目权限不足")
|
||||
if not attachment.storage_key or not os.path.exists(attachment.storage_key):
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="服务器未找到文件")
|
||||
return FileResponse(
|
||||
@@ -216,7 +212,10 @@ async def download_fee_attachment(
|
||||
@router.delete(
|
||||
"/attachments/{attachment_id}",
|
||||
status_code=status.HTTP_204_NO_CONTENT,
|
||||
dependencies=[Depends(get_current_user), Depends(require_study_not_locked())],
|
||||
dependencies=[
|
||||
Depends(require_api_permission("fees_attachments:delete")),
|
||||
Depends(require_study_not_locked())
|
||||
],
|
||||
)
|
||||
async def delete_fee_attachment(
|
||||
attachment_id: uuid.UUID,
|
||||
@@ -227,9 +226,14 @@ async def delete_fee_attachment(
|
||||
if not attachment:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="附件不存在")
|
||||
project_id = await _resolve_project_id(db, attachment.entity_type, attachment.entity_id)
|
||||
membership = await _ensure_project_access(db, project_id, current_user, write=True)
|
||||
|
||||
role_value = current_user.role.value if hasattr(current_user.role, "value") else current_user.role
|
||||
membership = None
|
||||
if role_value != "ADMIN":
|
||||
membership = await member_crud.get_member(db, project_id, current_user.id)
|
||||
if not membership or not membership.is_active:
|
||||
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="不是项目成员")
|
||||
|
||||
can_delete = (
|
||||
role_value == "ADMIN"
|
||||
or attachment.uploaded_by == current_user.id
|
||||
|
||||
@@ -3,7 +3,7 @@ import uuid
|
||||
from fastapi import APIRouter, Depends, HTTPException, status
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.core.deps import get_current_user, get_db_session, require_study_not_locked, require_study_permission
|
||||
from app.core.deps import get_current_user, get_db_session, require_study_not_locked, require_api_permission
|
||||
from app.crud import audit as audit_crud
|
||||
from app.crud import knowledge_note as note_crud
|
||||
from app.crud import site as site_crud
|
||||
@@ -32,7 +32,7 @@ async def _ensure_site_name_active(db: AsyncSession, study_id: uuid.UUID, site_n
|
||||
"/notes",
|
||||
response_model=KnowledgeNoteRead,
|
||||
status_code=status.HTTP_201_CREATED,
|
||||
dependencies=[Depends(require_study_permission("shared_library", "write"))],
|
||||
dependencies=[Depends(require_api_permission("knowledge_notes:create"))],
|
||||
)
|
||||
async def create_note(
|
||||
study_id: uuid.UUID,
|
||||
@@ -59,7 +59,7 @@ async def create_note(
|
||||
@router.get(
|
||||
"/notes",
|
||||
response_model=list[KnowledgeNoteRead],
|
||||
dependencies=[Depends(require_study_permission("shared_library", "read"))],
|
||||
dependencies=[Depends(require_api_permission("knowledge_notes:read"))],
|
||||
)
|
||||
async def list_notes(
|
||||
study_id: uuid.UUID,
|
||||
@@ -77,7 +77,7 @@ async def list_notes(
|
||||
@router.get(
|
||||
"/notes/{note_id}",
|
||||
response_model=KnowledgeNoteRead,
|
||||
dependencies=[Depends(require_study_permission("shared_library", "read"))],
|
||||
dependencies=[Depends(require_api_permission("knowledge_notes:read"))],
|
||||
)
|
||||
async def get_note(
|
||||
study_id: uuid.UUID,
|
||||
@@ -94,7 +94,7 @@ async def get_note(
|
||||
@router.patch(
|
||||
"/notes/{note_id}",
|
||||
response_model=KnowledgeNoteRead,
|
||||
dependencies=[Depends(require_study_permission("shared_library", "write"))],
|
||||
dependencies=[Depends(require_api_permission("knowledge_notes:update"))],
|
||||
)
|
||||
async def update_note(
|
||||
study_id: uuid.UUID,
|
||||
@@ -125,7 +125,7 @@ async def update_note(
|
||||
@router.delete(
|
||||
"/notes/{note_id}",
|
||||
status_code=status.HTTP_204_NO_CONTENT,
|
||||
dependencies=[Depends(require_study_permission("shared_library", "write"))],
|
||||
dependencies=[Depends(require_api_permission("knowledge_notes:delete"))],
|
||||
)
|
||||
async def delete_note(
|
||||
study_id: uuid.UUID,
|
||||
|
||||
@@ -3,7 +3,7 @@ import uuid
|
||||
from fastapi import APIRouter, Depends, HTTPException, status
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.core.deps import get_current_user, get_db_session, require_study_not_locked, require_study_permission
|
||||
from app.core.deps import get_current_user, get_db_session, require_study_not_locked, require_api_permission
|
||||
from app.crud import audit as audit_crud
|
||||
from app.crud import material_equipment as equipment_crud
|
||||
from app.crud import study as study_crud
|
||||
@@ -28,7 +28,7 @@ def _validate_calibration(need_calibration: bool, calibration_cycle_days: int |
|
||||
"/equipment",
|
||||
response_model=MaterialEquipmentRead,
|
||||
status_code=status.HTTP_201_CREATED,
|
||||
dependencies=[Depends(require_study_permission("materials", "write")), Depends(require_study_not_locked())],
|
||||
dependencies=[Depends(require_api_permission("material_equipments:create")), Depends(require_study_not_locked())],
|
||||
)
|
||||
async def create_equipment(
|
||||
study_id: uuid.UUID,
|
||||
@@ -57,7 +57,7 @@ async def create_equipment(
|
||||
@router.get(
|
||||
"/equipment",
|
||||
response_model=list[MaterialEquipmentRead],
|
||||
dependencies=[Depends(require_study_permission("materials", "read"))],
|
||||
dependencies=[Depends(require_api_permission("material_equipments:read"))],
|
||||
)
|
||||
async def list_equipments(
|
||||
study_id: uuid.UUID,
|
||||
@@ -74,7 +74,7 @@ async def list_equipments(
|
||||
@router.get(
|
||||
"/equipment/{equipment_id}",
|
||||
response_model=MaterialEquipmentRead,
|
||||
dependencies=[Depends(require_study_permission("materials", "read"))],
|
||||
dependencies=[Depends(require_api_permission("material_equipments:read"))],
|
||||
)
|
||||
async def get_equipment(
|
||||
study_id: uuid.UUID,
|
||||
@@ -91,7 +91,7 @@ async def get_equipment(
|
||||
@router.patch(
|
||||
"/equipment/{equipment_id}",
|
||||
response_model=MaterialEquipmentRead,
|
||||
dependencies=[Depends(require_study_permission("materials", "write")), Depends(require_study_not_locked())],
|
||||
dependencies=[Depends(require_api_permission("material_equipments:update")), Depends(require_study_not_locked())],
|
||||
)
|
||||
async def update_equipment(
|
||||
study_id: uuid.UUID,
|
||||
@@ -128,7 +128,7 @@ async def update_equipment(
|
||||
@router.delete(
|
||||
"/equipment/{equipment_id}",
|
||||
status_code=status.HTTP_204_NO_CONTENT,
|
||||
dependencies=[Depends(require_study_permission("materials", "write")), Depends(require_study_not_locked())],
|
||||
dependencies=[Depends(require_api_permission("material_equipments:delete")), Depends(require_study_not_locked())],
|
||||
)
|
||||
async def delete_equipment(
|
||||
study_id: uuid.UUID,
|
||||
|
||||
@@ -4,7 +4,7 @@ import uuid
|
||||
from fastapi import APIRouter, Depends
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.core.deps import get_db_session, require_study_permission
|
||||
from app.core.deps import get_db_session, require_api_permission
|
||||
from app.crud import overview as overview_crud
|
||||
from app.schemas.overview import ProjectOverviewResponse
|
||||
|
||||
@@ -14,7 +14,7 @@ router = APIRouter()
|
||||
@router.get(
|
||||
"/overview",
|
||||
response_model=ProjectOverviewResponse,
|
||||
dependencies=[Depends(require_study_permission("project_overview", "read"))],
|
||||
dependencies=[Depends(require_api_permission("project_overview:read"))],
|
||||
)
|
||||
async def get_project_overview(
|
||||
study_id: uuid.UUID,
|
||||
@@ -22,7 +22,7 @@ async def get_project_overview(
|
||||
) -> ProjectOverviewResponse:
|
||||
"""
|
||||
获取项目概览数据
|
||||
|
||||
|
||||
返回项目各中心的进度情况,包括:
|
||||
- 机构立项状态
|
||||
- 伦理审批状态
|
||||
|
||||
@@ -0,0 +1,126 @@
|
||||
"""权限模板管理API"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
from typing import Annotated, Optional
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, status
|
||||
from fastapi.responses import Response
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.core.deps import get_current_user, get_db_session, require_study_roles
|
||||
from app.models.permission_template import TemplateType
|
||||
from app.schemas.permission_template import (
|
||||
ApplyTemplateRequest,
|
||||
ApplyTemplateResponse,
|
||||
PermissionTemplateCreate,
|
||||
PermissionTemplateRead,
|
||||
PermissionTemplateUpdate,
|
||||
)
|
||||
from app.services.permission_template_service import PermissionTemplateService
|
||||
|
||||
# 模板管理路由(不需要 study_id)
|
||||
router = APIRouter(prefix="/permission-templates", tags=["permission-templates"])
|
||||
|
||||
# 项目级模板操作路由(需要 study_id,挂载到 /studies/{study_id})
|
||||
study_router = APIRouter(prefix="/permission-templates", tags=["permission-templates"])
|
||||
|
||||
|
||||
@router.get("", response_model=list[PermissionTemplateRead])
|
||||
async def list_templates(
|
||||
template_type: Optional[str] = None,
|
||||
category: Optional[str] = None,
|
||||
skip: int = 0,
|
||||
limit: int = 100,
|
||||
db: Annotated[AsyncSession, Depends(get_db_session)] = None,
|
||||
) -> list[PermissionTemplateRead]:
|
||||
"""列表权限模板"""
|
||||
t_type = TemplateType(template_type) if template_type else None
|
||||
templates = await PermissionTemplateService.list_templates(
|
||||
db, template_type=t_type, category=category, skip=skip, limit=limit
|
||||
)
|
||||
return [PermissionTemplateRead.model_validate(t) for t in templates]
|
||||
|
||||
|
||||
@router.post(
|
||||
"",
|
||||
response_model=PermissionTemplateRead,
|
||||
status_code=status.HTTP_201_CREATED,
|
||||
)
|
||||
async def create_template(
|
||||
payload: PermissionTemplateCreate,
|
||||
db: Annotated[AsyncSession, Depends(get_db_session)] = None,
|
||||
current_user=Depends(get_current_user),
|
||||
) -> PermissionTemplateRead:
|
||||
"""创建权限模板"""
|
||||
try:
|
||||
template = await PermissionTemplateService.create_template(db, payload, current_user.id)
|
||||
return PermissionTemplateRead.model_validate(template)
|
||||
except ValueError as e:
|
||||
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e))
|
||||
|
||||
|
||||
@router.get("/{template_id}", response_model=PermissionTemplateRead)
|
||||
async def get_template(
|
||||
template_id: uuid.UUID,
|
||||
db: Annotated[AsyncSession, Depends(get_db_session)] = None,
|
||||
) -> PermissionTemplateRead:
|
||||
"""获取权限模板"""
|
||||
template = await PermissionTemplateService.get_template(db, template_id)
|
||||
if not template:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="模板不存在")
|
||||
return PermissionTemplateRead.model_validate(template)
|
||||
|
||||
|
||||
@router.put("/{template_id}", response_model=PermissionTemplateRead)
|
||||
async def update_template(
|
||||
template_id: uuid.UUID,
|
||||
payload: PermissionTemplateUpdate,
|
||||
db: Annotated[AsyncSession, Depends(get_db_session)] = None,
|
||||
current_user=Depends(get_current_user),
|
||||
) -> PermissionTemplateRead:
|
||||
"""更新权限模板"""
|
||||
try:
|
||||
template = await PermissionTemplateService.update_template(db, template_id, payload)
|
||||
return PermissionTemplateRead.model_validate(template)
|
||||
except ValueError as e:
|
||||
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e))
|
||||
|
||||
|
||||
@router.delete("/{template_id}", status_code=status.HTTP_204_NO_CONTENT, response_class=Response)
|
||||
async def delete_template(
|
||||
template_id: uuid.UUID,
|
||||
db: Annotated[AsyncSession, Depends(get_db_session)] = None,
|
||||
current_user=Depends(get_current_user),
|
||||
):
|
||||
"""删除权限模板"""
|
||||
try:
|
||||
await PermissionTemplateService.delete_template(db, template_id)
|
||||
except ValueError as e:
|
||||
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e))
|
||||
|
||||
|
||||
@study_router.post(
|
||||
"/{template_id}/apply",
|
||||
response_model=ApplyTemplateResponse,
|
||||
)
|
||||
async def apply_template(
|
||||
study_id: uuid.UUID,
|
||||
template_id: uuid.UUID,
|
||||
payload: ApplyTemplateRequest,
|
||||
db: Annotated[AsyncSession, Depends(get_db_session)] = None,
|
||||
_=Depends(require_study_roles(["PM"])),
|
||||
) -> ApplyTemplateResponse:
|
||||
"""应用权限模板到项目"""
|
||||
try:
|
||||
result = await PermissionTemplateService.apply_template(
|
||||
db,
|
||||
study_id,
|
||||
payload.template_id,
|
||||
roles=payload.roles,
|
||||
override=payload.override,
|
||||
)
|
||||
return ApplyTemplateResponse(**result)
|
||||
except ValueError as e:
|
||||
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e))
|
||||
@@ -1,66 +0,0 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import uuid
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, status
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.core.deps import get_current_user, get_db_session, require_study_member, require_study_permission
|
||||
from app.core.project_permissions import PROJECT_PERMISSION_MODULES, get_project_role_permissions, replace_project_role_permissions
|
||||
from app.crud import audit as audit_crud
|
||||
from app.crud import study as study_crud
|
||||
from app.schemas.project_permission import ProjectPermissionModule, ProjectRolePermissionsRead, ProjectRolePermissionsUpdate
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
async def _ensure_study_exists(db: AsyncSession, study_id: uuid.UUID):
|
||||
study = await study_crud.get(db, study_id)
|
||||
if not study:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="项目不存在")
|
||||
return study
|
||||
|
||||
|
||||
@router.get("/", response_model=ProjectRolePermissionsRead, dependencies=[Depends(require_study_member())])
|
||||
async def get_permissions(
|
||||
study_id: uuid.UUID,
|
||||
db: AsyncSession = Depends(get_db_session),
|
||||
) -> ProjectRolePermissionsRead:
|
||||
await _ensure_study_exists(db, study_id)
|
||||
roles = await get_project_role_permissions(db, study_id)
|
||||
modules = [ProjectPermissionModule(**item) for item in PROJECT_PERMISSION_MODULES]
|
||||
return ProjectRolePermissionsRead(modules=modules, roles=roles)
|
||||
|
||||
|
||||
@router.put("/", response_model=ProjectRolePermissionsRead, dependencies=[Depends(require_study_permission("project_members", "write"))])
|
||||
async def update_permissions(
|
||||
study_id: uuid.UUID,
|
||||
payload: ProjectRolePermissionsUpdate,
|
||||
db: AsyncSession = Depends(get_db_session),
|
||||
current_user=Depends(get_current_user),
|
||||
) -> ProjectRolePermissionsRead:
|
||||
await _ensure_study_exists(db, study_id)
|
||||
roles = await replace_project_role_permissions(
|
||||
db,
|
||||
study_id,
|
||||
{
|
||||
role: {
|
||||
module: actions.model_dump()
|
||||
for module, actions in modules.items()
|
||||
}
|
||||
for role, modules in payload.roles.items()
|
||||
},
|
||||
)
|
||||
await audit_crud.log_action(
|
||||
db,
|
||||
study_id=study_id,
|
||||
entity_type="project_permissions",
|
||||
entity_id=study_id,
|
||||
action="PROJECT_PERMISSIONS_UPDATED",
|
||||
detail=json.dumps({"targetName": "项目权限", "after": roles}, ensure_ascii=False),
|
||||
operator_id=current_user.id,
|
||||
operator_role=current_user.role,
|
||||
)
|
||||
modules = [ProjectPermissionModule(**item) for item in PROJECT_PERMISSION_MODULES]
|
||||
return ProjectRolePermissionsRead(modules=modules, roles=roles)
|
||||
@@ -1,6 +1,6 @@
|
||||
from fastapi import APIRouter
|
||||
|
||||
from app.api.v1 import auth, users, admin_users, studies, sites, members, attachments, audit_logs, dashboard, subjects, visits, aes, finance_dashboard, finance_contracts, fees_contracts, fees_attachments, drug_shipments, material_equipments, project_milestones, startup, knowledge_notes, subject_histories, subject_pds, study_subject_pds, faq_categories, faqs, documents, overview, notifications, monitoring_visit_issues, project_permissions, api_permissions, permission_monitoring
|
||||
from app.api.v1 import auth, users, admin_users, studies, sites, members, attachments, audit_logs, dashboard, subjects, visits, aes, finance_dashboard, finance_contracts, fees_contracts, fees_attachments, drug_shipments, material_equipments, project_milestones, startup, knowledge_notes, subject_histories, subject_pds, study_subject_pds, faq_categories, faqs, documents, overview, notifications, monitoring_visit_issues, api_permissions, permission_monitoring, permission_templates
|
||||
|
||||
|
||||
api_router = APIRouter()
|
||||
@@ -12,8 +12,8 @@ api_router.include_router(overview.router, prefix="/studies/{study_id}", tags=["
|
||||
api_router.include_router(notifications.router, prefix="/studies/{study_id}", tags=["notifications"])
|
||||
api_router.include_router(sites.router, prefix="/studies/{study_id}/sites", tags=["sites"])
|
||||
api_router.include_router(members.router, prefix="/studies/{study_id}/members", tags=["study-members"])
|
||||
api_router.include_router(project_permissions.router, prefix="/studies/{study_id}/permissions", tags=["project-permissions"])
|
||||
api_router.include_router(api_permissions.router, tags=["api-permissions"])
|
||||
api_router.include_router(api_permissions.study_router, prefix="/studies/{study_id}", tags=["api-permissions"])
|
||||
api_router.include_router(attachments.router, prefix="/studies/{study_id}/{entity_type}/{entity_id}/attachments", tags=["attachments"])
|
||||
api_router.include_router(attachments.global_router, prefix="/attachments", tags=["attachments"])
|
||||
api_router.include_router(audit_logs.router, prefix="/studies/{study_id}/audit-logs", tags=["audit-logs"])
|
||||
@@ -38,3 +38,5 @@ api_router.include_router(faq_categories.router, prefix="/faqs/categories", tags
|
||||
api_router.include_router(faqs.router, prefix="/faqs/items", tags=["faqs"])
|
||||
api_router.include_router(documents.router, prefix="", tags=["documents"])
|
||||
api_router.include_router(permission_monitoring.router)
|
||||
api_router.include_router(permission_templates.router)
|
||||
api_router.include_router(permission_templates.study_router, prefix="/studies/{study_id}", tags=["permission-templates"])
|
||||
|
||||
@@ -3,7 +3,7 @@ import uuid
|
||||
from fastapi import APIRouter, Depends, HTTPException, status
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.core.deps import get_current_user, get_db_session, require_study_not_locked, require_study_permission
|
||||
from app.core.deps import get_current_user, get_db_session, require_study_not_locked, require_api_permission
|
||||
from app.crud import audit as audit_crud
|
||||
from app.crud import site as site_crud
|
||||
from app.crud import subject as subject_crud
|
||||
@@ -33,7 +33,7 @@ async def _ensure_subject_active(db: AsyncSession, subject) -> None:
|
||||
"/histories",
|
||||
response_model=SubjectHistoryRead,
|
||||
status_code=status.HTTP_201_CREATED,
|
||||
dependencies=[Depends(require_study_permission("subjects", "write"))],
|
||||
dependencies=[Depends(require_api_permission("subject_histories:create"))],
|
||||
)
|
||||
async def create_history(
|
||||
study_id: uuid.UUID,
|
||||
@@ -66,7 +66,7 @@ async def create_history(
|
||||
@router.get(
|
||||
"/histories",
|
||||
response_model=list[SubjectHistoryRead],
|
||||
dependencies=[Depends(require_study_permission("subjects", "read"))],
|
||||
dependencies=[Depends(require_api_permission("subject_histories:read"))],
|
||||
)
|
||||
async def list_histories(
|
||||
study_id: uuid.UUID,
|
||||
@@ -86,7 +86,7 @@ async def list_histories(
|
||||
@router.get(
|
||||
"/histories/{history_id}",
|
||||
response_model=SubjectHistoryRead,
|
||||
dependencies=[Depends(require_study_permission("subjects", "read"))],
|
||||
dependencies=[Depends(require_api_permission("subject_histories:read"))],
|
||||
)
|
||||
async def get_history(
|
||||
study_id: uuid.UUID,
|
||||
@@ -107,7 +107,7 @@ async def get_history(
|
||||
@router.patch(
|
||||
"/histories/{history_id}",
|
||||
response_model=SubjectHistoryRead,
|
||||
dependencies=[Depends(require_study_permission("subjects", "write"))],
|
||||
dependencies=[Depends(require_api_permission("subject_histories:update"))],
|
||||
)
|
||||
async def update_history(
|
||||
study_id: uuid.UUID,
|
||||
@@ -141,7 +141,7 @@ async def update_history(
|
||||
@router.delete(
|
||||
"/histories/{history_id}",
|
||||
status_code=status.HTTP_204_NO_CONTENT,
|
||||
dependencies=[Depends(require_study_permission("subjects", "write"))],
|
||||
dependencies=[Depends(require_api_permission("subject_histories:delete"))],
|
||||
)
|
||||
async def delete_history(
|
||||
study_id: uuid.UUID,
|
||||
|
||||
@@ -7,7 +7,7 @@ from app.core.deps import (
|
||||
get_current_user,
|
||||
get_db_session,
|
||||
require_study_not_locked,
|
||||
require_study_permission,
|
||||
require_api_permission,
|
||||
)
|
||||
from app.crud import audit as audit_crud
|
||||
from app.crud import site as site_crud
|
||||
@@ -64,7 +64,7 @@ def _normalize_choice(value: str | None, allowed: set[str], field_name: str) ->
|
||||
@router.get(
|
||||
"/pds",
|
||||
response_model=list[SubjectPdRead],
|
||||
dependencies=[Depends(require_study_permission("risk_issues", "read"))],
|
||||
dependencies=[Depends(require_api_permission("subject_pds:read"))],
|
||||
)
|
||||
async def list_subject_pds(
|
||||
study_id: uuid.UUID,
|
||||
@@ -83,7 +83,7 @@ async def list_subject_pds(
|
||||
"/pds",
|
||||
response_model=SubjectPdRead,
|
||||
status_code=status.HTTP_201_CREATED,
|
||||
dependencies=[Depends(require_study_permission("risk_issues", "write")), Depends(require_study_not_locked())],
|
||||
dependencies=[Depends(require_api_permission("subject_pds:create")), Depends(require_study_not_locked())],
|
||||
)
|
||||
async def create_subject_pd(
|
||||
study_id: uuid.UUID,
|
||||
@@ -128,7 +128,7 @@ async def create_subject_pd(
|
||||
@router.patch(
|
||||
"/pds/{pd_id}",
|
||||
response_model=SubjectPdRead,
|
||||
dependencies=[Depends(require_study_permission("risk_issues", "write")), Depends(require_study_not_locked())],
|
||||
dependencies=[Depends(require_api_permission("subject_pds:update")), Depends(require_study_not_locked())],
|
||||
)
|
||||
async def update_subject_pd(
|
||||
study_id: uuid.UUID,
|
||||
@@ -175,7 +175,7 @@ async def update_subject_pd(
|
||||
@router.delete(
|
||||
"/pds/{pd_id}",
|
||||
status_code=status.HTTP_204_NO_CONTENT,
|
||||
dependencies=[Depends(require_study_permission("risk_issues", "write")), Depends(require_study_not_locked())],
|
||||
dependencies=[Depends(require_api_permission("subject_pds:delete")), Depends(require_study_not_locked())],
|
||||
)
|
||||
async def delete_subject_pd(
|
||||
study_id: uuid.UUID,
|
||||
|
||||
Reference in New Issue
Block a user