权限管理:接入项目级权限矩阵

新增项目级角色权限矩阵,覆盖 PM、CRA、PV、IMP、QA 等项目角色,并通过迁移表持久化各业务模块的读写权限。

后端将参与者、合同费用、物资、启动、里程碑、风险问题、监查稽查、FAQ、共享库、文件版本等接口接入矩阵校验,修复审计日志导出权限和登录 502 的依赖导入问题。

前端新增权限管理页面和项目路由权限映射,按矩阵控制导航显示、直接访问拦截、操作按钮启停,并限制管理后台仅 admin 和授权 PM 可进入。

补充后端权限归一化与接口静态测试、前端路由/权限工具/权限管理页面/工作台等回归测试。
This commit is contained in:
Cheng Zhou
2026-05-13 08:58:03 +08:00
parent 77e842637d
commit 939fc70532
63 changed files with 1952 additions and 387 deletions
+2 -1
View File
@@ -5,7 +5,7 @@ import { resolve } from "node:path";
const readAuditLogsView = () => readFileSync(resolve(__dirname, "./AuditLogs.vue"), "utf8");
describe("audit logs access", () => {
it("allows current project PM access without relying on global PM role", () => {
it("allows only admins or authorized PMs to use audit export", () => {
const source = readAuditLogsView();
expect(source).toContain("const canAccessAuditLogs = computed");
@@ -13,6 +13,7 @@ describe("audit logs access", () => {
expect(source).toContain("getProjectRole");
expect(source).toContain("study.currentStudyRole");
expect(source).toContain('projectRole.value === "PM"');
expect(source).toContain("roles?.PM?.audit_export?.read");
expect(source).not.toContain('const role = auth.user?.role');
expect(source).not.toContain('role !== "ADMIN"');
});
+20 -2
View File
@@ -167,6 +167,7 @@ import { useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import { ArrowDown } from "@element-plus/icons-vue";
import { createAuditEvent, fetchAuditLogs } from "../../api/auditLogs";
import { fetchProjectRolePermissions } from "../../api/projectPermissions";
import { fetchUsers } from "../../api/users";
import { listMembers } from "../../api/members";
import { auditDict, normalizeAuditEvent } from "../../audit";
@@ -187,6 +188,7 @@ const exportLoading = ref(false);
const logs = ref<any[]>([]);
const users = ref<any[]>([]);
const allLogs = ref<any[]>([]);
const permissionMatrix = ref<any | null>(null);
const page = ref(1);
const pageSize = ref(20);
const total = ref(0);
@@ -212,8 +214,14 @@ const resolveUserDisplayName = (u: any): string => {
const userOptions = computed(() => users.value.map((u: any) => ({ label: resolveUserDisplayName(u), value: u.id })));
const isAdmin = computed(() => isSystemAdmin(auth.user));
const projectRole = computed(() => getProjectRole(study.currentStudy, study.currentStudyRole));
const canProjectExport = computed(() => !!study.currentStudy && isAdmin.value);
const canAccessAuditLogs = computed(() => isAdmin.value || projectRole.value === "PM");
const canProjectExport = computed(() => {
if (isAdmin.value) return true;
return projectRole.value === "PM" && !!permissionMatrix.value?.roles?.PM?.audit_export?.read;
});
const canAccessAuditLogs = computed(() => {
if (isAdmin.value) return true;
return projectRole.value === "PM" && !!permissionMatrix.value?.roles?.PM?.audit_export?.read;
});
const ensureAccess = () => {
if (!canAccessAuditLogs.value) {
@@ -221,6 +229,12 @@ const ensureAccess = () => {
}
};
const loadPermissionMatrix = async () => {
if (!study.currentStudy) return;
const { data } = await fetchProjectRolePermissions(study.currentStudy.id);
permissionMatrix.value = data;
};
const loadUsers = async () => {
try {
if (isAdmin.value) {
@@ -244,6 +258,9 @@ const loadLogs = async () => {
if (!study.currentStudy) return;
loading.value = true;
try {
if (!permissionMatrix.value) {
await loadPermissionMatrix();
}
const batchLimit = 500;
let skip = 0;
const allItems: any[] = [];
@@ -418,6 +435,7 @@ onMounted(async () => {
if (!auth.user && auth.token) {
await auth.fetchMe().catch(() => {});
}
await loadPermissionMatrix().catch(() => {});
ensureAccess();
await loadUsers();
await loadLogs();
@@ -83,11 +83,11 @@ describe("ProjectDetail setup draft publish workflow", () => {
});
describe("project detail management role", () => {
it("allows only current project administrators and PMs to manage setup content", () => {
it("allows only system administrators to manage setup content", () => {
const source = readProjectDetail();
expect(source).toContain("project.value?.role_in_study");
expect(source).toContain('["ADMIN", "PM"].includes(setupRole.value)');
expect(source).toContain("isSystemAdmin(authStore.user)");
expect(source).not.toContain('setupRole.value === "ADMIN"');
expect(source).not.toContain("project.value?.role_in_study || authStore.user?.role");
});
});
+5 -3
View File
@@ -1932,6 +1932,7 @@ import StateLoading from "../../components/StateLoading.vue";
import { useStudyStore } from "../../store/study";
import { useAuthStore } from "../../store/auth";
import { TEXT, requiredMessage } from "../../locales";
import { isSystemAdmin } from "../../utils/roles";
import { groupErrorsBySection, parseFieldPath, type SetupValidationError } from "../../utils/setupFieldLocator";
import { buildSetupReadableDiffRows, serializeDiffValue, type SetupDiffRow } from "../../utils/setupDiffRows";
import {
@@ -2402,8 +2403,7 @@ const setupDraft = reactive<SetupConfigDraft>({
const storageKey = computed(() => `ctms_setup_config_draft_${String(route.params.projectId || "")}`);
const projectDraftStorageKey = computed(() => `ctms_setup_project_draft_${String(route.params.projectId || "")}`);
const setupRole = computed(() => String(project.value?.role_in_study || "").toUpperCase());
const canManageSetup = computed(() => ["ADMIN", "PM"].includes(setupRole.value));
const canManageSetup = computed(() => isSystemAdmin(authStore.user));
const isPreviewView = computed(() => setupViewMode.value === "preview");
const isPublishedVersionView = computed(() => setupViewMode.value === "published");
const isPublishedView = computed(() => isPreviewView.value || isPublishedVersionView.value);
@@ -4419,6 +4419,7 @@ const refreshProjectDisplayAfterPublish = async () => {
formBaselineSnapshot.value = serializeFormForCompare();
if (studyStore.currentStudy?.id === project.value.id) {
studyStore.setCurrentStudy({ ...(studyStore.currentStudy as Study), ...project.value } as Study);
await studyStore.loadCurrentStudyPermissions().catch(() => {});
}
} catch {
// Ignore refresh errors to avoid breaking publish success flow.
@@ -5559,9 +5560,10 @@ const confirmPublishConfig = async () => {
}
};
const enterProject = () => {
const enterProject = async () => {
if (!project.value) return;
studyStore.setCurrentStudy(project.value);
await studyStore.loadCurrentStudyPermissions().catch(() => {});
router.push("/project/overview");
};
const goMembers = () => {
@@ -0,0 +1,16 @@
import { describe, expect, it } from "vitest";
import { readFileSync } from "node:fs";
import { resolve } from "node:path";
const readProjectPermissions = () => readFileSync(resolve(__dirname, "./ProjectPermissions.vue"), "utf8");
describe("project permissions matrix", () => {
it("locks management backend permissions to admin and PM roles", () => {
const source = readProjectPermissions();
expect(source).toContain('new Set(["project_members", "sites", "audit_export"])');
expect(source).toContain('role === "PM" || role === "ADMIN"');
expect(source).toContain("!canConfigureAdminModule(role, mod.key)");
expect(source).toContain("!canConfigureAdminModule(role, moduleKey)");
});
});
@@ -0,0 +1,475 @@
<template>
<div class="permission-page">
<div class="permission-shell unified-shell" v-loading="loading">
<div class="permission-header unified-action-bar">
<div class="permission-title">
<div class="title-icon">
<el-icon><Key /></el-icon>
</div>
<div>
<h2>权限管理</h2>
</div>
</div>
<div class="permission-project-meta">
<span class="meta-item">
<span class="meta-label">项目编号</span>
<strong>{{ project?.code || "-" }}</strong>
</span>
<span class="meta-separator" />
<span class="meta-item meta-item--name">
<span class="meta-label">项目名称</span>
<strong>{{ project?.name || "-" }}</strong>
</span>
</div>
<div class="permission-actions">
<el-button type="primary" :loading="saving" :disabled="!dirty" @click="save">
<el-icon><Check /></el-icon>
保存
</el-button>
</div>
</div>
<section class="permission-matrix unified-section">
<div class="matrix-scroll">
<div class="matrix-grid" :style="{ '--module-count': modules.length }">
<div class="matrix-head matrix-role-head">角色</div>
<div v-for="mod in modules" :key="mod.key" class="matrix-head module-head" :class="{ 'is-admin-module': isAdminModule(mod.key) }">
<span>{{ mod.label }}</span>
</div>
<template v-for="role in roleOrder" :key="role">
<div class="role-cell">
<span class="role-badge" :class="`role-badge--${role.toLowerCase()}`">
{{ roleLabel(role) }}
</span>
</div>
<div v-for="mod in modules" :key="`${role}-${mod.key}`" class="permission-cell" :class="{ 'is-admin-module': isAdminModule(mod.key), 'is-readonly-module': !isWriteSupported(mod) }">
<label class="perm-check" :class="{ 'is-checked': matrix[role]?.[mod.key]?.read, 'is-disabled': isReadLocked(role, mod) }">
<input
type="checkbox"
:disabled="isReadLocked(role, mod)"
:checked="!!matrix[role]?.[mod.key]?.read"
@change="setPermission(role, mod.key, 'read', ($event.target as HTMLInputElement).checked)"
/>
<span class="check-box" />
<span></span>
</label>
<label v-if="isWriteSupported(mod)" class="perm-check" :class="{ 'is-checked': matrix[role]?.[mod.key]?.write, 'is-disabled': isWriteLocked(role, mod) }">
<input
type="checkbox"
:disabled="isWriteLocked(role, mod)"
:checked="!!matrix[role]?.[mod.key]?.write"
@change="setPermission(role, mod.key, 'write', ($event.target as HTMLInputElement).checked)"
/>
<span class="check-box" />
<span></span>
</label>
</div>
</template>
</div>
</div>
</section>
</div>
</div>
</template>
<script setup lang="ts">
import { computed, onMounted, ref } from "vue";
import { useRoute } from "vue-router";
import { ElMessage } from "element-plus";
import { Check, Key } from "@element-plus/icons-vue";
import { fetchStudyDetail } from "../../api/studies";
import { fetchProjectRolePermissions, updateProjectRolePermissions } from "../../api/projectPermissions";
import type { ProjectPermissionActionState, ProjectPermissionMatrix, ProjectPermissionModule, Study, UserRole } from "../../types/api";
import { displayEnum } from "../../utils/display";
import { TEXT } from "../../locales";
const route = useRoute();
const projectId = computed(() => route.params.projectId as string);
const roleOrder: UserRole[] = ["ADMIN", "PM", "CRA", "PV", "IMP", "QA"];
const loading = ref(false);
const saving = ref(false);
const project = ref<Study | null>(null);
const modules = ref<ProjectPermissionModule[]>([]);
const matrix = ref<ProjectPermissionMatrix>({} as ProjectPermissionMatrix);
const initialSnapshot = ref("");
const roleLabel = (role: UserRole) => displayEnum(TEXT.enums.userRole, role);
const adminModuleKeys = new Set(["project_members", "sites", "audit_export"]);
const isAdminModule = (moduleKey: string) => adminModuleKeys.has(moduleKey);
const canConfigureAdminModule = (role: UserRole, moduleKey: string) => !isAdminModule(moduleKey) || role === "PM" || role === "ADMIN";
const isWriteSupported = (mod: ProjectPermissionModule) => mod.writable !== false;
const findModule = (moduleKey: string) => modules.value.find((mod) => mod.key === moduleKey);
const isReadLocked = (role: UserRole, mod?: ProjectPermissionModule) => role === "ADMIN" || (mod ? !canConfigureAdminModule(role, mod.key) : false);
const isWriteLocked = (role: UserRole, mod: ProjectPermissionModule) => role === "ADMIN" || !isWriteSupported(mod) || !canConfigureAdminModule(role, mod.key);
const normalizeMatrix = (source: ProjectPermissionMatrix): ProjectPermissionMatrix => {
const normalized = {} as ProjectPermissionMatrix;
for (const role of roleOrder) {
normalized[role] = {};
for (const mod of modules.value) {
const item = source?.[role]?.[mod.key] || { read: false, write: false };
const canWrite = isWriteSupported(mod);
const canConfigure = canConfigureAdminModule(role, mod.key);
const write = role === "ADMIN" ? canWrite : canConfigure && canWrite ? !!item.write : false;
const read = role === "ADMIN" ? true : canConfigure && (!!item.read || write);
normalized[role][mod.key] = { read, write };
}
}
return normalized;
};
const snapshot = (source: ProjectPermissionMatrix) => JSON.stringify(normalizeMatrix(source));
const dirty = computed(() => snapshot(matrix.value) !== initialSnapshot.value);
const ensureCell = (role: UserRole, moduleKey: string): ProjectPermissionActionState => {
if (!matrix.value[role]) matrix.value[role] = {};
if (!matrix.value[role][moduleKey]) matrix.value[role][moduleKey] = { read: false, write: false };
return matrix.value[role][moduleKey];
};
const setPermission = (role: UserRole, moduleKey: string, action: "read" | "write", value: boolean) => {
const mod = findModule(moduleKey);
if (role === "ADMIN" || !mod || !canConfigureAdminModule(role, moduleKey) || (action === "write" && !isWriteSupported(mod))) return;
const cell = ensureCell(role, moduleKey);
cell[action] = value;
if (action === "write" && value) cell.read = true;
if (action === "read" && !value) cell.write = false;
};
const load = async () => {
if (!projectId.value) return;
loading.value = true;
try {
const [projectResp, permissionResp] = await Promise.all([
fetchStudyDetail(projectId.value),
fetchProjectRolePermissions(projectId.value),
]);
project.value = projectResp.data;
modules.value = permissionResp.data.modules;
matrix.value = normalizeMatrix(permissionResp.data.roles);
initialSnapshot.value = snapshot(matrix.value);
} catch (error: any) {
ElMessage.error(error?.response?.data?.detail || "加载权限失败");
} finally {
loading.value = false;
}
};
const save = async () => {
if (!projectId.value) return;
saving.value = true;
try {
const payload = { roles: normalizeMatrix(matrix.value) };
const { data } = await updateProjectRolePermissions(projectId.value, payload);
modules.value = data.modules;
matrix.value = normalizeMatrix(data.roles);
initialSnapshot.value = snapshot(matrix.value);
ElMessage.success("权限已保存");
} catch (error: any) {
ElMessage.error(error?.response?.data?.detail || "保存权限失败");
} finally {
saving.value = false;
}
};
onMounted(load);
</script>
<style scoped>
.permission-page {
display: flex;
flex-direction: column;
}
.permission-shell {
background: transparent;
}
.permission-header {
display: grid;
grid-template-columns: minmax(220px, 1fr) auto minmax(220px, 1fr);
align-items: center;
justify-content: space-between;
min-height: 52px;
padding-top: 10px;
padding-bottom: 10px;
}
.permission-title {
display: flex;
align-items: center;
gap: 10px;
}
.title-icon {
display: grid;
place-items: center;
width: 34px;
height: 34px;
border-radius: 8px;
color: #0f766e;
background: #e7f8f5;
border: 1px solid #b9ebe2;
}
.permission-title h2 {
margin: 0;
font-size: 18px;
line-height: 1.2;
color: #172033;
}
.permission-project-meta {
display: flex;
align-items: center;
gap: 14px;
max-width: min(720px, 48vw);
color: #172033;
white-space: nowrap;
justify-self: center;
}
.meta-item {
display: inline-flex;
align-items: center;
gap: 8px;
min-width: 0;
}
.meta-item--name strong {
overflow: hidden;
text-overflow: ellipsis;
}
.meta-label {
color: #64748b;
font-size: 12px;
font-weight: 600;
}
.meta-item strong {
min-width: 0;
font-size: 14px;
font-weight: 800;
}
.meta-separator {
width: 1px;
height: 18px;
background: #dbe3ee;
}
.permission-actions {
display: flex;
align-items: center;
gap: 8px;
margin-left: auto;
justify-content: flex-end;
justify-self: end;
}
.permission-actions :deep(.el-button) {
height: 30px;
padding: 0 12px;
font-size: 12px;
}
.permission-matrix {
padding: 0;
overflow: hidden;
}
.matrix-scroll {
overflow-x: auto;
}
.matrix-grid {
--module-count: 6;
display: grid;
grid-template-columns: 108px repeat(var(--module-count), minmax(82px, 1fr));
min-width: 1320px;
border-top: 1px solid #e6ebf2;
border-left: 1px solid #e6ebf2;
}
.matrix-head,
.role-cell,
.permission-cell {
border-right: 1px solid #e6ebf2;
border-bottom: 1px solid #e6ebf2;
background: #fff;
}
.matrix-head {
min-height: 46px;
padding: 8px 10px;
background: #f8fafc;
color: #334155;
font-weight: 700;
font-size: 13px;
}
.matrix-head.is-admin-module {
position: relative;
background: #fff7ed;
color: #9a3412;
}
.matrix-head.is-admin-module::before {
content: "";
position: absolute;
left: 0;
top: 0;
width: 100%;
height: 3px;
background: #f97316;
}
.matrix-role-head {
display: flex;
align-items: center;
}
.module-head {
display: flex;
flex-direction: column;
justify-content: center;
}
.role-cell {
display: flex;
align-items: center;
padding: 8px 10px;
}
.permission-cell {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 6px;
padding: 7px 8px;
}
.permission-cell.is-admin-module {
background: #fffaf3;
}
.role-badge {
display: inline-flex;
align-items: center;
justify-content: center;
min-width: 68px;
padding: 4px 10px;
border-radius: 999px;
font-weight: 700;
font-size: 12px;
}
.role-badge--admin {
color: #1d4ed8;
background: #dbeafe;
}
.role-badge--pm {
color: #047857;
background: #d1fae5;
}
.role-badge--cra {
color: #7c3aed;
background: #ede9fe;
}
.role-badge--pv {
color: #be123c;
background: #ffe4e6;
}
.role-badge--imp {
color: #b45309;
background: #fef3c7;
}
.role-badge--qa {
color: #475569;
background: #e2e8f0;
}
.perm-check {
position: relative;
display: inline-flex;
align-items: center;
gap: 5px;
min-width: 48px;
color: #64748b;
font-weight: 700;
font-size: 12px;
cursor: pointer;
user-select: none;
}
.perm-check input {
position: absolute;
opacity: 0;
pointer-events: none;
}
.check-box {
width: 15px;
height: 15px;
border-radius: 5px;
border: 1.5px solid #cbd5e1;
background: #fff;
box-shadow: inset 0 0 0 1.5px #fff;
}
.perm-check.is-checked {
color: #1d4ed8;
}
.perm-check.is-checked .check-box {
border-color: #2563eb;
background: #2563eb;
}
.perm-check.is-checked .check-box::after {
content: "";
display: block;
width: 6px;
height: 3px;
margin: 3px auto 0;
border-left: 1.8px solid #fff;
border-bottom: 1.8px solid #fff;
transform: rotate(-45deg);
}
.perm-check.is-disabled {
cursor: not-allowed;
opacity: 0.58;
}
@media (max-width: 860px) {
.permission-header,
.permission-title,
.permission-actions {
align-items: stretch;
}
.permission-header {
flex-direction: column;
gap: 14px;
}
.permission-project-meta {
max-width: none;
white-space: normal;
}
.permission-actions {
margin-left: 0;
}
}
</style>
+27 -11
View File
@@ -30,12 +30,15 @@
<el-tag v-else type="success" effect="plain" round>未锁定</el-tag>
</template>
</el-table-column>
<el-table-column :label="TEXT.common.labels.actions" width="240" align="center">
<el-table-column :label="TEXT.common.labels.actions" width="176" align="center">
<template #default="scope">
<div class="action-row">
<el-tooltip :content="TEXT.modules.adminProjects.members" placement="top">
<el-button link type="primary" :icon="User" class="action-btn" @click="goMembers(scope.row)" />
</el-tooltip>
<el-tooltip content="权限管理" placement="top">
<el-button link type="primary" :icon="Key" class="action-btn" @click="goPermissions(scope.row)" />
</el-tooltip>
<el-tooltip :content="TEXT.modules.adminProjects.sites" placement="top">
<el-button link type="primary" :icon="OfficeBuilding" class="action-btn" @click="goSites(scope.row)" />
</el-tooltip>
@@ -68,7 +71,7 @@
import { onMounted, ref } from "vue";
import { useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import { User, OfficeBuilding, ArrowRight, Delete, Lock } from "@element-plus/icons-vue";
import { User, OfficeBuilding, ArrowRight, Delete, Lock, Key } from "@element-plus/icons-vue";
import { fetchStudies, deleteStudy, lockStudy } from "../../api/studies";
import type { Study } from "../../types/api";
import ProjectForm from "./ProjectForm.vue";
@@ -108,6 +111,10 @@ const goSites = (row: Study) => {
router.push(`/admin/projects/${row.id}/sites`);
};
const goPermissions = (row: Study) => {
router.push(`/admin/projects/${row.id}/permissions`);
};
const handleDelete = async (study: Study) => {
try {
// 第一次确认
@@ -197,8 +204,9 @@ const handleLockToggle = async (study: Study) => {
}
};
const enterStudy = (row: Study) => {
const enterStudy = async (row: Study) => {
studyStore.setCurrentStudy(row);
await studyStore.loadCurrentStudyPermissions().catch(() => {});
router.push("/project/overview");
};
@@ -244,7 +252,8 @@ onMounted(() => {
.action-row {
display: inline-flex;
align-items: center;
gap: 10px;
gap: 4px;
justify-content: center;
white-space: nowrap;
}
@@ -263,20 +272,27 @@ onMounted(() => {
}
.action-btn {
font-size: 18px;
padding: 4px;
margin: 0 2px;
transition: all 0.3s;
width: 28px;
height: 28px;
min-height: 28px;
font-size: 16px;
padding: 0;
margin: 0;
border-radius: 4px;
transition: background-color 0.2s, color 0.2s, transform 0.2s;
}
.action-row :deep(.el-button + .el-button) {
margin-left: 0;
}
.action-btn:hover {
transform: scale(1.1);
transform: translateY(-1px);
background-color: #f3f4f6;
border-radius: 4px;
}
.enter-btn {
font-size: 18px;
font-size: 16px;
font-weight: bold;
}
</style>