fix: 补上清单里还没对上的登录拒绝、会话回退和代理清理

This commit is contained in:
2026-11-16 16:46:37 +08:00
parent a1e2b6e65c
commit 3cff9dc37a
19 changed files with 223 additions and 65 deletions
+20 -7
View File
@@ -1,5 +1,6 @@
<script setup lang="ts">
import { onMounted, ref } from "vue";
import { onMounted, onUnmounted, ref } from "vue";
import { apiFetch, setSessionDenied } from "./shared/http";
import { darkTheme, dateZhCN, NButton, NConfigProvider, NDialogProvider, zhCN } from "naive-ui";
import LoginView from "./features/auth/LoginView.vue";
import Shell from "./shell/Shell.vue";
@@ -18,7 +19,7 @@ function applyPayload(payload: unknown) {
async function loadSession() {
try {
const response = await fetch("/api/session");
const response = await apiFetch("/api/session");
if (response.status === 401) {
session.value = null;
sessionError.value = "";
@@ -43,12 +44,24 @@ async function loadSession() {
}
onMounted(() => {
setSessionDenied(() => {
void loadSession();
});
void loadSession();
window.addEventListener("focus", onWindowFocus);
});
onUnmounted(() => {
window.removeEventListener("focus", onWindowFocus);
});
function onWindowFocus() {
void loadSession();
}
async function exitSystem() {
try {
const response = await fetch("/api/logout", { method: "POST" });
const response = await apiFetch("/api/logout", { method: "POST" });
if (!response.ok) {
sessionError.value = "没有退出。";
return;
@@ -62,7 +75,7 @@ async function exitSystem() {
async function revokeAccount() {
try {
const response = await fetch("/api/revoke", { method: "POST" });
const response = await apiFetch("/api/revoke", { method: "POST" });
if (!response.ok) {
sessionError.value = "没有注销。";
return;
@@ -76,7 +89,7 @@ async function revokeAccount() {
async function exitAdmin() {
try {
const response = await fetch("/api/admin/logout", { method: "POST" });
const response = await apiFetch("/api/admin/logout", { method: "POST" });
if (!response.ok) {
sessionError.value = "没有退出。";
return;
@@ -111,8 +124,8 @@ function onLogin(next: AppSession) {
<n-button size="small" @click="loadSession">重试</n-button>
</div>
<LoginView v-if="!session" @success="onLogin" />
<Shell v-else-if="session.kind === 'user'" :employee-id="session.employeeId" @logout="exitSystem" @revoke="revokeAccount" />
<AdminShell v-else-if="session.kind === 'admin'" :username="session.username" @logout="exitAdmin" @refresh="loadSession" />
<Shell v-else-if="session.kind === 'user'" :key="session.employeeId" :employee-id="session.employeeId" @logout="exitSystem" @revoke="revokeAccount" />
<AdminShell v-else-if="session.kind === 'admin'" :key="session.username" :username="session.username" @logout="exitAdmin" @refresh="loadSession" />
</div>
</n-dialog-provider>
</n-config-provider>
+3 -2
View File
@@ -1,4 +1,5 @@
<script setup lang="ts">
import { apiFetch } from "../../shared/http";
import { computed, onMounted, onUnmounted, ref } from "vue";
import { NAlert, NButton, NIcon, NInput, NPagination, NTooltip } from "naive-ui";
import { DownloadOutline } from "@vicons/ionicons5";
@@ -71,7 +72,7 @@ async function load(clamp = true) {
offset: String((page.value - 1) * pageSize.value),
limit: String(pageSize.value),
});
const response = await fetch(`/api/admin/courses?${params}`);
const response = await apiFetch(`/api/admin/courses?${params}`);
if (disposed || seq !== loadSeq) return;
const payload = await response.json().catch(() => ({}));
if (disposed || seq !== loadSeq) return;
@@ -126,7 +127,7 @@ async function loadCourses() {
setError("");
fetching.value = true;
try {
const response = await fetch("/api/admin/courses/load", { method: "POST" });
const response = await apiFetch("/api/admin/courses/load", { method: "POST" });
await response.json().catch(() => ({}));
if (!response.ok) {
fetching.value = false;
+7 -6
View File
@@ -1,4 +1,5 @@
<script setup lang="ts">
import { apiFetch } from "../../shared/http";
import { computed, onMounted, onUnmounted, ref } from "vue";
import { NAlert, NButton, NIcon, NInput, NPagination, NSpin, NTooltip } from "naive-ui";
import { RefreshOutline } from "@vicons/ionicons5";
@@ -124,7 +125,7 @@ async function load(clamp = true) {
offset: String((page.value - 1) * pageSize.value),
limit: String(pageSize.value),
});
const response = await fetch(`/api/admin/proxies?${params}`);
const response = await apiFetch(`/api/admin/proxies?${params}`);
if (disposed || seq !== loadSeq) return;
const payload: unknown = await response.json().catch(() => ({}));
if (disposed || seq !== loadSeq) return;
@@ -186,7 +187,7 @@ async function probeOne(row: ProxyRow) {
probingId.value = row.id;
setError("");
try {
const response = await fetch(`/api/admin/proxies/${row.id}/probe`, { method: "POST" });
const response = await apiFetch(`/api/admin/proxies/${row.id}/probe`, { method: "POST" });
const payload: unknown = await response.json().catch(() => ({}));
if (!response.ok) {
setError("没有测出延迟。");
@@ -217,7 +218,7 @@ async function filteredIds() {
offset: String(offset),
limit: String(limit),
});
const response = await fetch(`/api/admin/proxies?${params}`);
const response = await apiFetch(`/api/admin/proxies?${params}`);
const payload: unknown = await response.json().catch(() => ({}));
if (!response.ok || !isRecord(payload) || !Array.isArray(payload.items)) {
throw new Error("代理列表没有获取到。");
@@ -240,7 +241,7 @@ async function probeAll() {
setError("没有可测试的代理。");
return;
}
const response = await fetch("/api/admin/proxies/probe", {
const response = await apiFetch("/api/admin/proxies/probe", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(ids ? { ids } : {}),
@@ -252,7 +253,7 @@ async function probeAll() {
}
for (let attempt = 0; attempt < 120; attempt += 1) {
if (disposed) return;
const status = await fetch("/api/admin/proxies/probe");
const status = await apiFetch("/api/admin/proxies/probe");
const body: unknown = await status.json().catch(() => ({}));
if (!status.ok || !isRecord(body)) break;
if (body.running !== true) {
@@ -273,7 +274,7 @@ async function refreshNow() {
setError("");
fetching.value = true;
try {
const response = await fetch("/api/admin/proxies/refresh", { method: "POST" });
const response = await apiFetch("/api/admin/proxies/refresh", { method: "POST" });
await response.json().catch(() => ({}));
if (!response.ok) {
fetching.value = false;
+3 -2
View File
@@ -1,4 +1,5 @@
<script setup lang="ts">
import { apiFetch } from "../../shared/http";
import { onMounted, onUnmounted, ref } from "vue";
import { NAlert, NButton, NForm, NFormItem, NInput, NInputNumber, NRadioButton, NRadioGroup, NSwitch } from "naive-ui";
@@ -54,7 +55,7 @@ onUnmounted(() => window.clearTimeout(savedTimer));
onMounted(async () => {
try {
const response = await fetch("/api/admin/settings");
const response = await apiFetch("/api/admin/settings");
const payload = await response.json().catch(() => ({}));
if (!response.ok || !payload || typeof payload !== "object") {
errorText.value = detailOf(payload, "系统配置没有获取到。");
@@ -151,7 +152,7 @@ async function save() {
}
saving.value = true;
try {
const response = await fetch("/api/admin/settings", {
const response = await apiFetch("/api/admin/settings", {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body),
+27 -12
View File
@@ -1,4 +1,5 @@
<script setup lang="ts">
import { apiFetch } from "../../shared/http";
import { computed, onMounted, ref } from "vue";
import { NAlert, NButton, NCheckbox, NDropdown, NForm, NFormItem, NIcon, NInputNumber, NModal, NRadioButton, NRadioGroup, NSelect, NTimePicker, NTooltip, useDialog, type DropdownOption } from "naive-ui";
import { EllipsisHorizontalOutline, EllipsisVerticalOutline, PauseOutline, PlayOutline, RefreshOutline, SettingsOutline } from "@vicons/ionicons5";
@@ -249,7 +250,7 @@ function validityClass(text: string) {
async function load() {
loading.value = true;
try {
const response = await fetch("/api/admin/users");
const response = await apiFetch("/api/admin/users");
const payload: unknown = await response.json().catch(() => ({}));
if (!response.ok) {
errorText.value = detailOf(payload, "用户列表没有获取到。");
@@ -277,7 +278,7 @@ async function checkOne(row: UserRow) {
checkingId.value = row.employee_id;
errorText.value = "";
try {
const response = await fetch(`/api/admin/users/${encodeURIComponent(row.employee_id)}/check`, { method: "POST" });
const response = await apiFetch(`/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, "检查失败");
@@ -301,7 +302,7 @@ async function checkAll() {
checkingAll.value = true;
errorText.value = "";
try {
const response = await fetch("/api/admin/users/check-all", { method: "POST" });
const response = await apiFetch("/api/admin/users/check-all", { method: "POST" });
const payload: unknown = await response.json().catch(() => ({}));
if (!response.ok) {
errorText.value = detailOf(payload, "检查失败");
@@ -375,7 +376,7 @@ async function openCredentials(row: UserRow) {
credentialLoading.value = true;
credentialOpen.value = true;
try {
const response = await fetch(`/api/admin/users/${encodeURIComponent(row.employee_id)}/credentials`);
const response = await apiFetch(`/api/admin/users/${encodeURIComponent(row.employee_id)}/credentials`);
const payload: unknown = await response.json().catch(() => ({}));
if (current !== credentialRequest || !credentialOpen.value) return;
if (!response.ok || !isRecord(payload)) {
@@ -393,7 +394,7 @@ async function openCredentials(row: UserRow) {
async function setPaused(row: UserRow, paused: boolean) {
errorText.value = "";
try {
const response = await fetch(`/api/admin/users/${encodeURIComponent(row.employee_id)}/refresh`, {
const response = await apiFetch(`/api/admin/users/${encodeURIComponent(row.employee_id)}/refresh`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ paused }),
@@ -423,7 +424,7 @@ function confirmRefresh(row: UserRow) {
async function removeUser(row: UserRow) {
errorText.value = "";
try {
const response = await fetch(`/api/admin/users/${encodeURIComponent(row.employee_id)}`, { method: "DELETE" });
const response = await apiFetch(`/api/admin/users/${encodeURIComponent(row.employee_id)}`, { method: "DELETE" });
const payload: unknown = await response.json().catch(() => ({}));
if (!response.ok) {
errorText.value = detailOf(payload, "没有删除。");
@@ -516,11 +517,25 @@ async function openSettings(ids: string[]) {
const row = users.value.find((item) => item.employee_id === employeeId);
if (row) applyRowSettings(row);
try {
const response = await fetch(`/api/admin/users/${encodeURIComponent(employeeId)}/proxy`);
const [usersResponse, proxyResponse] = await Promise.all([
apiFetch("/api/admin/users"),
apiFetch(`/api/admin/users/${encodeURIComponent(employeeId)}/proxy`),
]);
if (current !== settingsRequest || !settingsOpen.value) return;
const payload: unknown = await response.json().catch(() => ({}));
const usersPayload: unknown = await usersResponse.json().catch(() => null);
const payload: unknown = await proxyResponse.json().catch(() => ({}));
if (current !== settingsRequest || !settingsOpen.value) return;
if (!response.ok || !isRecord(payload)) {
if (!usersResponse.ok || !Array.isArray(usersPayload)) {
settingsError.value = "学习设置没有获取到,不能保存。";
return;
}
const fresh = usersPayload.map(asUser).find((item) => item?.employee_id === employeeId);
if (!fresh) {
settingsError.value = "学习设置没有获取到,不能保存。";
return;
}
applyRowSettings(fresh);
if (!proxyResponse.ok || !isRecord(payload)) {
settingsError.value = "代理没有获取到,不能保存。";
return;
}
@@ -652,7 +667,7 @@ async function saveSettings() {
}
settingsSaving.value = true;
try {
const response = await fetch("/api/admin/users/study-settings", {
const response = await apiFetch("/api/admin/users/study-settings", {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
@@ -703,7 +718,7 @@ async function setStudy(ids: string[], action: "start" | "stop") {
studyBusy.value = true;
errorText.value = "";
try {
const response = await fetch("/api/admin/users/study", {
const response = await apiFetch("/api/admin/users/study", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ employee_ids: ids, action }),
@@ -737,7 +752,7 @@ async function clearProxy(ids: string[]) {
if (!ids.length) return;
errorText.value = "";
try {
const response = await fetch("/api/admin/users/proxy/clear", {
const response = await apiFetch("/api/admin/users/proxy/clear", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ employee_ids: ids }),
+6 -5
View File
@@ -1,4 +1,5 @@
<script setup lang="ts">
import { apiFetch } from "../../shared/http";
import { computed, onUnmounted, ref, watch } from "vue";
import { NAlert, NButton, NCheckbox, NIcon, NInput, NTooltip } from "naive-ui";
import { ChevronForward, MoonOutline, SunnyOutline } from "@vicons/ionicons5";
@@ -94,7 +95,7 @@ onUnmounted(() => {
async function loadConfig() {
try {
const response = await fetch("/api/login-config");
const response = await apiFetch("/api/login-config");
const payload = await response.json().catch(() => ({}));
if (response.ok && payload && typeof payload === "object") {
showManual.value = Boolean((payload as { show_manual_checkbox?: unknown }).show_manual_checkbox);
@@ -193,7 +194,7 @@ async function startQr() {
qrArmed.value = false;
submitting.value = true;
try {
const response = await fetch("/api/login/qr", { method: "POST" });
const response = await apiFetch("/api/login/qr", { method: "POST" });
const payload = await response.json().catch(() => ({})) as LoginPayload;
if (!response.ok) {
errorText.value = readableDetail(payload.detail, "二维码没有获取到");
@@ -225,7 +226,7 @@ async function pollQr() {
if (!attemptId.value || submitting.value || polling) return;
polling = true;
try {
const response = await fetch("/api/login/qr/poll", {
const response = await apiFetch("/api/login/qr/poll", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ attempt_id: attemptId.value }),
@@ -271,7 +272,7 @@ async function submit() {
errorText.value = "";
submitting.value = true;
try {
const response = await fetch("/api/login", {
const response = await apiFetch("/api/login", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
@@ -305,7 +306,7 @@ async function sendOffset() {
submitting.value = true;
errorText.value = "";
try {
const response = await fetch("/api/login/jigsaw", {
const response = await apiFetch("/api/login/jigsaw", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ attempt_id: attemptId.value, offset: offset.value }),
+3 -2
View File
@@ -1,4 +1,5 @@
<script setup lang="ts">
import { apiFetch } from "../../shared/http";
import { onMounted, ref } from "vue";
import { NAlert, NButton, NIcon, NModal, NTooltip } from "naive-ui";
import { RefreshOutline } from "@vicons/ionicons5";
@@ -52,7 +53,7 @@ async function load() {
const hadData = items.value !== null;
if (!hadData) state.value = "loading";
try {
const response = await fetch("/api/home/exams");
const response = await apiFetch("/api/home/exams");
const payload = await response.json().catch(() => ({}));
if (!response.ok) {
errorText.value = "考试列表没有获取到。";
@@ -98,7 +99,7 @@ async function openDetail(item: ExamItem) {
}
detailLoading.value = true;
try {
const response = await fetch(`/api/exam?${new URLSearchParams({ path: item.detail })}`);
const response = await apiFetch(`/api/exam?${new URLSearchParams({ path: item.detail })}`);
const payload = await response.json().catch(() => ({}));
if (current !== detailRequest) return;
if (!response.ok) {
@@ -1,4 +1,5 @@
<script setup lang="ts">
import { apiFetch } from "../../shared/http";
import { computed, h, onMounted, ref } from "vue";
import { NAlert, NButton, NDataTable, NIcon, NPagination, NTooltip, type DataTableColumns } from "naive-ui";
import { RefreshOutline } from "@vicons/ionicons5";
@@ -21,6 +22,7 @@ type SectionState = "loading" | "ready" | "error";
const items = ref<HistoryItem[] | null>(null);
const hours = ref<HistoryHours | null>(null);
const historyLimited = ref(false);
const state = ref<SectionState>("loading");
const errorText = ref("");
const refreshing = ref(false);
@@ -69,7 +71,7 @@ async function load() {
const hadData = items.value !== null;
if (!hadData) state.value = "loading";
try {
const response = await fetch("/api/home/history");
const response = await apiFetch("/api/home/history");
const payload = await response.json().catch(() => ({})) as Record<string, unknown>;
if (!response.ok) {
errorText.value = "学时历史没有获取到。";
@@ -94,6 +96,7 @@ async function load() {
today_hours: asHour(payload.today_hours),
total_hours: asHour(payload.total_hours),
};
historyLimited.value = payload.limited === true;
errorText.value = "";
state.value = "ready";
const maxPage = Math.max(1, Math.ceil(parsed.length / pageSize.value));
@@ -178,6 +181,7 @@ onMounted(refresh);
<div>
<h2>学时历史</h2>
<p v-if="items">共 {{ items.length }} 条</p>
<p v-if="historyLimited">只统计了最近 50 页</p>
</div>
<n-tooltip placement="bottom">
<template #trigger>
+13 -9
View File
@@ -1,4 +1,5 @@
<script setup lang="ts">
import { apiFetch } from "../../shared/http";
import { computed, onMounted, onUnmounted, ref, watch } from "vue";
import { NAlert, NButton, NForm, NFormItem, NIcon, NInputNumber, NModal, NProgress, NSelect, NSwitch, NTimePicker, NTooltip } from "naive-ui";
import { GlobeOutline, PlayOutline, RefreshOutline, StopOutline } from "@vicons/ionicons5";
@@ -17,6 +18,7 @@ interface HomeSummary {
total_hours: string;
total_score: string;
points: string | number | null;
limited?: boolean;
}
interface StudyWorker {
@@ -165,6 +167,7 @@ function asSummary(value: unknown): HomeSummary | null {
total_hours: String(text("total_hours") ?? ""),
total_score: String(text("total_score") ?? ""),
points: typeof row.points === "number" || typeof row.points === "string" ? row.points : null,
limited: row.limited === true,
};
}
@@ -241,7 +244,7 @@ async function loadSummary() {
const hadData = summary.value !== null;
if (!hadData) summaryState.value = "loading";
try {
const response = await fetch("/api/home/summary");
const response = await apiFetch("/api/home/summary");
const payload = await response.json().catch(() => ({}));
if (!response.ok) {
summaryError.value = "个人学习信息没有获取到。";
@@ -280,7 +283,7 @@ function refresh() {
async function loadTarget() {
try {
const res = await fetch("/api/settings/monthly-target");
const res = await apiFetch("/api/settings/monthly-target");
if (!res.ok) return false;
const data = await res.json();
monthlyTarget.value = data.monthly_target ?? 600;
@@ -314,7 +317,7 @@ const startTime = computed({
async function loadStart() {
try {
const res = await fetch("/api/settings/study-start");
const res = await apiFetch("/api/settings/study-start");
if (!res.ok) return false;
const data = await res.json();
startDay.value = typeof data.day === "number" ? data.day : STUDY_DAY_DEFAULT;
@@ -335,7 +338,7 @@ const scheduleReady = computed(() => targetLoaded.value && startLoaded.value &&
async function loadWorkers() {
try {
const res = await fetch("/api/settings/course-workers");
const res = await apiFetch("/api/settings/course-workers");
if (!res.ok) return false;
const data = await res.json();
courseWorkers.value = typeof data.workers === "number" ? data.workers : 1;
@@ -347,7 +350,7 @@ async function loadWorkers() {
}
async function putJson(url: string, body: Record<string, unknown>, fallback: string) {
const res = await fetch(url, {
const res = await apiFetch(url, {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body),
@@ -451,7 +454,7 @@ const proxyOptions = [
async function loadProxy() {
try {
const res = await fetch("/api/settings/proxy");
const res = await apiFetch("/api/settings/proxy");
const data = await res.json().catch(() => ({}));
if (!res.ok) return false;
proxyScheme.value = typeof data.scheme === "string" && data.scheme ? data.scheme : "off";
@@ -499,7 +502,7 @@ async function saveProxy() {
}
proxySaving.value = true;
try {
const res = await fetch("/api/settings/proxy", {
const res = await apiFetch("/api/settings/proxy", {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(
@@ -566,7 +569,7 @@ function applyStudyControl(payload: Record<string, unknown>) {
async function loadStudyControl() {
try {
const res = await fetch("/api/settings/study-control");
const res = await apiFetch("/api/settings/study-control");
if (res.status === 401) {
stopStudySocket();
return;
@@ -743,7 +746,7 @@ async function toggleStudy() {
studyError.value = "";
const action = studyControl.value.started ? "stop" : "start";
try {
const res = await fetch("/api/settings/study-control", {
const res = await apiFetch("/api/settings/study-control", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ action }),
@@ -830,6 +833,7 @@ onUnmounted(() => {
</dd>
</div>
</dl>
<p v-if="summary?.limited" class="study-live-hint">只统计了最近 50 页</p>
</section>
<section class="panel-card study-card" :class="{ 'is-busy': studyingWorkers.length > 0 }">
+3 -2
View File
@@ -1,4 +1,5 @@
<script setup lang="ts">
import { apiFetch } from "../../shared/http";
import { onMounted, ref } from "vue";
import { NAlert, NButton, NIcon, NModal, NTooltip } from "naive-ui";
import { RefreshOutline } from "@vicons/ionicons5";
@@ -68,7 +69,7 @@ async function load() {
const hadData = items.value !== null;
if (!hadData) state.value = "loading";
try {
const response = await fetch("/api/home/trainings");
const response = await apiFetch("/api/home/trainings");
const payload = await response.json().catch(() => ({}));
if (!response.ok) {
errorText.value = "培训列表没有获取到。";
@@ -114,7 +115,7 @@ async function openDetail(item: TrainingItem) {
}
detailLoading.value = true;
try {
const response = await fetch(`/api/training?${new URLSearchParams({ path: item.detail })}`);
const response = await apiFetch(`/api/training?${new URLSearchParams({ path: item.detail })}`);
const payload = await response.json().catch(() => ({}));
if (current !== detailRequest) return;
if (!response.ok) {
+28
View File
@@ -0,0 +1,28 @@
type Denied = () => void;
let onDenied: Denied | null = null;
export function setSessionDenied(handler: Denied) {
onDenied = handler;
}
function requestUrl(input: RequestInfo | URL) {
if (typeof input === "string") return input;
if (input instanceof URL) return input.href;
return input.url;
}
export async function apiFetch(input: RequestInfo | URL, init?: RequestInit) {
const response = await fetch(input, init);
if (requestUrl(input).includes("/api/session")) return response;
if (response.status === 401) {
onDenied?.();
return response;
}
if (response.status === 403) {
const body = await response.clone().json().catch(() => null);
const detail = body && typeof body === "object" ? (body as { detail?: unknown }).detail : "";
if (detail === "管理员不能访问该接口") onDenied?.();
}
return response;
}