feat: 增加管理后台,登录后按身份进入用户管理或系统配置

This commit is contained in:
Nixevol
2026-10-28 03:55:53 +08:00
parent ad52207a93
commit 5895141926
8 changed files with 898 additions and 14 deletions
+359
View File
@@ -0,0 +1,359 @@
<script setup lang="ts">
import { onMounted, ref } from "vue";
import { NAlert, NButton, NModal, useDialog } from "naive-ui";
interface UserRow {
employee_id: string;
has_credential: boolean;
refresh_paused: boolean;
last_refresh_at: string | null;
credential_valid: boolean | null;
}
interface SecretField {
label: string;
value: string;
}
const dialog = useDialog();
const loading = ref(true);
const errorText = ref("");
const users = ref<UserRow[]>([]);
const liveResults = ref<Record<string, string>>({});
const checkingId = ref("");
const checkingAll = ref(false);
const credentialOpen = ref(false);
const credentialTitle = ref("凭据");
const credentialLoading = ref(false);
const credentialError = ref("");
const credentialNote = ref("");
const credentialFields = ref<SecretField[]>([]);
const tokenFields: { label: string; key: string }[] = [
{ label: "统一认证 token", key: "ucs_token" },
{ label: "账号标识", key: "ucs_account_id" },
{ label: "用户标识", key: "ucs_user_id" },
{ label: "ssoinfo", key: "ucs_ssoinfo" },
{ label: "unionId", key: "ucs_union_id" },
{ label: "学习平台 token", key: "yxt_token" },
];
function isRecord(value: unknown): value is Record<string, unknown> {
return !!value && typeof value === "object" && !Array.isArray(value);
}
function detailOf(payload: unknown, fallback: string) {
if (isRecord(payload) && typeof payload.detail === "string" && payload.detail) return payload.detail;
return fallback;
}
function textOf(value: unknown) {
return typeof value === "string" ? value : "";
}
function readValid(value: unknown): boolean | null {
if (value === true) return true;
if (value === false) return false;
return null;
}
function asUser(value: unknown): UserRow | null {
if (!isRecord(value) || (typeof value.employee_id !== "string" && typeof value.employee_id !== "number")) return null;
return {
employee_id: String(value.employee_id),
has_credential: value.has_credential === true,
refresh_paused: value.refresh_paused === true,
last_refresh_at: typeof value.last_refresh_at === "string" && value.last_refresh_at ? value.last_refresh_at : null,
credential_valid: readValid(value.credential_valid),
};
}
function formatRefreshTime(value: string | null) {
if (!value) return "";
const date = new Date(value);
if (Number.isNaN(date.getTime())) return value;
const pad = (part: number) => String(part).padStart(2, "0");
return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`;
}
function checkLabel(payload: Record<string, unknown>) {
const result = payload.result;
if (result === "有效" || result === "已失效" || result === "检查失败") return result;
if (result === "未保存" || result === "未保存凭证") return "未保存凭证";
return "检查失败";
}
function validityText(row: UserRow) {
const live = liveResults.value[row.employee_id];
if (live) return live;
if (row.refresh_paused) return "未检查";
if (row.credential_valid === true) return "有效";
if (row.credential_valid === false) return "已失效";
return "未检查";
}
function validityClass(text: string) {
if (text === "有效") return "ok";
if (text === "已失效" || text === "检查失败") return "late";
return "quiet";
}
async function load() {
loading.value = true;
try {
const response = await fetch("/api/admin/users");
const payload: unknown = await response.json().catch(() => ({}));
if (!response.ok) {
errorText.value = detailOf(payload, "用户列表没有获取到。");
return;
}
if (!Array.isArray(payload)) {
errorText.value = detailOf(payload, "用户列表没有获取到。");
return;
}
errorText.value = "";
users.value = payload.map(asUser).filter((item): item is UserRow => item !== null);
} catch {
errorText.value = "用户列表没有获取到。";
} finally {
loading.value = false;
}
}
function remember(employeeId: string, label: string) {
liveResults.value = { ...liveResults.value, [employeeId]: label };
}
async function checkOne(row: UserRow) {
if (checkingId.value || checkingAll.value) return;
checkingId.value = row.employee_id;
errorText.value = "";
try {
const response = await fetch(`/api/admin/users/${encodeURIComponent(row.employee_id)}/check`, { method: "POST" });
const payload: unknown = await response.json().catch(() => ({}));
if (!response.ok || !isRecord(payload)) {
remember(row.employee_id, "检查失败");
errorText.value = detailOf(payload, "检查失败");
return;
}
const label = checkLabel(payload);
remember(row.employee_id, label);
errorText.value = label === "检查失败" ? detailOf(payload, "") : "";
} catch {
remember(row.employee_id, "检查失败");
errorText.value = "检查失败";
} finally {
checkingId.value = "";
}
}
async function checkAll() {
if (checkingId.value || checkingAll.value || !users.value.length) return;
checkingAll.value = true;
errorText.value = "";
try {
const response = await fetch("/api/admin/users/check-all", { method: "POST" });
const payload: unknown = await response.json().catch(() => ({}));
if (!response.ok) {
errorText.value = detailOf(payload, "检查失败");
return;
}
if (!Array.isArray(payload)) {
errorText.value = detailOf(payload, "检查失败");
return;
}
const next = { ...liveResults.value };
const notes: string[] = [];
for (const item of payload) {
if (!isRecord(item) || item.employee_id == null) continue;
const employeeId = String(item.employee_id);
const label = checkLabel(item);
next[employeeId] = label;
if (label === "检查失败") {
const detail = typeof item.detail === "string" ? item.detail : "";
if (detail) notes.push(`${employeeId}:${detail}`);
}
}
liveResults.value = next;
errorText.value = notes.join(";");
} catch {
errorText.value = "检查失败";
} finally {
checkingAll.value = false;
}
}
function resetCredential() {
credentialFields.value = [];
credentialNote.value = "";
credentialError.value = "";
}
function applyCredential(payload: Record<string, unknown>) {
const note = textOf(payload.detail);
const password = textOf(payload.password);
const tokens = tokenFields.map((item) => ({ label: item.label, value: textOf(payload[item.key]) }));
const hasToken = tokens.some((item) => item.value !== "");
if (note && !hasToken) {
credentialNote.value = note;
credentialFields.value = password ? [{ label: "密码", value: password }] : [];
return;
}
credentialNote.value = "";
credentialFields.value = [{ label: "密码", value: password }, ...tokens];
}
function onCredentialShow(show: boolean) {
credentialOpen.value = show;
if (!show) resetCredential();
}
async function openCredentials(row: UserRow) {
credentialTitle.value = `工号 ${row.employee_id} 的凭据`;
resetCredential();
credentialLoading.value = true;
credentialOpen.value = true;
try {
const response = await fetch(`/api/admin/users/${encodeURIComponent(row.employee_id)}/credentials`);
const payload: unknown = await response.json().catch(() => ({}));
if (!response.ok || !isRecord(payload)) {
credentialError.value = detailOf(payload, "凭据没有获取到。");
return;
}
applyCredential(payload);
} catch {
credentialError.value = "凭据没有获取到。";
} finally {
credentialLoading.value = false;
}
}
async function setPaused(row: UserRow, paused: boolean) {
errorText.value = "";
try {
const response = await fetch(`/api/admin/users/${encodeURIComponent(row.employee_id)}/refresh`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ paused }),
});
const payload: unknown = await response.json().catch(() => ({}));
if (!response.ok) {
errorText.value = detailOf(payload, "自动刷新没有改成。");
return;
}
row.refresh_paused = paused;
} catch {
errorText.value = "自动刷新没有改成。";
}
}
function confirmRefresh(row: UserRow) {
const paused = !row.refresh_paused;
dialog.warning({
title: paused ? "停止自动刷新" : "恢复自动刷新",
content: paused ? `停止工号 ${row.employee_id} 的自动刷新?` : `恢复工号 ${row.employee_id} 的自动刷新?`,
positiveText: paused ? "停止" : "恢复",
negativeText: "取消",
onPositiveClick: () => setPaused(row, paused),
});
}
async function removeUser(row: UserRow) {
errorText.value = "";
try {
const response = await fetch(`/api/admin/users/${encodeURIComponent(row.employee_id)}`, { method: "DELETE" });
const payload: unknown = await response.json().catch(() => ({}));
if (!response.ok) {
errorText.value = detailOf(payload, "没有删除。");
return;
}
users.value = users.value.filter((item) => item.employee_id !== row.employee_id);
const next = { ...liveResults.value };
delete next[row.employee_id];
liveResults.value = next;
} catch {
errorText.value = "没有删除。";
}
}
function confirmDelete(row: UserRow) {
dialog.warning({
title: "删除用户",
content: `删除工号 ${row.employee_id}?`,
positiveText: "删除",
negativeText: "取消",
positiveButtonProps: { type: "error" },
onPositiveClick: () => removeUser(row),
});
}
onMounted(() => {
void load();
});
</script>
<template>
<section class="page admin-page">
<header class="page-head">
<h2>用户管理</h2>
<n-button :loading="checkingAll" :disabled="checkingAll || checkingId !== '' || !users.length" @click="checkAll">检查全部</n-button>
</header>
<n-alert v-if="errorText" class="admin-alert" type="error">{{ errorText }}</n-alert>
<div class="admin-scroll">
<p v-if="loading" class="admin-status">正在获取</p>
<table v-else-if="users.length" class="admin-table">
<thead>
<tr>
<th>工号</th>
<th>凭证</th>
<th>凭据是否有效</th>
<th>上次刷新时间</th>
<th>自动刷新</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<tr v-for="row in users" :key="row.employee_id">
<td class="employee">{{ row.employee_id }}</td>
<td>{{ row.has_credential ? "已保存凭证" : "未保存凭证" }}</td>
<td :class="validityClass(validityText(row))">{{ validityText(row) }}</td>
<td class="when">{{ formatRefreshTime(row.last_refresh_at) }}</td>
<td>{{ row.refresh_paused ? "已停止" : "开启" }}</td>
<td>
<div class="row-actions">
<n-button size="small" :loading="checkingId === row.employee_id" :disabled="checkingAll || checkingId !== ''" @click="checkOne(row)">检查</n-button>
<n-button size="small" @click="openCredentials(row)">查看凭据</n-button>
<n-button size="small" @click="confirmRefresh(row)">{{ row.refresh_paused ? "恢复自动刷新" : "停止自动刷新" }}</n-button>
<n-button size="small" type="error" quaternary @click="confirmDelete(row)">删除</n-button>
</div>
</td>
</tr>
</tbody>
</table>
<p v-else-if="!errorText" class="admin-status">没有用户</p>
</div>
<n-modal
:show="credentialOpen"
preset="card"
:title="credentialTitle"
:style="{ width: 'min(720px, calc(100vw - 32px))' }"
:content-style="{ maxHeight: 'min(70vh, 640px)', overflow: 'auto' }"
@update:show="onCredentialShow"
>
<p v-if="credentialLoading" class="admin-status">正在获取</p>
<n-alert v-else-if="credentialError" type="error">{{ credentialError }}</n-alert>
<div v-else>
<p v-if="credentialNote" class="credential-note">{{ credentialNote }}</p>
<div v-for="field in credentialFields" :key="field.label" class="secret-field">
<div class="secret-label">{{ field.label }}</div>
<div class="secret-value">{{ field.value }}</div>
</div>
</div>
<template #footer>
<div class="modal-actions">
<n-button @click="credentialOpen = false">关闭</n-button>
</div>
</template>
</n-modal>
</section>
</template>