feat: 增加管理首页运行面板并支持用户改密
This commit is contained in:
+1
-1
@@ -29,7 +29,7 @@ Vue 3、TypeScript、Naive UI。Node.js 只用于安装依赖、本地开发和
|
||||
## Capabilities and Constraints
|
||||
|
||||
- 用户功能:提交任务,取得结果文件。多个任务可以并行,也可以排队。
|
||||
- 管理功能:选择登录方式,管理用户,管理大数据平台账号池,设置凭证刷新间隔和并行数量,手动添加账号。并行数量范围是 1 到 32,采集和导出共用。调大后马上多领任务。调小后不中断正在运行的任务,等它们结束后再降到新的数量。
|
||||
- 管理功能:首页运行面板查看账号池指标(总数、新增、有效、失效、未退出、地市分布)。选择登录方式,管理用户,管理大数据平台账号池,设置凭证刷新间隔和并行数量,手动添加账号。并行数量范围是 1 到 32,采集和导出共用。调大后马上多领任务。调小后不中断正在运行的任务,等它们结束后再降到新的数量。用户管理可为用户角色改密;管理员账号只能由本人修改。
|
||||
- 登录先看账号名。账号名与本系统管理员一致时,只校验本系统密码,不处理图形验证码,也不交给大数据平台。密码不正确就停在这里。
|
||||
- 其余账号只启用一种登录方式。大数据平台登录时,登录页直接显示图形验证码,登录失败后更换验证码;登录成功后该账号进入账号池。自有账号由管理员添加,不能自行注册,登录不显示验证码,也不发送手机验证码。
|
||||
- 操作结果用 toast 提示。最短显示 2.5 秒;超过 6 个字后,每多一个字加 0.3 秒;最长 8 秒。每条可以单独关闭。
|
||||
|
||||
@@ -2,6 +2,7 @@ from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import os
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from fastapi.responses import Response
|
||||
@@ -390,6 +391,28 @@ def delete_user(user_id: int, actor: Actor = Depends(current_actor), session: Se
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
@router.put("/admin/users/{user_id}/password")
|
||||
def update_user_password(user_id: int, body: dict, actor: Actor = Depends(current_actor), session: Session = Depends(get_session)) -> dict:
|
||||
require_admin(actor)
|
||||
user = session.get(User, user_id)
|
||||
if user is None:
|
||||
raise _bad("账号不存在", 404)
|
||||
password = str(body.get("password") or "")
|
||||
if not password:
|
||||
raise _bad("请填写密码")
|
||||
if not _can_set_user_password(actor, user):
|
||||
raise _bad("管理员账号只能由本人修改")
|
||||
user.password_hash = hash_password(password)
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
@router.get("/admin/dashboard")
|
||||
def admin_dashboard(actor: Actor = Depends(current_actor), session: Session = Depends(get_session)) -> dict:
|
||||
require_admin(actor)
|
||||
rows = session.scalars(select(NqiAccount)).all()
|
||||
return {"pool": _pool_dashboard(rows)}
|
||||
|
||||
|
||||
@router.get("/admin/pool")
|
||||
def list_pool(actor: Actor = Depends(current_actor), session: Session = Depends(get_session)) -> dict:
|
||||
require_admin(actor)
|
||||
@@ -503,6 +526,55 @@ def _public_task(task: ExportTask) -> dict:
|
||||
}
|
||||
|
||||
|
||||
def _can_set_user_password(actor: Actor, user: User) -> bool:
|
||||
if user.role == "user":
|
||||
return True
|
||||
return actor.kind == "local" and actor.id == str(user.id)
|
||||
|
||||
|
||||
def _as_utc(value: datetime | None) -> datetime | None:
|
||||
if value is None:
|
||||
return None
|
||||
if value.tzinfo is None:
|
||||
return value.replace(tzinfo=timezone.utc)
|
||||
return value.astimezone(timezone.utc)
|
||||
|
||||
|
||||
def _pool_dashboard(rows: list[NqiAccount]) -> dict:
|
||||
today = utcnow().date()
|
||||
week_start = today - timedelta(days=6)
|
||||
daily = {(today - timedelta(days=offset)).isoformat(): 0 for offset in range(13, -1, -1)}
|
||||
cities: dict[str, int] = {}
|
||||
added_today = 0
|
||||
added_week = 0
|
||||
for row in rows:
|
||||
saved = _as_utc(row.saved_at)
|
||||
if saved is not None:
|
||||
day = saved.date()
|
||||
key = day.isoformat()
|
||||
if key in daily:
|
||||
daily[key] += 1
|
||||
if day == today:
|
||||
added_today += 1
|
||||
if week_start <= day <= today:
|
||||
added_week += 1
|
||||
city = str(row.city_name or "").strip() or "未填写"
|
||||
cities[city] = cities.get(city, 0) + 1
|
||||
return {
|
||||
"total": len(rows),
|
||||
"valid": sum(1 for row in rows if row.credential_valid),
|
||||
"invalid": sum(1 for row in rows if not row.credential_valid),
|
||||
"sessionOpen": sum(1 for row in rows if row.session_open),
|
||||
"sessionClosed": sum(1 for row in rows if not row.session_open),
|
||||
"addedToday": added_today,
|
||||
"addedWeek": added_week,
|
||||
"userRole": sum(1 for row in rows if row.role == "user"),
|
||||
"adminRole": sum(1 for row in rows if row.role == "admin"),
|
||||
"dailyAdded": [{"date": date, "count": count} for date, count in daily.items()],
|
||||
"cities": [{"name": name, "count": count} for name, count in sorted(cities.items(), key=lambda item: (-item[1], item[0]))],
|
||||
}
|
||||
|
||||
|
||||
def _save_pool(session: Session, user: dict, cookies: list) -> NqiAccount:
|
||||
login_id = str(user.get("loginId") or "").strip()
|
||||
if not login_id:
|
||||
|
||||
@@ -205,6 +205,43 @@ def test_concurrency_bounds():
|
||||
check_concurrency(33)
|
||||
|
||||
|
||||
def test_admin_dashboard_and_user_password(client: TestClient):
|
||||
from datetime import timedelta
|
||||
|
||||
from app.db import session_scope
|
||||
from app.models import NqiAccount, utcnow
|
||||
|
||||
logged = client.post("/api/auth/local", json={"username": "admin", "password": "admin-pass"})
|
||||
headers = {"Authorization": f"Bearer {logged.json()['token']}"}
|
||||
admin_id = logged.json()["user"]["id"]
|
||||
client.post("/api/admin/users", json={"username": "user", "password": "user-pass", "role": "user"}, headers=headers)
|
||||
client.post("/api/admin/users", json={"username": "boss", "password": "boss-pass", "role": "admin"}, headers=headers)
|
||||
rows = client.get("/api/admin/users", headers=headers).json()["users"]
|
||||
user_id = next(row["id"] for row in rows if row["username"] == "user")
|
||||
other_id = next(row["id"] for row in rows if row["username"] == "boss")
|
||||
denied = client.put(f"/api/admin/users/{other_id}/password", json={"password": "hacked"}, headers=headers)
|
||||
assert denied.status_code == 400
|
||||
changed = client.put(f"/api/admin/users/{user_id}/password", json={"password": "new-user-pass"}, headers=headers)
|
||||
assert changed.status_code == 200
|
||||
assert client.post("/api/auth/local", json={"username": "user", "password": "new-user-pass"}).status_code == 200
|
||||
self_ok = client.put(f"/api/admin/users/{admin_id}/password", json={"password": "admin-pass-2"}, headers=headers)
|
||||
assert self_ok.status_code == 200
|
||||
empty = client.get("/api/admin/dashboard", headers=headers)
|
||||
assert empty.status_code == 200
|
||||
assert empty.json()["pool"]["total"] == 0
|
||||
now = utcnow()
|
||||
with session_scope() as session:
|
||||
session.add(NqiAccount(login_id="a1", city_name="广州", credential_valid=True, session_open=True, saved_at=now))
|
||||
session.add(NqiAccount(login_id="a2", city_name="深圳", credential_valid=False, session_open=False, saved_at=now - timedelta(days=2)))
|
||||
stats = client.get("/api/admin/dashboard", headers=headers).json()["pool"]
|
||||
assert stats["total"] == 2
|
||||
assert stats["valid"] == 1
|
||||
assert stats["invalid"] == 1
|
||||
assert stats["addedToday"] == 1
|
||||
assert stats["addedWeek"] == 2
|
||||
assert stats["sessionOpen"] == 1
|
||||
|
||||
|
||||
def test_admin_can_set_concurrency(client: TestClient):
|
||||
logged = client.post("/api/auth/local", json={"username": "admin", "password": "admin-pass"})
|
||||
headers = {"Authorization": f"Bearer {logged.json()['token']}"}
|
||||
|
||||
Generated
+26
@@ -9,6 +9,7 @@
|
||||
"version": "0.1.0",
|
||||
"dependencies": {
|
||||
"@vicons/ionicons5": "^0.13.0",
|
||||
"echarts": "^6.1.0",
|
||||
"naive-ui": "^2.43.2",
|
||||
"vue": "^3.5.13",
|
||||
"vue-router": "^4.5.1"
|
||||
@@ -643,6 +644,16 @@
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/echarts": {
|
||||
"version": "6.1.0",
|
||||
"resolved": "https://registry.npmjs.org/echarts/-/echarts-6.1.0.tgz",
|
||||
"integrity": "sha512-q0yaFPggC9FUdsWH4blavRWFmxdrIodbkoKNAjJudAI6CA9gNPxHtV2RcZNEepZVlk4yvBYkOkbk6HIVpIyHZA==",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"tslib": "2.3.0",
|
||||
"zrender": "6.1.0"
|
||||
}
|
||||
},
|
||||
"node_modules/entities": {
|
||||
"version": "7.0.1",
|
||||
"resolved": "https://registry.npmjs.org/entities/-/entities-7.0.1.tgz",
|
||||
@@ -1186,6 +1197,12 @@
|
||||
"integrity": "sha512-M8RGFoKtZ8dF+iwJfAJTOH/SM4KluKOKRJpjCMhI8bG3qB74zrFoArKZ62ll0Fr3mqkMJiQOmWYkdYgDeITYQg==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/tslib": {
|
||||
"version": "2.3.0",
|
||||
"resolved": "https://registry.npmjs.org/tslib/-/tslib-2.3.0.tgz",
|
||||
"integrity": "sha512-N82ooyxVNm6h1riLCoyS9e3fuJ3AMG2zIZs2Gd1ATcSFjSA23Q0fzjjZeh0jbJvWVDZ0cJT8yaNNaaXHzueNjg==",
|
||||
"license": "0BSD"
|
||||
},
|
||||
"node_modules/typescript": {
|
||||
"version": "6.0.3",
|
||||
"resolved": "https://registry.npmjs.org/typescript/-/typescript-6.0.3.tgz",
|
||||
@@ -1379,6 +1396,15 @@
|
||||
"peerDependencies": {
|
||||
"vue": "^3.0.11"
|
||||
}
|
||||
},
|
||||
"node_modules/zrender": {
|
||||
"version": "6.1.0",
|
||||
"resolved": "https://registry.npmjs.org/zrender/-/zrender-6.1.0.tgz",
|
||||
"integrity": "sha512-oEGMDB6pOP2S6OwRR4PdVv610zrjnA3Bh+JnSG12fYJlBKjtNAoEb5fSUoCOOINlH96I2fU38/A2UpRKs67xYQ==",
|
||||
"license": "BSD-3-Clause",
|
||||
"dependencies": {
|
||||
"tslib": "2.3.0"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,6 +10,7 @@
|
||||
},
|
||||
"dependencies": {
|
||||
"@vicons/ionicons5": "^0.13.0",
|
||||
"echarts": "^6.1.0",
|
||||
"naive-ui": "^2.43.2",
|
||||
"vue": "^3.5.13",
|
||||
"vue-router": "^4.5.1"
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
<script setup lang="ts">
|
||||
import { onMounted, onUnmounted, ref, watch } from "vue";
|
||||
import * as echarts from "echarts/core";
|
||||
import { BarChart, PieChart } from "echarts/charts";
|
||||
import { GridComponent, LegendComponent, TooltipComponent } from "echarts/components";
|
||||
import { CanvasRenderer } from "echarts/renderers";
|
||||
import type { ECharts, EChartsCoreOption } from "echarts/core";
|
||||
|
||||
echarts.use([BarChart, PieChart, GridComponent, LegendComponent, TooltipComponent, CanvasRenderer]);
|
||||
|
||||
const props = defineProps<{ option: EChartsCoreOption }>();
|
||||
const el = ref<HTMLDivElement | null>(null);
|
||||
let chart: ECharts | null = null;
|
||||
|
||||
function render() {
|
||||
if (!el.value) return;
|
||||
if (!chart) chart = echarts.init(el.value);
|
||||
chart.setOption(props.option, true);
|
||||
}
|
||||
|
||||
function resize() {
|
||||
chart?.resize();
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
render();
|
||||
window.addEventListener("resize", resize);
|
||||
});
|
||||
|
||||
onUnmounted(() => {
|
||||
window.removeEventListener("resize", resize);
|
||||
chart?.dispose();
|
||||
chart = null;
|
||||
});
|
||||
|
||||
watch(() => props.option, render, { deep: true });
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div ref="el" class="dash-chart" />
|
||||
</template>
|
||||
@@ -0,0 +1,186 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref } from "vue";
|
||||
import type { EChartsCoreOption } from "echarts/core";
|
||||
import Shell from "../../shell/Shell.vue";
|
||||
import { api } from "../../shared/http";
|
||||
import { isDark } from "../../shared/theme";
|
||||
import { useToast } from "../../shared/toast";
|
||||
import ChartPane from "./ChartPane.vue";
|
||||
|
||||
interface PoolDash {
|
||||
total: number;
|
||||
valid: number;
|
||||
invalid: number;
|
||||
sessionOpen: number;
|
||||
sessionClosed: number;
|
||||
addedToday: number;
|
||||
addedWeek: number;
|
||||
userRole: number;
|
||||
adminRole: number;
|
||||
dailyAdded: { date: string; count: number }[];
|
||||
cities: { name: string; count: number }[];
|
||||
}
|
||||
|
||||
const toast = useToast();
|
||||
const loaded = ref(false);
|
||||
const pool = ref<PoolDash>({
|
||||
total: 0,
|
||||
valid: 0,
|
||||
invalid: 0,
|
||||
sessionOpen: 0,
|
||||
sessionClosed: 0,
|
||||
addedToday: 0,
|
||||
addedWeek: 0,
|
||||
userRole: 0,
|
||||
adminRole: 0,
|
||||
dailyAdded: [],
|
||||
cities: [],
|
||||
});
|
||||
|
||||
const cards = computed(() => [
|
||||
{ label: "账号总数", value: pool.value.total },
|
||||
{ label: "今日新增", value: pool.value.addedToday },
|
||||
{ label: "近7日新增", value: pool.value.addedWeek },
|
||||
{ label: "有效凭证", value: pool.value.valid, tone: "ok" },
|
||||
{ label: "失效凭证", value: pool.value.invalid, tone: pool.value.invalid ? "bad" : "" },
|
||||
{ label: "未退出", value: pool.value.sessionOpen, tone: "run" },
|
||||
]);
|
||||
|
||||
function theme() {
|
||||
const style = getComputedStyle(document.documentElement);
|
||||
return {
|
||||
ink: style.getPropertyValue("--ink").trim() || "#0D1117",
|
||||
muted: style.getPropertyValue("--muted").trim() || "#57606A",
|
||||
line: style.getPropertyValue("--line").trim() || "#D0D7DE",
|
||||
accent: style.getPropertyValue("--accent").trim() || "#0969DA",
|
||||
danger: style.getPropertyValue("--danger").trim() || "#CF222E",
|
||||
ok: style.getPropertyValue("--ok").trim() || "#1A7F37",
|
||||
panel: style.getPropertyValue("--panel").trim() || "#FFFFFF",
|
||||
};
|
||||
}
|
||||
|
||||
function axis(colors: ReturnType<typeof theme>) {
|
||||
return {
|
||||
axisLine: { lineStyle: { color: colors.line } },
|
||||
axisTick: { show: false },
|
||||
axisLabel: { color: colors.muted, fontSize: 11 },
|
||||
splitLine: { lineStyle: { color: colors.line, type: "dashed" as const } },
|
||||
};
|
||||
}
|
||||
|
||||
const dailyOption = computed<EChartsCoreOption>(() => {
|
||||
const colors = theme();
|
||||
void isDark.value;
|
||||
const days = pool.value.dailyAdded;
|
||||
return {
|
||||
color: [colors.accent],
|
||||
tooltip: { trigger: "axis" },
|
||||
grid: { left: 36, right: 12, top: 24, bottom: 28 },
|
||||
xAxis: {
|
||||
type: "category",
|
||||
data: days.map((item) => item.date.slice(5)),
|
||||
...axis(colors),
|
||||
},
|
||||
yAxis: { type: "value", minInterval: 1, ...axis(colors) },
|
||||
series: [{
|
||||
type: "bar",
|
||||
name: "新增",
|
||||
barMaxWidth: 18,
|
||||
data: days.map((item) => item.count),
|
||||
itemStyle: { borderRadius: [3, 3, 0, 0] },
|
||||
}],
|
||||
};
|
||||
});
|
||||
|
||||
const statusOption = computed<EChartsCoreOption>(() => {
|
||||
const colors = theme();
|
||||
void isDark.value;
|
||||
const items = [
|
||||
{ name: "有效", value: pool.value.valid, itemStyle: { color: colors.ok } },
|
||||
{ name: "失效", value: pool.value.invalid, itemStyle: { color: colors.danger } },
|
||||
];
|
||||
return {
|
||||
tooltip: { trigger: "item" },
|
||||
legend: { bottom: 0, textStyle: { color: colors.muted } },
|
||||
series: [{
|
||||
type: "pie",
|
||||
radius: ["42%", "68%"],
|
||||
center: ["50%", "44%"],
|
||||
label: { color: colors.ink, formatter: "{b} {c}" },
|
||||
data: pool.value.total ? items : [{ name: "暂无", value: 1, itemStyle: { color: colors.line }, label: { show: false } }],
|
||||
}],
|
||||
};
|
||||
});
|
||||
|
||||
const cityOption = computed<EChartsCoreOption>(() => {
|
||||
const colors = theme();
|
||||
void isDark.value;
|
||||
const rows = pool.value.cities.slice(0, 8);
|
||||
return {
|
||||
color: [colors.accent],
|
||||
tooltip: { trigger: "axis" },
|
||||
grid: { left: 56, right: 16, top: 16, bottom: 28 },
|
||||
xAxis: { type: "value", minInterval: 1, ...axis(colors) },
|
||||
yAxis: {
|
||||
type: "category",
|
||||
data: rows.map((item) => item.name),
|
||||
inverse: true,
|
||||
...axis(colors),
|
||||
},
|
||||
series: [{
|
||||
type: "bar",
|
||||
name: "账号",
|
||||
barMaxWidth: 16,
|
||||
data: rows.map((item) => item.count),
|
||||
itemStyle: { borderRadius: [0, 3, 3, 0] },
|
||||
}],
|
||||
};
|
||||
});
|
||||
|
||||
async function load() {
|
||||
try {
|
||||
const result = await api<{ pool: PoolDash }>("/api/admin/dashboard");
|
||||
pool.value = result.pool;
|
||||
loaded.value = true;
|
||||
} catch (error) {
|
||||
toast.error(error instanceof Error ? error.message : "运行面板没有获取到");
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(load);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Shell>
|
||||
<section class="page admin-page">
|
||||
<header class="page-head">
|
||||
<h2>运行面板</h2>
|
||||
</header>
|
||||
<div class="admin-scroll">
|
||||
<p v-if="!loaded" class="admin-status">正在获取</p>
|
||||
<template v-else>
|
||||
<div class="dash-kpis">
|
||||
<article v-for="card in cards" :key="card.label" class="surface dash-kpi">
|
||||
<span>{{ card.label }}</span>
|
||||
<strong :class="card.tone && `status-${card.tone}`">{{ card.value }}</strong>
|
||||
</article>
|
||||
</div>
|
||||
<div class="dash-grid">
|
||||
<section class="surface dash-card">
|
||||
<h3>近14日新增账号</h3>
|
||||
<ChartPane :option="dailyOption" />
|
||||
</section>
|
||||
<section class="surface dash-card">
|
||||
<h3>凭证状态</h3>
|
||||
<ChartPane :option="statusOption" />
|
||||
</section>
|
||||
<section class="surface dash-card dash-wide">
|
||||
<h3>地市分布</h3>
|
||||
<ChartPane :option="cityOption" />
|
||||
</section>
|
||||
</div>
|
||||
</template>
|
||||
</div>
|
||||
</section>
|
||||
</Shell>
|
||||
</template>
|
||||
@@ -81,14 +81,14 @@ onMounted(load);
|
||||
<div class="form-row">
|
||||
<label for="refresh-seconds">凭证刷新间隔<n-tooltip><template #trigger><n-icon class="hint-mark" :size="16"><HelpCircleOutline /></n-icon></template>账号池里的平台凭证按这个间隔刷新。</n-tooltip></label>
|
||||
<div class="setting-control">
|
||||
<n-input-number id="refresh-seconds" v-model:value="seconds" button-placement="both" :min="60" :max="86400" :precision="0" />
|
||||
<n-input-number id="refresh-seconds" v-model:value="seconds" size="small" button-placement="both" :min="60" :max="86400" :precision="0" />
|
||||
<span class="setting-unit">秒</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="form-row">
|
||||
<label for="worker-concurrency">同时运行的任务数<n-tooltip><template #trigger><n-icon class="hint-mark" :size="16"><HelpCircleOutline /></n-icon></template>采集和导出共用。调大后马上多领任务。调小后不打断正在运行的任务。</n-tooltip></label>
|
||||
<div class="setting-control">
|
||||
<n-input-number id="worker-concurrency" v-model:value="concurrency" button-placement="both" :min="1" :max="32" :precision="0" />
|
||||
<n-input-number id="worker-concurrency" v-model:value="concurrency" size="small" button-placement="both" :min="1" :max="32" :precision="0" />
|
||||
<span class="setting-unit">个</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
<script setup lang="ts">
|
||||
import { onMounted, ref } from "vue";
|
||||
import { NButton, NInput, NModal, NSelect, useDialog } from "naive-ui";
|
||||
import { NButton, NDropdown, NIcon, NInput, NModal, NSelect, useDialog } from "naive-ui";
|
||||
import type { DropdownOption } from "naive-ui";
|
||||
import { EllipsisVerticalOutline } from "@vicons/ionicons5";
|
||||
import Shell from "../../shell/Shell.vue";
|
||||
import { api } from "../../shared/http";
|
||||
import { useToast } from "../../shared/toast";
|
||||
@@ -13,6 +15,26 @@ const show = ref(false);
|
||||
const username = ref("");
|
||||
const password = ref("");
|
||||
const role = ref("user");
|
||||
const pwdShow = ref(false);
|
||||
const pwdUser = ref<User | null>(null);
|
||||
const pwdNext = ref("");
|
||||
const pwdAgain = ref("");
|
||||
const actorId = sessionStorage.getItem("decom-id") || "";
|
||||
const actorKind = sessionStorage.getItem("decom-kind") || "";
|
||||
const actorName = sessionStorage.getItem("decom-name") || "";
|
||||
|
||||
function canReset(user: User) {
|
||||
if (user.role === "user") return true;
|
||||
if (actorKind && actorKind !== "local") return false;
|
||||
return actorId === String(user.id) || (!actorId && user.username === actorName);
|
||||
}
|
||||
|
||||
function actionOptions(user: User): DropdownOption[] {
|
||||
const options: DropdownOption[] = [];
|
||||
if (canReset(user)) options.push({ label: "修改密码", key: "password" });
|
||||
options.push({ label: "删除", key: "delete" });
|
||||
return options;
|
||||
}
|
||||
|
||||
async function load() {
|
||||
const result = await api<{ users: User[] }>("/api/admin/users");
|
||||
@@ -54,6 +76,38 @@ function confirmRemove(user: User) {
|
||||
});
|
||||
}
|
||||
|
||||
function openPassword(user: User) {
|
||||
pwdUser.value = user;
|
||||
pwdNext.value = "";
|
||||
pwdAgain.value = "";
|
||||
pwdShow.value = true;
|
||||
}
|
||||
|
||||
function onAction(key: string | number, user: User) {
|
||||
if (key === "password") openPassword(user);
|
||||
if (key === "delete") confirmRemove(user);
|
||||
}
|
||||
|
||||
async function savePassword() {
|
||||
if (!pwdUser.value) return false;
|
||||
if (!pwdNext.value) {
|
||||
toast.error("请填写密码");
|
||||
return false;
|
||||
}
|
||||
if (pwdNext.value !== pwdAgain.value) {
|
||||
toast.error("两次密码不一致");
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
await api(`/api/admin/users/${pwdUser.value.id}/password`, { method: "PUT", body: JSON.stringify({ password: pwdNext.value }) });
|
||||
pwdShow.value = false;
|
||||
toast.success("密码已修改");
|
||||
} catch (error) {
|
||||
toast.error(error instanceof Error ? error.message : "修改失败");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(load);
|
||||
</script>
|
||||
|
||||
@@ -78,7 +132,13 @@ onMounted(load);
|
||||
<tr v-for="user in users" :key="user.id">
|
||||
<td>{{ user.username }}</td>
|
||||
<td class="col-role">{{ user.role === "admin" ? "管理员" : "用户" }}</td>
|
||||
<td class="col-actions"><n-button size="small" quaternary @click="confirmRemove(user)">删除</n-button></td>
|
||||
<td class="col-actions">
|
||||
<n-dropdown trigger="click" placement="bottom-end" :options="actionOptions(user)" @select="(key) => onAction(key, user)">
|
||||
<n-button quaternary circle size="small" aria-label="操作">
|
||||
<template #icon><n-icon><EllipsisVerticalOutline /></n-icon></template>
|
||||
</n-button>
|
||||
</n-dropdown>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
@@ -93,5 +153,9 @@ onMounted(load);
|
||||
<div class="form-row"><label>密码</label><n-input v-model:value="password" type="password" /></div>
|
||||
<div class="form-row"><label>角色</label><n-select v-model:value="role" :options="[{ label: '用户', value: 'user' }, { label: '管理员', value: 'admin' }]" /></div>
|
||||
</n-modal>
|
||||
<n-modal v-model:show="pwdShow" class="app-dialog" preset="dialog" :show-icon="false" :title="pwdUser ? `修改密码 · ${pwdUser.username}` : '修改密码'" positive-text="保存" negative-text="取消" @positive-click="savePassword">
|
||||
<div class="form-row"><label>新密码</label><n-input v-model:value="pwdNext" type="password" /></div>
|
||||
<div class="form-row"><label>确认密码</label><n-input v-model:value="pwdAgain" type="password" /></div>
|
||||
</n-modal>
|
||||
</Shell>
|
||||
</template>
|
||||
|
||||
@@ -168,7 +168,7 @@ async function beginLogin() {
|
||||
}
|
||||
if (result.status === "ok" && result.token && result.user) {
|
||||
saveSession(result.token, result.user);
|
||||
router.push(result.user.role === "admin" ? "/admin/settings" : "/tasks");
|
||||
router.push(result.user.role === "admin" ? "/admin" : "/tasks");
|
||||
}
|
||||
} catch (error) {
|
||||
fail(error);
|
||||
@@ -192,7 +192,7 @@ async function startNqi() {
|
||||
});
|
||||
if (result.status === "ok" && result.token && result.user) {
|
||||
saveSession(result.token, result.user);
|
||||
router.push(result.user.role === "admin" ? "/admin/settings" : "/tasks");
|
||||
router.push(result.user.role === "admin" ? "/admin" : "/tasks");
|
||||
return;
|
||||
}
|
||||
sessionId.value = result.sessionId || "";
|
||||
@@ -307,7 +307,7 @@ async function finishNqi() {
|
||||
}
|
||||
if (result.token && result.user) {
|
||||
saveSession(result.token, result.user);
|
||||
router.push(result.user.role === "admin" ? "/admin/settings" : "/tasks");
|
||||
router.push(result.user.role === "admin" ? "/admin" : "/tasks");
|
||||
}
|
||||
} catch (error) {
|
||||
fail(error);
|
||||
|
||||
+5
-3
@@ -4,6 +4,7 @@ import App from "./App.vue";
|
||||
import InstallView from "./features/install/InstallView.vue";
|
||||
import LoginView from "./features/auth/LoginView.vue";
|
||||
import TasksView from "./features/user/TasksView.vue";
|
||||
import DashboardView from "./features/admin/DashboardView.vue";
|
||||
import SettingsView from "./features/admin/SettingsView.vue";
|
||||
import UsersView from "./features/admin/UsersView.vue";
|
||||
import PoolView from "./features/admin/PoolView.vue";
|
||||
@@ -17,12 +18,13 @@ const router = createRouter({
|
||||
routes: [
|
||||
{ path: "/install", component: InstallView },
|
||||
{ path: "/login", component: LoginView },
|
||||
{ path: "/", redirect: "/tasks" },
|
||||
{ path: "/", redirect: () => sessionStorage.getItem("decom-role") === "admin" ? "/admin" : "/tasks" },
|
||||
{ path: "/tasks", component: TasksView, meta: { role: "user" } },
|
||||
{ path: "/admin/settings", component: SettingsView, meta: { role: "admin" } },
|
||||
{ path: "/admin", component: DashboardView, meta: { role: "admin" } },
|
||||
{ path: "/admin/users", component: UsersView, meta: { role: "admin" } },
|
||||
{ path: "/admin/pool", component: PoolView, meta: { role: "admin" } },
|
||||
{ path: "/admin/sources", component: SourcesView, meta: { role: "admin" } },
|
||||
{ path: "/admin/settings", component: SettingsView, meta: { role: "admin" } },
|
||||
],
|
||||
});
|
||||
|
||||
@@ -35,7 +37,7 @@ router.beforeEach(async (to) => {
|
||||
if (!token()) return "/login";
|
||||
const role = sessionStorage.getItem("decom-role");
|
||||
if (to.meta.role === "admin" && role !== "admin") return "/tasks";
|
||||
if (to.meta.role === "user" && role === "admin") return "/admin/settings";
|
||||
if (to.meta.role === "user" && role === "admin") return "/admin";
|
||||
return true;
|
||||
});
|
||||
|
||||
|
||||
@@ -16,16 +16,22 @@ export function setToken(value: string) {
|
||||
else sessionStorage.removeItem("decom-token");
|
||||
}
|
||||
|
||||
export function saveSession(tokenValue: string, user: { role: string; name: string }) {
|
||||
export function saveSession(tokenValue: string, user: { role: string; name: string; id?: string; kind?: string }) {
|
||||
setToken(tokenValue);
|
||||
sessionStorage.setItem("decom-role", user.role);
|
||||
sessionStorage.setItem("decom-name", user.name);
|
||||
if (user.id) sessionStorage.setItem("decom-id", user.id);
|
||||
else sessionStorage.removeItem("decom-id");
|
||||
if (user.kind) sessionStorage.setItem("decom-kind", user.kind);
|
||||
else sessionStorage.removeItem("decom-kind");
|
||||
}
|
||||
|
||||
export function clearSession() {
|
||||
setToken("");
|
||||
sessionStorage.removeItem("decom-role");
|
||||
sessionStorage.removeItem("decom-name");
|
||||
sessionStorage.removeItem("decom-id");
|
||||
sessionStorage.removeItem("decom-kind");
|
||||
}
|
||||
|
||||
export async function api<T>(path: string, options: RequestInit = {}): Promise<T> {
|
||||
@@ -40,6 +46,8 @@ export async function api<T>(path: string, options: RequestInit = {}): Promise<T
|
||||
setToken("");
|
||||
sessionStorage.removeItem("decom-role");
|
||||
sessionStorage.removeItem("decom-name");
|
||||
sessionStorage.removeItem("decom-id");
|
||||
sessionStorage.removeItem("decom-kind");
|
||||
}
|
||||
if (!response.ok) {
|
||||
let message = "请求失败";
|
||||
|
||||
@@ -3,7 +3,7 @@ import { h, onMounted, onUnmounted, ref } from "vue";
|
||||
import type { Component } from "vue";
|
||||
import { useRoute, useRouter } from "vue-router";
|
||||
import { NButton, NIcon, NLayout, NLayoutSider, NMenu } from "naive-ui";
|
||||
import { CloudDownloadOutline, KeyOutline, ListOutline, LogOutOutline, PeopleOutline, PersonOutline, SettingsOutline } from "@vicons/ionicons5";
|
||||
import { CloudDownloadOutline, HomeOutline, KeyOutline, ListOutline, LogOutOutline, PeopleOutline, PersonOutline, SettingsOutline } from "@vicons/ionicons5";
|
||||
import { api, clearSession, token } from "../shared/http";
|
||||
import ThemeButton from "./ThemeButton.vue";
|
||||
|
||||
@@ -18,10 +18,11 @@ const name = sessionStorage.getItem("decom-name") || "";
|
||||
const collapsed = ref(window.innerWidth < 800);
|
||||
const items = role === "admin"
|
||||
? [
|
||||
{ label: "设置", key: "/admin/settings", icon: renderIcon(SettingsOutline) },
|
||||
{ label: "首页", key: "/admin", icon: renderIcon(HomeOutline) },
|
||||
{ label: "用户", key: "/admin/users", icon: renderIcon(PeopleOutline) },
|
||||
{ label: "账号池", key: "/admin/pool", icon: renderIcon(KeyOutline) },
|
||||
{ label: "采集", key: "/admin/sources", icon: renderIcon(CloudDownloadOutline) },
|
||||
{ label: "设置", key: "/admin/settings", icon: renderIcon(SettingsOutline) },
|
||||
]
|
||||
: [{ label: "任务", key: "/tasks", icon: renderIcon(ListOutline) }];
|
||||
|
||||
|
||||
+55
-5
@@ -142,6 +142,50 @@ button, input, select { font: inherit; }
|
||||
}
|
||||
.settings-card .form-row:last-child { margin-bottom: 10px; }
|
||||
|
||||
.dash-kpis {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(6, minmax(0, 1fr));
|
||||
gap: 12px;
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
.dash-kpi {
|
||||
padding: 14px 16px 12px;
|
||||
}
|
||||
.dash-kpi span {
|
||||
display: block;
|
||||
color: var(--muted);
|
||||
font-size: 12px;
|
||||
}
|
||||
.dash-kpi strong {
|
||||
display: block;
|
||||
margin-top: 6px;
|
||||
font-size: 24px;
|
||||
font-weight: 650;
|
||||
letter-spacing: -0.03em;
|
||||
line-height: 1.2;
|
||||
}
|
||||
.dash-grid {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1.4fr) minmax(0, 1fr);
|
||||
gap: 12px;
|
||||
}
|
||||
.dash-card { padding: 16px 16px 8px; }
|
||||
.dash-card h3 {
|
||||
margin: 0 0 8px;
|
||||
font-size: 13px;
|
||||
font-weight: 650;
|
||||
}
|
||||
.dash-wide { grid-column: 1 / -1; }
|
||||
.dash-chart { height: 260px; }
|
||||
|
||||
@media (max-width: 1100px) {
|
||||
.dash-kpis { grid-template-columns: repeat(3, minmax(0, 1fr)); }
|
||||
.dash-grid { grid-template-columns: 1fr; }
|
||||
}
|
||||
@media (max-width: 720px) {
|
||||
.dash-kpis { grid-template-columns: repeat(2, minmax(0, 1fr)); }
|
||||
}
|
||||
|
||||
/* tables */
|
||||
.admin-table {
|
||||
width: 100%;
|
||||
@@ -249,14 +293,20 @@ button, input, select { font: inherit; }
|
||||
align-items: center;
|
||||
}
|
||||
.setting-control {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1fr) auto;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
gap: 8px;
|
||||
width: auto;
|
||||
min-width: 0;
|
||||
}
|
||||
.setting-control .n-input-number { width: 100%; min-width: 0; }
|
||||
.setting-unit { flex: none; color: var(--muted); line-height: 34px; }
|
||||
.settings-fields .setting-control .n-input-number {
|
||||
width: 112px;
|
||||
min-width: 112px;
|
||||
}
|
||||
.settings-fields .setting-control .n-input__input-el {
|
||||
text-align: center;
|
||||
}
|
||||
.setting-unit { flex: none; color: var(--muted); line-height: 28px; }
|
||||
.panel { background: var(--panel); border: 1px solid var(--line); }
|
||||
.hint {
|
||||
width: 16px;
|
||||
|
||||
Reference in New Issue
Block a user