调整系统管理入口并实现用户分组与角色可见范围

This commit is contained in:
xuans committed 2026-09-25 22:15:52 +08:00
1 parent c91aab659b
commit 5bcada2ac8
28 files changed
+915 -72

No files matched your search

+2 -2
View File
@@ -1,6 +1,6 @@
<script setup>
import { useAppShell } from "./App.js";
import AccessDenied from "./views/AccessDenied/AccessDenied.vue";
import UserWorkspace from "./views/UserManagement/UserWorkspace.vue";
import Dashboard from "./views/Dashboard/Dashboard.vue";
import Login from "./views/Login/Login.vue";
import PasswordReset from "./views/PasswordReset/PasswordReset.vue";
@@ -46,7 +46,7 @@ const {
<Login v-else-if="setupState && authenticated === false" />
<AccessDenied
<UserWorkspace
v-else-if="setupState && authenticated === true && isAdmin === false"
/>
@@ -29,6 +29,9 @@ test("用户管理导航按权限显示,权限变化后回到基本信息", ()
navigation.selectSection("users");
assert.equal(navigation.activeSection.value, "users");
user.value = { role: "admin" };
assert.equal(navigation.activeSection.value, "users");
assert.equal(navigation.sections.value.length, 6);
user.value = null;
assert.equal(navigation.activeSection.value, "overview");
assert.equal(navigation.sections.value.length, 5);
});
+1 -5
View File
@@ -1,5 +1,4 @@
<script setup>
import ChangePassword from "../components/ChangePassword/ChangePassword.vue";
import UserManagement from "../UserManagement/UserManagement.vue";
import SettingsModal from "./SettingsModal.vue";
import DomainModal from "./DomainModal.vue";
@@ -145,16 +144,12 @@ const { activeSection, activeLabel, sections, selectSection } = useDashboardNavi
<h1>证书管理总览</h1>
</div>
<div class="topbar-actions">
<ChangePassword />
<button class="secondary-button" type="button" @click="loadData">
刷新状态
</button>
<button v-if="activeSection === 'activity'" class="secondary-button" type="button" @click="runRenewalNow">
立即检查续期
</button>
<button class="secondary-button" type="button" @click="openSettings">
系统设置
</button>
<button
class="secondary-button"
type="button"
@@ -504,6 +499,7 @@ const { activeSection, activeLabel, sections, selectSection } = useDashboardNavi
:active-section="activeSection"
:sections="sections"
@select="selectSection"
@settings="openSettings"
/>
</div>
@@ -12,7 +12,7 @@ export const dashboardSections = [
export function useDashboardNavigation(currentUser) {
const selectedSection = ref("overview");
const sections = computed(() => dashboardSections.filter(
(section) => section.id !== "users" || currentUser.value?.role === "super_admin",
(section) => section.id !== "users" || ["super_admin", "admin"].includes(currentUser.value?.role),
));
const activeSection = computed(() => sections.value.some(
(section) => section.id === selectedSection.value,
@@ -4,7 +4,7 @@ defineProps({
sections: { type: Array, required: true },
});
defineEmits(["select"]);
defineEmits(["select", "settings"]);
</script>
<template>
@@ -55,6 +55,18 @@ defineEmits(["select"]);
<i v-if="activeSection === section.id" class="navigation-current" aria-hidden="true"></i>
</button>
</template>
<button
class="navigation-item"
type="button"
title="配置服务、证书签发和邮件通知"
aria-haspopup="dialog"
@click="$emit('settings')"
>
<svg viewBox="0 0 24 24" fill="none" aria-hidden="true">
<path d="M4 7h16M4 17h16M8 4v6M16 14v6" />
</svg>
<span>系统设置</span>
</button>
<p class="navigation-footer">SSL 证书管理</p>
</nav>
</template>
@@ -0,0 +1,30 @@
import { ref } from "vue";
export function useUserGroupEditor(props, emit) {
const groupName = ref("");
const groupError = ref("");
function addGroup() {
const name = groupName.value.trim();
groupError.value = "";
if (!name || name === "默认分组" || [...name].length > 32 || /[\u0000-\u001f\u007f-\u009f]/u.test(name)) {
groupError.value = "请输入 1 到 32 个字符的分组名称;默认分组无需添加";
return;
}
const groups = [...new Set([...props.modelValue, name])];
if (props.role === "user" && groups.length > 1) {
groupError.value = "普通用户只能属于一个分组,请先移除原分组";
return;
}
if (groups.length > 32) {
groupError.value = "分组数量不能超过 32 个";
return;
}
emit("update:modelValue", groups);
groupName.value = "";
}
function removeGroup(name) {
emit("update:modelValue", props.modelValue.filter((item) => item !== name));
groupError.value = "";
}
return { groupName, groupError, addGroup, removeGroup };
}
@@ -0,0 +1,46 @@
<script setup>
import HelpTip from "../components/HelpTip/HelpTip.vue";
import { useUserGroupEditor } from "./UserGroupEditor.js";
const props = defineProps({
modelValue: { type: Array, required: true },
availableGroups: { type: Array, default: () => [] },
role: { type: String, required: true },
});
const emit = defineEmits(["update:modelValue"]);
const { groupName, groupError, addGroup, removeGroup } = useUserGroupEditor(props, emit);
</script>
<template>
<fieldset class="group-editor">
<legend>
所属分组
<HelpTip>未选择时归入默认分组。管理员可属于多个分组,普通用户最多一个分组。分组名称区分大小写。</HelpTip>
</legend>
<div class="group-selection">
<span v-if="!modelValue.length" class="user-badge">默认分组</span>
<button v-for="name in modelValue" :key="name" type="button" :aria-label="`移除分组 ${name}`" @click="removeGroup(name)">
{{ name }} ×
</button>
</div>
<div class="group-input-row">
<input
v-model="groupName"
type="text"
list="user-group-options"
aria-label="选择或新建分组"
placeholder="选择或输入分组名称"
maxlength="32"
@keydown.enter.prevent="addGroup"
/>
<datalist id="user-group-options">
<option v-for="name in availableGroups" :key="name" :value="name" />
</datalist>
<button type="button" class="secondary-button" @click="addGroup">添加到分组</button>
</div>
<p v-if="groupError" class="form-error" role="alert">{{ groupError }}</p>
<p v-else-if="role === 'user' && modelValue.length > 1" class="form-error" role="alert">普通用户只能属于一个分组,请移除多余分组后保存。</p>
</fieldset>
</template>
<style scoped src="./UserManagement.css"></style>
@@ -1,5 +1,79 @@
.user-management {
margin-top: 18px;
padding: 24px;
border: 1px solid #e2e8f2;
border-radius: 20px;
background: rgba(255, 255, 255, 0.86);
}
.user-groups {
display: grid;
gap: 12px;
}
.user-group {
min-width: 0;
border: 1px solid #e2e8f2;
border-radius: 12px;
overflow: hidden;
}
.user-group-heading {
margin: 0;
padding: 12px 16px;
color: #32405a;
background: #f7faff;
font-size: 14px;
}
summary.user-group-heading {
cursor: pointer;
}
.user-group-heading span {
margin-left: 12px;
color: #71809a;
font-size: 12px;
font-weight: 400;
}
.user-group-empty {
margin: 0;
padding: 16px;
color: #71809a;
font-size: 13px;
}
.group-editor {
margin: 16px 0;
padding: 12px;
border: 1px solid #d5ddea;
border-radius: 10px;
}
.group-editor legend {
color: #394963;
font-size: 13px;
}
.group-selection,
.group-input-row {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 8px;
margin: 8px 0;
}
.group-input-row input {
flex: 1;
min-width: 120px;
padding: 10px;
border: 1px solid #d5ddea;
border-radius: 8px;
}
.group-selection button {
border: 1px solid #d5ddea;
padding: 5px 8px;
border-radius: 6px;
color: #315aaa;
background: #edf3ff;
cursor: pointer;
}
.user-group-heading:focus-visible,
.user-table-wrap:focus-visible {
outline: 2px solid #315aaa;
outline-offset: -2px;
}
.user-management-heading {
display: flex;
@@ -11,8 +11,27 @@ const statusLabels = {
disabled: "已禁用",
};
export function groupUsers(users) {
const groups = new Map();
const defaults = { name: "默认分组", isDefault: true, users: [] };
for (const user of users) {
const names = [...new Set(user.groups || [])];
if (!names.length) defaults.users.push(user);
for (const name of names) {
if (!groups.has(name)) groups.set(name, { name, isDefault: false, users: [] });
groups.get(name).users.push(user);
}
}
return [defaults, ...[...groups.values()].sort((a, b) => a.name.localeCompare(b.name, "zh-CN"))];
}
export function useUserManagement() {
const visible = ref(false);
const visible = ref(true);
const currentRole = ref("");
const canManage = computed(() => currentRole.value === "super_admin");
const showGroups = computed(() => ["super_admin", "admin"].includes(currentRole.value));
const groupedUsers = computed(() => groupUsers(users.value));
const availableGroups = computed(() => groupedUsers.value.filter((group) => !group.isDefault).map((group) => group.name));
const users = ref([]);
const loading = ref(false);
const saving = ref(false);
@@ -54,6 +73,7 @@ export function useUserManagement() {
const result = await response.json().catch(() => ({}));
if (!response.ok) throw new Error(result.error || "读取用户列表失败");
users.value = result.items || [];
currentRole.value = result.current_role || "";
visible.value = true;
} catch (err) {
if (err.message !== "登录会话已过期,请重新登录") {
@@ -71,10 +91,12 @@ export function useUserManagement() {
password: "",
role: "user",
status: "active",
groups: [],
};
}
function openCreate() {
if (!canManage.value) return;
editingId.value = "";
editingRole.value = "";
form.value = createEmptyForm();
@@ -83,7 +105,7 @@ export function useUserManagement() {
}
function openEdit(item) {
if (isPrimaryAccount(item)) return;
if (!canManage.value || isPrimaryAccount(item)) return;
editingId.value = item.id;
editingRole.value = item.role;
form.value = {
@@ -92,6 +114,7 @@ export function useUserManagement() {
password: "",
role: item.role || "user",
status: item.status || "active",
groups: [...(item.groups || [])],
};
formError.value = "";
showForm.value = true;
@@ -103,11 +126,19 @@ export function useUserManagement() {
async function saveUser() {
formError.value = "";
if (!canManage.value) {
formError.value = "只有超级管理员可以修改用户";
return;
}
if (editingId.value === "primary-super-admin") {
formError.value = "主超级管理员不能通过用户管理修改";
return;
}
const payload = { ...form.value };
if (payload.role.trim().toLowerCase() === "user" && payload.groups.length > 1) {
formError.value = "普通用户只能属于一个分组,请保留一个分组或清空为默认分组";
return;
}
if (payload.role.trim().toLowerCase() === "super_admin" && editingRole.value !== "super_admin") {
formError.value = "不能新增或提升为超级管理员";
return;
@@ -143,7 +174,7 @@ export function useUserManagement() {
}
async function toggleStatus(item) {
if (isPrimaryAccount(item)) return;
if (!canManage.value || isPrimaryAccount(item)) return;
const nextStatus = item.status === "active" ? "disabled" : "active";
if (item.role === "super_admin" && nextStatus === "disabled") {
notice.value = "最后一个超级管理员不能被禁用";
@@ -169,6 +200,7 @@ export function useUserManagement() {
}
async function deleteUser(item) {
if (!canManage.value) return;
if (isPrimaryAccount(item)) return;
if (!window.confirm(`确定删除用户“${item.username}”吗?`)) return;
try {
@@ -191,6 +223,11 @@ export function useUserManagement() {
onMounted(loadUsers);
return {
currentRole,
canManage,
showGroups,
groupedUsers,
availableGroups,
visible,
users,
loading,
@@ -1,13 +1,14 @@
import assert from "node:assert/strict";
import test from "node:test";
import { useUserManagement } from "./UserManagement.js";
import { groupUsers, useUserManagement } from "./UserManagement.js";
import { useUserGroupEditor } from "./UserGroupEditor.js";
import { mountComposable } from "../../test-support/mount.js";
async function setup(t) {
const calls = [];
const mounted = await mountComposable(t, useUserManagement, async (path, options) => {
calls.push({ path, options });
return Response.json({ items: [] });
return Response.json({ items: [], current_role: "super_admin" });
});
calls.length = 0;
return { ...mounted, calls };
@@ -51,3 +52,89 @@ test("管理员和普通用户仍能正常创建及编辑", async (t) => {
assert.deepEqual(writes.map(({ options }) => options.method), ["POST", "PUT", "POST", "PUT"]);
assert.equal(state.formError.value, "");
});
test("默认分组置顶,多组管理员同时出现在所属分组且不重复", () => {
const members = [
{ id: "multi", groups: ["乙组", "甲组", "甲组"] },
{ id: "single", groups: ["甲组"] },
{ id: "default" },
];
const result = groupUsers(members);
assert.equal(result[0].isDefault, true);
assert.deepEqual(result[0].users.map((user) => user.id), ["default"]);
assert.equal(result.find((group) => group.name === "甲组").users.length, 2);
assert.equal(result.find((group) => group.name === "乙组").users.length, 1);
});
test("管理员只能读取成员,普通用户不显示分组,未知权限默认关闭写入", async (t) => {
for (const role of ["admin", "user", ""]) {
const writes = [];
const { state } = await mountComposable(t, useUserManagement, async (path, options) => {
if (options.method) writes.push(path);
return Response.json({ items: [], current_role: role });
});
assert.equal(state.canManage.value, false);
assert.equal(state.showGroups.value, role === "admin");
state.openCreate();
state.openEdit({ id: "member", role: "user" });
assert.equal(state.showForm.value, false);
await state.saveUser();
await state.toggleStatus({ id: "member", status: "active" });
await state.deleteUser({ id: "member" });
assert.deepEqual(writes, []);
}
});
test("普通用户不允许多组,降级时保留选择供用户修正", async (t) => {
const { state, calls } = await setup(t);
state.openEdit({ id: "leader", username: "leader", role: "admin", groups: ["甲组", "乙组"] });
state.form.value.role = "user";
await state.saveUser();
assert.match(state.formError.value, /只能属于一个分组/);
assert.deepEqual(state.form.value.groups, ["甲组", "乙组"]);
assert.equal(calls.length, 0);
state.form.value.groups = ["乙组"];
await state.saveUser();
assert.deepEqual(JSON.parse(calls.find((call) => call.options.method === "PUT").options.body).groups, ["乙组"]);
});
test("分组编辑器支持管理员多组并拒绝普通用户多组及保留名称", () => {
const props = { modelValue: [], role: "admin" };
const editor = useUserGroupEditor(props, (_, value) => { props.modelValue = value; });
for (const name of [" 甲组 ", "乙组", "甲组"]) {
editor.groupName.value = name;
editor.addGroup();
}
assert.deepEqual(props.modelValue, ["甲组", "乙组"]);
props.role = "user";
editor.groupName.value = "丙组";
editor.addGroup();
assert.match(editor.groupError.value, /只能属于一个分组/);
editor.removeGroup("乙组");
assert.deepEqual(props.modelValue, ["甲组"]);
editor.groupName.value = "默认分组";
editor.addGroup();
assert.match(editor.groupError.value, /默认分组无需添加/);
});
test("分组页面结构可编译,默认组不折叠,命名组默认关闭,密码入口仅在用户管理", async () => {
const { readFile } = await import("node:fs/promises");
const { parse, compileScript, compileTemplate } = await import("@vue/compiler-sfc");
for (const file of ["UserManagement.vue", "UserTable.vue", "UserGroupEditor.vue", "UserWorkspace.vue"]) {
const source = await readFile(new URL(file, import.meta.url), "utf8");
const { descriptor, errors } = parse(source);
assert.deepEqual(errors, []);
assert.ok(compileScript(descriptor, { id: file }));
assert.deepEqual(compileTemplate({ source: descriptor.template.content, filename: file, id: file }).errors, []);
}
const source = await readFile(new URL("UserManagement.vue", import.meta.url), "utf8");
assert.match(source, /section v-if="group.isDefault"/);
assert.match(source, /<details v-else class="user-group">/);
assert.match(source, /v-else-if="showGroups"/);
assert.match(source, /<ChangePassword/);
const dashboard = await readFile(new URL("../Dashboard/Dashboard.vue", import.meta.url), "utf8");
const navigation = await readFile(new URL("../Dashboard/DashboardNavigation.vue", import.meta.url), "utf8");
assert.doesNotMatch(dashboard, /<ChangePassword/);
assert.doesNotMatch(dashboard, /@click="openSettings"/);
assert.match(navigation, /\$emit\('settings'\)/);
});
@@ -1,8 +1,15 @@
<script setup>
import HelpTip from "../components/HelpTip/HelpTip.vue";
import { useUserManagement } from "./UserManagement.js";
import ChangePassword from "../components/ChangePassword/ChangePassword.vue";
import UserTable from "./UserTable.vue";
import UserGroupEditor from "./UserGroupEditor.vue";
const {
canManage,
showGroups,
groupedUsers,
availableGroups,
visible,
users,
loading,
@@ -38,10 +45,11 @@ const {
</HelpTip>
</div>
<div class="user-management-actions">
<ChangePassword />
<button class="secondary-button" type="button" :disabled="loading" @click="loadUsers">
{{ loading ? "读取中……" : "刷新列表" }}
</button>
<button class="primary-button" type="button" @click="openCreate">添加用户</button>
<button v-if="canManage" class="primary-button" type="button" @click="openCreate">添加用户</button>
</div>
</div>
@@ -49,42 +57,37 @@ const {
<p v-if="notice" class="user-message notice-message">{{ notice }}</p>
<div v-if="loading && users.length === 0" class="user-empty">正在读取用户列表……</div>
<div v-else-if="users.length === 0" class="user-empty">暂无数据库用户,配置中的超级管理员仍可登录。</div>
<div v-else class="user-table-wrap">
<table class="user-table">
<thead>
<tr>
<th>账号</th>
<th>邮箱</th>
<th>角色</th>
<th>状态</th>
<th>创建时间</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<tr v-for="item in users" :key="item.id">
<td><strong>{{ item.username }}</strong></td>
<td>{{ item.email || "未绑定" }}</td>
<td><span class="user-badge">{{ roleLabels[item.role] || item.role }}</span></td>
<td><span class="user-status" :class="item.status">{{ statusLabels[item.status] || item.status }}</span></td>
<td>{{ new Date(item.created_at).toLocaleString("zh-CN") }}</td>
<td>
<span v-if="isPrimaryAccount(item)" class="user-badge">受保护账号</span>
<div v-else class="user-row-actions">
<button class="text-button" type="button" @click="openEdit(item)">编辑</button>
<button class="text-button" type="button" @click="toggleStatus(item)">
{{ item.status === "active" ? "禁用" : "启用" }}
</button>
<button v-if="item.role !== 'super_admin'" class="text-button danger-text" type="button" @click="deleteUser(item)">删除</button>
</div>
</td>
</tr>
</tbody>
</table>
<div v-else-if="showGroups" class="user-groups">
<template v-for="group in groupedUsers" :key="group.name">
<section v-if="group.isDefault" class="user-group default-group" aria-label="默认分组">
<h3 class="user-group-heading">默认分组 <span>{{ group.users.length }} 人</span></h3>
<UserTable
:users="group.users"
:can-manage="canManage"
:role-labels="roleLabels"
:status-labels="statusLabels"
@edit="openEdit"
@toggle="toggleStatus"
@delete="deleteUser"
/>
</section>
<details v-else class="user-group">
<summary class="user-group-heading">{{ group.name }} <span>{{ group.users.length }} 人</span></summary>
<UserTable
:users="group.users"
:can-manage="canManage"
:role-labels="roleLabels"
:status-labels="statusLabels"
@edit="openEdit"
@toggle="toggleStatus"
@delete="deleteUser"
/>
</details>
</template>
</div>
<UserTable v-else :users="users" :role-labels="roleLabels" :status-labels="statusLabels" />
<div v-if="showForm" class="modal-backdrop" @click.self="closeForm">
<div v-if="showForm && canManage" class="modal-backdrop" @click.self="closeForm">
<section class="modal-card user-modal" role="dialog" aria-modal="true" :aria-label="formTitle">
<div class="modal-heading">
<div>
@@ -125,6 +128,7 @@ const {
</select>
</label>
</div>
<UserGroupEditor v-model="form.groups" :role="form.role" :available-groups="availableGroups" />
<p v-if="formError" class="form-error">{{ formError }}</p>
<div class="modal-actions">
<button class="secondary-button" type="button" :disabled="saving" @click="closeForm">取消</button>
@@ -0,0 +1,48 @@
<script setup>
defineProps({
users: { type: Array, required: true },
canManage: { type: Boolean, default: false },
roleLabels: { type: Object, required: true },
statusLabels: { type: Object, required: true },
});
defineEmits(["edit", "toggle", "delete"]);
</script>
<template>
<p v-if="!users.length" class="user-group-empty">暂无成员</p>
<div v-else class="user-table-wrap" tabindex="0" aria-label="用户列表">
<table class="user-table">
<thead>
<tr>
<th scope="col">账号</th>
<th scope="col">邮箱</th>
<th scope="col">角色</th>
<th scope="col">状态</th>
<th scope="col">创建时间</th>
<th v-if="canManage" scope="col">操作</th>
</tr>
</thead>
<tbody>
<tr v-for="item in users" :key="item.id">
<td><strong>{{ item.username }}</strong></td>
<td>{{ item.email || "未绑定" }}</td>
<td><span class="user-badge">{{ roleLabels[item.role] || item.role }}</span></td>
<td><span class="user-status" :class="item.status">{{ statusLabels[item.status] || item.status }}</span></td>
<td>{{ new Date(item.created_at).toLocaleString("zh-CN") }}</td>
<td v-if="canManage">
<span v-if="item.id === 'primary-super-admin'" class="user-badge">受保护账号</span>
<div v-else class="user-row-actions">
<button class="text-button" type="button" @click="$emit('edit', item)">编辑</button>
<button class="text-button" type="button" @click="$emit('toggle', item)">
{{ item.status === "active" ? "禁用" : "启用" }}
</button>
<button v-if="item.role !== 'super_admin'" class="text-button danger-text" type="button" @click="$emit('delete', item)">删除</button>
</div>
</td>
</tr>
</tbody>
</table>
</div>
</template>
<style scoped src="./UserManagement.css"></style>
@@ -0,0 +1,26 @@
.user-workspace {
max-width: 1180px;
margin: 0 auto;
padding: 28px;
}
.user-workspace header {
display: flex;
align-items: center;
justify-content: space-between;
gap: 16px;
}
.user-workspace h1 {
color: #25344d;
font-size: 26px;
}
.user-workspace button {
padding: 10px 16px;
border: 1px solid #d5ddea;
border-radius: 10px;
color: #32405a;
background: #fff;
cursor: pointer;
}
@@ -0,0 +1,21 @@
<script setup>
import UserManagement from "./UserManagement.vue";
import { useAccessDenied } from "../AccessDenied/AccessDenied.js";
const { loggingOut, error, logout } = useAccessDenied();
</script>
<template>
<main class="user-workspace">
<header>
<h1>Scert 用户中心</h1>
<button type="button" :disabled="loggingOut" @click="logout">
{{ loggingOut ? "正在退出……" : "退出登录" }}
</button>
</header>
<p v-if="error" role="alert">{{ error }}</p>
<UserManagement />
</main>
</template>
<style scoped src="./UserWorkspace.css"></style>