feat: 新增控制面管理功能,优化插件加载与消息通知
- 新增内网插件控制面服务,实现统一账户、权限管理与插件分发 - 重构后端插件加载逻辑,支持按账号动态权限白名单加载 - 优化XQ0001排班异常提醒文案与推送群配置 - 新增前端管理界面与登录态会话管理 - 新增插件上传、账号管理等后台管理接口
This commit is contained in:
+222
-7
@@ -9,6 +9,8 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
import os
|
||||
import socket
|
||||
import threading
|
||||
import uuid
|
||||
@@ -16,19 +18,48 @@ from contextlib import asynccontextmanager
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
|
||||
from fastapi import FastAPI, HTTPException, WebSocket
|
||||
from fastapi import FastAPI, File, HTTPException, Request, Response, UploadFile, WebSocket
|
||||
from pydantic import BaseModel
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from fastapi.staticfiles import StaticFiles
|
||||
from pydantic import BaseModel
|
||||
|
||||
from webhost.backend import auth as platform_auth
|
||||
from webhost.backend.hub import HUB
|
||||
from webhost.backend.plugins import PLUGINS # noqa: F401 触发注册
|
||||
from webhost.backend.plugins import PLUGINS, load_plugins # PLUGINS 为注册表,启动时显式填装
|
||||
from webhost.backend.plugins.base import RunContext
|
||||
|
||||
PORT = 8799
|
||||
DIST = Path(__file__).resolve().parents[1] / "frontend" / "dist"
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
# ==================== 插件权限源(阶段二:控制面接口;默认全量兜底) ====================
|
||||
PLUGIN_SOURCE = os.getenv("PLUGIN_SOURCE", "all") # all | controlplane
|
||||
CONTROLPLANE_URL = os.getenv("CONTROLPLANE_URL", "").rstrip("/")
|
||||
CONTROLPLANE_ACCOUNT = os.getenv("CONTROLPLANE_ACCOUNT", "")
|
||||
CONTROLPLANE_TOKEN = os.getenv("CONTROLPLANE_TOKEN", "")
|
||||
# 统一账户体系为真源:登录态由后端 cookie 会话维护(账号在统一后端 accounts 表)。
|
||||
# cookie 会话:token -> account;登录后 set-cookie,进程内保持,供代理转发账号。
|
||||
SESSION_COOKIE = "cp_session"
|
||||
_SESS: dict[str, str] = {}
|
||||
_SESS_LOCK = threading.Lock()
|
||||
|
||||
|
||||
def _sess_account(request: Request) -> str:
|
||||
"""从请求 cookie 会话解析当前登录账号;未登录返回空串。"""
|
||||
token = request.cookies.get(SESSION_COOKIE, "")
|
||||
with _SESS_LOCK:
|
||||
return _SESS.get(token, "")
|
||||
|
||||
|
||||
def _require_login(request: Request) -> str:
|
||||
"""业务执行接口的统一登录门槛:未登录统一账户(无有效会话 cookie)则拒绝。"""
|
||||
account = _sess_account(request)
|
||||
if not account:
|
||||
raise HTTPException(401, "未登录:请先登录统一账户")
|
||||
return account
|
||||
|
||||
|
||||
# 平台登录态:标签/展示名来自 auth,在线状态实时校验(非内存假状态)
|
||||
PLATFORMS: dict = {p["id"]: {"id": p["id"], "label": p["label"]}
|
||||
for p in platform_auth.platforms()}
|
||||
@@ -44,9 +75,61 @@ class RunReq(BaseModel):
|
||||
fields: dict = {}
|
||||
|
||||
|
||||
def _resolve_allowed() -> set | None:
|
||||
"""按权限源决定可加载插件白名单。None = 全量加载(默认/控制面不可达兜底)。"""
|
||||
if PLUGIN_SOURCE != "controlplane" or not CONTROLPLANE_URL:
|
||||
return None
|
||||
if not CONTROLPLANE_ACCOUNT:
|
||||
_LOGGER.warning("PLUGIN_SOURCE=controlplane 但未设置 CONTROLPLANE_ACCOUNT,回退全量加载")
|
||||
return None
|
||||
import requests
|
||||
|
||||
headers = {"X-API-Token": CONTROLPLANE_TOKEN} if CONTROLPLANE_TOKEN else {}
|
||||
try:
|
||||
r = requests.get(f"{CONTROLPLANE_URL}/api/plugins",
|
||||
params={"account": CONTROLPLANE_ACCOUNT},
|
||||
headers=headers, timeout=5)
|
||||
r.raise_for_status()
|
||||
allowed = {p["id"] for p in r.json().get("plugins", [])}
|
||||
_LOGGER.info("控制面权限清单(%s):%s", CONTROLPLANE_ACCOUNT,
|
||||
sorted(allowed) or "(空)")
|
||||
return allowed
|
||||
except Exception as _exc: # noqa: BLE001
|
||||
_LOGGER.error("拉取控制面权限清单失败,回退全量加载:%s", _exc)
|
||||
return None
|
||||
|
||||
|
||||
# ==================== 统一后端(数据库 API)代理:底座前端访问统一后端的唯一通道 ====================
|
||||
# 底座前端不直连统一后端/数据库;全部经本层代理转发,并注入「当前登录账号 + 内部凭证」。
|
||||
|
||||
|
||||
def _cp_headers(request: Request) -> dict:
|
||||
h = {"X-Admin-User": _sess_account(request)}
|
||||
if CONTROLPLANE_TOKEN:
|
||||
h["X-API-Token"] = CONTROLPLANE_TOKEN
|
||||
return h
|
||||
|
||||
|
||||
def _cp_call(method: str, path: str, **kw) -> dict:
|
||||
if not CONTROLPLANE_URL:
|
||||
raise HTTPException(503, "统一后端未配置(CONTROLPLANE_URL)")
|
||||
import requests
|
||||
|
||||
r = requests.request(method, f"{CONTROLPLANE_URL}{path}", timeout=30, **kw)
|
||||
try:
|
||||
body = r.json()
|
||||
except ValueError:
|
||||
body = {"detail": r.text[:300]}
|
||||
if r.status_code >= 400:
|
||||
raise HTTPException(r.status_code, body.get("detail", f"统一后端 {r.status_code}"))
|
||||
return body
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(app: FastAPI):
|
||||
HUB.bind(asyncio.get_running_loop())
|
||||
# 显式加载插件:默认全量;配置 controlplane 源则按账号权限白名单加载
|
||||
load_plugins(_resolve_allowed())
|
||||
yield
|
||||
|
||||
|
||||
@@ -54,6 +137,135 @@ app = FastAPI(title="37du Web Host", lifespan=lifespan)
|
||||
app.add_middleware(CORSMiddleware, allow_origins=["*"], allow_methods=["*"], allow_headers=["*"])
|
||||
|
||||
|
||||
@app.get("/api/admin/me")
|
||||
def admin_me(request: Request) -> dict:
|
||||
"""当前登录账号是否为管理员(会话 cookie)。统一后端不可达时视为非管理员。"""
|
||||
account = _sess_account(request)
|
||||
if not account:
|
||||
return {"account": "", "is_admin": False}
|
||||
try:
|
||||
return _cp_call("GET", "/api/admin/me", headers=_cp_headers(request))
|
||||
except HTTPException:
|
||||
return {"account": account, "is_admin": False}
|
||||
|
||||
|
||||
class _LoginIn(BaseModel):
|
||||
account: str
|
||||
password: str
|
||||
|
||||
|
||||
@app.post("/api/admin/login")
|
||||
def admin_login(b: _LoginIn, response: Response) -> dict:
|
||||
"""统一账户登录:校验账号+密码通过后,写会话 cookie 记为当前登录账号。"""
|
||||
try:
|
||||
r = _cp_call("POST", "/api/admin/auth",
|
||||
headers={"X-Admin-User": b.account.strip(),
|
||||
**({"X-API-Token": CONTROLPLANE_TOKEN} if CONTROLPLANE_TOKEN else {}),
|
||||
"Content-Type": "application/json"},
|
||||
json={"account": b.account, "password": b.password})
|
||||
except HTTPException as e:
|
||||
raise e
|
||||
if not r.get("ok"):
|
||||
return r
|
||||
token = uuid.uuid4().hex
|
||||
with _SESS_LOCK:
|
||||
_SESS[token] = b.account.strip()
|
||||
response.set_cookie(SESSION_COOKIE, token, httponly=True, samesite="lax")
|
||||
return {**r, "account": b.account.strip()}
|
||||
|
||||
|
||||
@app.post("/api/admin/logout")
|
||||
def admin_logout(request: Request, response: Response) -> dict:
|
||||
"""登出:清除会话 cookie 与内存会话。"""
|
||||
token = request.cookies.get(SESSION_COOKIE, "")
|
||||
with _SESS_LOCK:
|
||||
_SESS.pop(token, None)
|
||||
response.delete_cookie(SESSION_COOKIE)
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
class _PwdIn(BaseModel):
|
||||
account: str
|
||||
old_password: str
|
||||
new_password: str
|
||||
|
||||
|
||||
@app.post("/api/admin/password")
|
||||
def admin_password(b: _PwdIn, request: Request) -> dict:
|
||||
return _cp_call("POST", "/api/admin/password",
|
||||
headers={**_cp_headers(request), "Content-Type": "application/json"},
|
||||
json=b.model_dump())
|
||||
|
||||
|
||||
@app.get("/api/admin/overview")
|
||||
def admin_overview(request: Request) -> dict:
|
||||
return _cp_call("GET", "/api/admin/overview", headers=_cp_headers(request))
|
||||
|
||||
|
||||
@app.get("/api/admin/admins")
|
||||
def admin_list(request: Request) -> dict:
|
||||
return _cp_call("GET", "/api/admin/admins", headers=_cp_headers(request))
|
||||
|
||||
|
||||
@app.get("/api/admin/accounts")
|
||||
def admin_accounts(request: Request) -> dict:
|
||||
return _cp_call("GET", "/api/admin/accounts", headers=_cp_headers(request))
|
||||
|
||||
|
||||
@app.post("/api/admin/account")
|
||||
def admin_account_create(body: dict, request: Request) -> dict:
|
||||
return _cp_call("POST", "/api/admin/account",
|
||||
headers={**_cp_headers(request), "Content-Type": "application/json"},
|
||||
json=body)
|
||||
|
||||
|
||||
@app.post("/api/admin/account/update")
|
||||
def admin_account_update(body: dict, request: Request) -> dict:
|
||||
return _cp_call("POST", "/api/admin/account/update",
|
||||
headers={**_cp_headers(request), "Content-Type": "application/json"},
|
||||
json=body)
|
||||
|
||||
|
||||
@app.post("/api/admin/account/reset_pwd")
|
||||
def admin_account_reset(body: dict, request: Request) -> dict:
|
||||
return _cp_call("POST", "/api/admin/account/reset_pwd",
|
||||
headers={**_cp_headers(request), "Content-Type": "application/json"},
|
||||
json=body)
|
||||
|
||||
|
||||
@app.post("/api/admin/account/delete")
|
||||
def admin_account_delete(body: dict, request: Request) -> dict:
|
||||
return _cp_call("POST", "/api/admin/account/delete",
|
||||
headers={**_cp_headers(request), "Content-Type": "application/json"},
|
||||
json=body)
|
||||
|
||||
|
||||
@app.post("/api/admin/plugin/delete")
|
||||
def admin_plugin_delete(body: dict, request: Request) -> dict:
|
||||
return _cp_call("POST", "/api/admin/plugin/delete",
|
||||
headers={**_cp_headers(request), "Content-Type": "application/json"},
|
||||
json=body)
|
||||
|
||||
|
||||
@app.post("/api/admin/account_plugins")
|
||||
def admin_grant(body: dict, request: Request) -> dict:
|
||||
return _cp_call("POST", "/api/admin/account_plugins",
|
||||
headers={**_cp_headers(request), "Content-Type": "application/json"},
|
||||
json=body)
|
||||
|
||||
|
||||
@app.post("/api/admin/pkg")
|
||||
async def admin_upload(plugin_id: str, version: str, name: str = "",
|
||||
upload: UploadFile = File(...), request: Request = None) -> dict:
|
||||
"""前端上传插件包:接收文件并转发给统一后端 multipart 发布。"""
|
||||
content = await upload.read()
|
||||
files = {"upload": (upload.filename or "pkg.zip", content,
|
||||
upload.content_type or "application/octet-stream")}
|
||||
params = {"plugin_id": plugin_id, "name": name or plugin_id, "version": version}
|
||||
return _cp_call("POST", "/api/admin/pkg", params=params,
|
||||
headers=_cp_headers(request), files=files)
|
||||
|
||||
|
||||
def _plugin_schema(p) -> dict:
|
||||
return {"id": p.id, "name": p.name, "version": p.version,
|
||||
"description": p.description, "uses_month": getattr(p, "uses_month", False),
|
||||
@@ -69,8 +281,9 @@ def meta() -> dict:
|
||||
|
||||
|
||||
@app.post("/api/platforms/{pid}/login")
|
||||
def login(pid: str) -> dict:
|
||||
"""真实登录:复用有效 cookies 或浏览器自动化登录(滑块),秒级~分钟级阻塞。"""
|
||||
def login(pid: str, request: Request) -> dict:
|
||||
"""真实登录:需先通过统一账户登录(有会话)。复用有效 cookies 或浏览器自动化登录(滑块)。"""
|
||||
_require_login(request)
|
||||
plat = PLATFORMS.get(pid)
|
||||
if not plat:
|
||||
raise HTTPException(404, "平台不存在")
|
||||
@@ -91,7 +304,8 @@ def _run_target(plugin, fields: dict, run_id: str) -> None:
|
||||
|
||||
|
||||
@app.post("/api/runs", status_code=202)
|
||||
def start_run(req: RunReq) -> dict:
|
||||
def start_run(req: RunReq, request: Request) -> dict:
|
||||
_require_login(request)
|
||||
try:
|
||||
plugin = PLUGINS.find(req.plugin_id)
|
||||
except KeyError:
|
||||
@@ -109,7 +323,8 @@ def start_run(req: RunReq) -> dict:
|
||||
|
||||
|
||||
@app.get("/api/runs/{run_id}")
|
||||
def get_run(run_id: str) -> dict:
|
||||
def get_run(run_id: str, request: Request) -> dict:
|
||||
_require_login(request)
|
||||
with RUN_LOCK:
|
||||
run = RUNS.get(run_id)
|
||||
if not run:
|
||||
|
||||
@@ -48,13 +48,12 @@ def _discover_modules() -> list:
|
||||
|
||||
|
||||
def load_plugins(allowed: set = None) -> None:
|
||||
"""动态加载插件。allowed 为空 = 全量;否则仅加载白名单内的插件。
|
||||
"""动态加载插件。allowed 为 None = 全量;否则为严格白名单(空集 = 零权限,全不加载)。
|
||||
|
||||
单插件加载失败记 ERROR(含堆栈首行)后跳过,不拖垮整体启动。
|
||||
"""
|
||||
allowed = allowed if allowed is not None else set()
|
||||
for _mod in _discover_modules():
|
||||
if allowed and _mod not in allowed:
|
||||
if allowed is not None and _mod not in allowed:
|
||||
_LOGGER.info("插件 %s 不在权限白名单,跳过加载", _mod)
|
||||
continue
|
||||
try:
|
||||
@@ -64,5 +63,5 @@ def load_plugins(allowed: set = None) -> None:
|
||||
traceback.format_exc(limit=1))
|
||||
|
||||
|
||||
# 触发加载(阶段一:全量;阶段二改由 main.py 显式调用并传入权限白名单)
|
||||
load_plugins()
|
||||
# 注意:这里不再 import 时自动加载。由宿主(main.py)在应用启动时显式调用
|
||||
# load_plugins(allowed) 一次性加载,以便阶段二可传入按账号动态计算的权限白名单。
|
||||
@@ -1,6 +1,7 @@
|
||||
<template>
|
||||
<div class="__app">
|
||||
<!-- 顶部:品牌 + 平台登录态 + 进度 -->
|
||||
<LoginPage v-if="!store.current" :app-name="store.appName" @ok="onLogin" />
|
||||
<div class="__app" v-else>
|
||||
<!-- 顶部:品牌 + 平台登录态 + 当前账号/登出 + 进度 -->
|
||||
<header class="topbar panel">
|
||||
<div class="brand">
|
||||
<span class="logo">37</span>
|
||||
@@ -34,6 +35,12 @@
|
||||
<span v-if="store.running" class="run-label">{{ store.progress }}%</span>
|
||||
<div v-show="store.running" class="progress"><div :style="{ width: store.progress + '%' }"></div></div>
|
||||
</div>
|
||||
|
||||
<div class="acct">
|
||||
<span class="acct-name">{{ store.current }}</span>
|
||||
<em v-if="store.isAdmin" class="acct-tag">管理员</em>
|
||||
<button class="chip" @click="logout">登出</button>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<!-- 主体:左场景 | 右插件页 + 日志 -->
|
||||
@@ -47,8 +54,8 @@
|
||||
<li
|
||||
v-for="(p, i) in store.plugins"
|
||||
:key="p.id"
|
||||
:class="{ active: p.id === store.selectedId }"
|
||||
@click="store.selectedId = p.id"
|
||||
:class="{ active: p.id === store.selectedId && store.view === 'plugin' }"
|
||||
@click="openPlugin(p.id)"
|
||||
>
|
||||
<span class="scene-icon" :style="{ background: PALETTE[i % PALETTE.length] }">
|
||||
{{ p.name.slice(0, 1) }}
|
||||
@@ -56,13 +63,22 @@
|
||||
<span class="scene-name">{{ p.name }}</span>
|
||||
<em>v{{ p.version }}</em>
|
||||
</li>
|
||||
<li
|
||||
class="admin-entry"
|
||||
:class="{ active: store.view === 'admin' }"
|
||||
@click="store.view = 'admin'"
|
||||
>
|
||||
<span class="scene-icon" style="background: #3b3f4a">⚙</span>
|
||||
<span class="scene-name">控制面管理</span>
|
||||
</li>
|
||||
</ul>
|
||||
<div class="side-foot">场景以插件方式接入</div>
|
||||
</aside>
|
||||
|
||||
<main class="main">
|
||||
<div class="page-scroll panel">
|
||||
<PluginPage />
|
||||
<PluginPage v-if="store.view === 'plugin'" />
|
||||
<ManagementView v-else-if="store.view === 'admin'" />
|
||||
</div>
|
||||
<LogPanel />
|
||||
</main>
|
||||
@@ -74,14 +90,21 @@
|
||||
import { computed, onMounted, ref } from 'vue'
|
||||
import PluginPage from './components/PluginPage.vue'
|
||||
import LogPanel from './components/LogPanel.vue'
|
||||
import ManagementView from './components/ManagementView.vue'
|
||||
import LoginPage from './components/LoginPage.vue'
|
||||
import { store, handleEvent, clearLogs } from './store'
|
||||
import { connectWS, fetchMeta, loginPlatform } from './api'
|
||||
import { connectWS, fetchMeta, loginPlatform, adminLogout } from './api'
|
||||
|
||||
const PALETTE = ['#3b6cff', '#7c5cff', '#12a4d8', '#22b07a', '#e88a3a', '#e5484d']
|
||||
|
||||
const wsText = computed(() =>
|
||||
store.wsOn ? '服务已连接' : '连接中断,正在重连…')
|
||||
|
||||
function openPlugin(id) {
|
||||
store.selectedId = id
|
||||
store.view = 'plugin'
|
||||
}
|
||||
|
||||
onMounted(async () => {
|
||||
const meta = await fetchMeta()
|
||||
store.appName = meta.appName
|
||||
@@ -94,10 +117,34 @@ onMounted(async () => {
|
||||
window.__ws = ws
|
||||
ws.onopen = () => (store.wsOn = true)
|
||||
ws.onclose = () => { store.wsOn = false; setTimeout(() => (location.reload()), 2500) }
|
||||
checkSession()
|
||||
})
|
||||
|
||||
const busyLogin = ref('')
|
||||
|
||||
async function checkSession() {
|
||||
// 已在本地标记登录:与后端会话 cookie 是否一致(后端重启会失效,此时回登录页)
|
||||
if (!store.current) return
|
||||
try {
|
||||
const me = await fetch('/api/admin/me').then((r) => r.json())
|
||||
if (!me.account) { store.current = ''; store.isAdmin = false }
|
||||
else store.isAdmin = !!me.is_admin
|
||||
} catch (_) { /* 后端 down:暂保持本地态 */
|
||||
}
|
||||
}
|
||||
|
||||
function onLogin(ok) {
|
||||
store.current = ok.account
|
||||
store.isAdmin = !!ok.is_admin
|
||||
try { localStorage.setItem('cp_account', ok.account) } catch (_) {}
|
||||
}
|
||||
async function logout() {
|
||||
try { await adminLogout() } catch (_) {}
|
||||
store.current = ''
|
||||
store.isAdmin = false
|
||||
try { localStorage.removeItem('cp_account') } catch (_) {}
|
||||
}
|
||||
|
||||
async function login(id) {
|
||||
if (busyLogin.value) return
|
||||
busyLogin.value = id
|
||||
@@ -152,6 +199,11 @@ async function login(id) {
|
||||
.run-state { display: flex; align-items: center; gap: 10px; }
|
||||
.run-label { font-size: 12px; color: var(--primary); font-weight: 600; min-width: 38px; text-align: right; }
|
||||
|
||||
.acct { display: flex; align-items: center; gap: 8px; margin-left: 12px; }
|
||||
.acct-name { font-size: 13px; font-weight: 600; color: var(--text-sub); }
|
||||
.acct-tag { font-style: normal; font-size: 10px; color: var(--primary);
|
||||
border: 1px solid var(--primary-weak); background: var(--primary-weak); border-radius: 999px; padding: 1px 7px; }
|
||||
|
||||
.body { flex: 1; display: flex; gap: 14px; min-height: 0; margin-top: 14px; }
|
||||
|
||||
.side { width: 232px; flex-shrink: 0; display: flex; flex-direction: column; padding: 14px 12px; }
|
||||
@@ -172,6 +224,8 @@ async function login(id) {
|
||||
}
|
||||
.scene-name { flex: 1; color: var(--text-sub); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||||
.scene-list li.active .scene-name { color: var(--primary); }
|
||||
.scene-list li.admin-entry { border-top: 1px dashed var(--border); margin-top: 6px; border-radius: 0; }
|
||||
.scene-list li.admin-entry.active .scene-name { color: var(--primary); font-weight: 600; }
|
||||
.scene-list em { font-style: normal; font-size: 10px; color: var(--text-faint); }
|
||||
.side-foot { font-size: 10px; color: var(--text-faint); text-align: center; padding-top: 10px; border-top: 1px dashed var(--border); margin-top: 8px; }
|
||||
|
||||
|
||||
@@ -37,4 +37,57 @@ export function connectWS(onEvent) {
|
||||
try { onEvent(JSON.parse(e.data)) } catch (_) {}
|
||||
}
|
||||
return ws
|
||||
}
|
||||
|
||||
// ===== 控制面管理(统一后端数据库 API,经底座后端代理) =====
|
||||
export async function adminMe() {
|
||||
return j('/api/admin/me')
|
||||
}
|
||||
export async function adminLogin(account, password) {
|
||||
return jj('/api/admin/login', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ account, password }) })
|
||||
}
|
||||
export async function adminLogout() {
|
||||
return j('/api/admin/logout', { method: 'POST' })
|
||||
}
|
||||
export async function adminPassword(body) {
|
||||
return jj('/api/admin/password', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) })
|
||||
}
|
||||
export async function adminOverview() {
|
||||
return j('/api/admin/overview')
|
||||
}
|
||||
async function jj(url, opts) {
|
||||
const r = await fetch(url, opts)
|
||||
if (!r.ok) {
|
||||
let m = `HTTP ${r.status}`
|
||||
try { m = (await r.json()).detail || m } catch (_) {}
|
||||
throw new Error(m)
|
||||
}
|
||||
return r.json()
|
||||
}
|
||||
export async function adminGrant(body) {
|
||||
return jj('/api/admin/account_plugins', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) })
|
||||
}
|
||||
export async function adminAccounts() {
|
||||
return j('/api/admin/accounts')
|
||||
}
|
||||
export async function adminAccountCreate(body) {
|
||||
return jj('/api/admin/account', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) })
|
||||
}
|
||||
export async function adminAccountUpdate(body) {
|
||||
return jj('/api/admin/account/update', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) })
|
||||
}
|
||||
export async function adminAccountReset(body) {
|
||||
return jj('/api/admin/account/reset_pwd', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) })
|
||||
}
|
||||
export async function adminAccountDelete(body) {
|
||||
return jj('/api/admin/account/delete', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) })
|
||||
}
|
||||
export async function adminPluginDelete(body) {
|
||||
return jj('/api/admin/plugin/delete', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) })
|
||||
}
|
||||
export async function adminUpload(pluginId, name, version, file) {
|
||||
const fd = new FormData()
|
||||
fd.append('upload', file)
|
||||
const qs = new URLSearchParams({ plugin_id: pluginId, name, version })
|
||||
return jj('/api/admin/pkg?' + qs.toString(), { method: 'POST', body: fd })
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
<template>
|
||||
<div class="login">
|
||||
<div class="card">
|
||||
<div class="brand">
|
||||
<span class="logo">37</span>
|
||||
<div class="brand-meta">
|
||||
<strong>{{ appName || '37du 业务场景工具集' }}</strong>
|
||||
<span>统一账户登录</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="row">
|
||||
<input v-model="account" placeholder="账号" @keyup.enter="doLogin">
|
||||
<input v-model="password" type="password" placeholder="密码" @keyup.enter="doLogin">
|
||||
</div>
|
||||
<button class="primary" :disabled="busy" @click="doLogin">{{ busy ? '校验中…' : '登录' }}</button>
|
||||
<p class="tip">账号统一由控制面带部门建档,所有账号均需密码登录,密码不落前端明文。</p>
|
||||
<p class="msg" v-if="msg">{{ msg }}</p>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { ref } from 'vue'
|
||||
import { adminLogin } from '../api'
|
||||
|
||||
const props = defineProps({ appName: { type: String, default: '' } })
|
||||
const emit = defineEmits(['ok'])
|
||||
const account = ref('')
|
||||
const password = ref('')
|
||||
const busy = ref(false)
|
||||
const msg = ref('')
|
||||
|
||||
async function doLogin() {
|
||||
if (!account.value || !password.value) return (msg.value = '请输入账号和密码')
|
||||
busy.value = true
|
||||
try {
|
||||
const r = await adminLogin(account.value, password.value)
|
||||
emit('ok', { account: account.value.trim(), is_admin: !!r.is_admin })
|
||||
} catch (e) {
|
||||
msg.value = '登录失败:' + (e.message || e)
|
||||
} finally {
|
||||
busy.value = false
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.login { display: grid; place-items: center; height: 100%; }
|
||||
.card { width: 340px; display: flex; flex-direction: column; gap: 14px;
|
||||
border: 1px solid var(--border); border-radius: 12px; padding: 28px; box-shadow: 0 10px 30px -14px rgba(0,0,0,.18); }
|
||||
.brand { display: flex; align-items: center; gap: 12px; margin-bottom: 4px; }
|
||||
.logo { width: 40px; height: 40px; border-radius: 11px; display: grid; place-items: center;
|
||||
background: var(--primary-grad); color: #fff; font-size: 15px; font-weight: 800; }
|
||||
.brand-meta { display: flex; flex-direction: column; line-height: 1.25; }
|
||||
.brand-meta strong { font-size: 15px; }
|
||||
.brand-meta span { font-size: 11px; color: var(--text-faint); }
|
||||
.row { display: flex; flex-direction: column; gap: 10px; }
|
||||
.row input { border: 1px solid var(--border-strong); border-radius: var(--radius-sm); padding: 10px 12px; background: var(--surface); font: inherit; }
|
||||
.row input:focus { outline: none; border-color: var(--primary); }
|
||||
button.primary { border: none; border-radius: var(--radius-sm); padding: 10px; cursor: pointer;
|
||||
background: var(--primary); color: #fff; font: inherit; }
|
||||
button.primary:disabled { opacity: .55; cursor: not-allowed; }
|
||||
.tip { color: var(--text-faint); font-size: 11.5px; line-height: 1.6; }
|
||||
.msg { color: #e5484d; font-size: 12px; }
|
||||
</style>
|
||||
@@ -0,0 +1,229 @@
|
||||
<template>
|
||||
<div class="mgmt">
|
||||
<div class="m-head">
|
||||
<div>
|
||||
<h3>控制面管理</h3>
|
||||
<p class="m-sub">统一后端 · 数据库开放 API · 当前账号 {{ store.current }}</p>
|
||||
</div>
|
||||
<button class="primary btn" @click="load" :disabled="busy">{{ busy ? '读取中…' : '刷新' }}</button>
|
||||
</div>
|
||||
<div class="toast-note" v-if="msg">{{ msg }}</div>
|
||||
|
||||
<section>
|
||||
<h4>上传插件包</h4>
|
||||
<div class="row">
|
||||
<input v-model="pid" placeholder="插件 ID,如 seal_check">
|
||||
<input v-model="pname" placeholder="插件名称">
|
||||
<input v-model="pver" placeholder="版本,如 1.1.0" style="width:110px">
|
||||
<input type="file" @change="e => pfile = e.target.files[0]">
|
||||
<button class="primary" @click="upload">上传发布</button>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<h4>插件列表</h4>
|
||||
<table>
|
||||
<thead><tr><th>插件</th><th>名称</th><th>最新版</th><th>版本</th><th>授权账号</th><th>操作</th></tr></thead>
|
||||
<tbody>
|
||||
<tr v-if="!data.plugins.length"><td colspan="6" class="muted">暂无插件,请先上传</td></tr>
|
||||
<tr v-for="p in data.plugins" :key="p.id">
|
||||
<td><b>{{ p.id }}</b></td>
|
||||
<td>{{ p.name }}</td>
|
||||
<td>{{ p.latest_version }}</td>
|
||||
<td class="muted">{{ (p.versions||[]).map(v=>v.version).join(' · ') || '—' }}</td>
|
||||
<td>{{ (p.accounts||[]).join('、') || '—' }}</td>
|
||||
<td><button class="link danger" @click="delPlugin(p.id)">删除</button></td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<h4>账号管理</h4>
|
||||
<div class="row" style="margin-bottom:14px">
|
||||
<input v-model="naAcct" placeholder="账号">
|
||||
<input v-model="naPwd" type="password" placeholder="初始密码">
|
||||
<input v-model="naDept" placeholder="部门" style="width:120px">
|
||||
<label class="ck"><input type="checkbox" v-model="naAdmin">管理员</label>
|
||||
<button class="primary" @click="createAccount">建号</button>
|
||||
</div>
|
||||
<table>
|
||||
<thead><tr><th>账号</th><th>部门</th><th>管理员</th><th>已授权插件</th><th>操作</th></tr></thead>
|
||||
<tbody>
|
||||
<tr v-for="a in data.accounts" :key="a.account">
|
||||
<td><b>{{ a.account }}</b></td>
|
||||
<td>
|
||||
<input class="ipt-sm" :value="a.dept" @change="e => setDept(a.account, e.target.value)"
|
||||
:disabled="a.account===current">
|
||||
</td>
|
||||
<td>
|
||||
<button class="link" :class="{ 'on': a.is_admin, 'danger': !a.is_admin && a.account!==current }"
|
||||
@click="a.account!==current ? toggleAdmin(a) : null">
|
||||
{{ a.is_admin ? '是' : '否' }}
|
||||
</button>
|
||||
</td>
|
||||
<td class="muted">{{ (a.plugins||[]).join('、') || '—' }}</td>
|
||||
<td>
|
||||
<button class="link" @click="resetPwd(a.account)">重置密码</button>
|
||||
<button class="link danger" v-if="a.account!==current" @click="delAccount(a.account)">删除</button>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
<!-- 账号插件授权 -->
|
||||
<div class="row" style="margin-top:16px">
|
||||
<input v-model="grantAcc" placeholder="授权账号,如 alice">
|
||||
<button @click="loadGrant">载入</button>
|
||||
<span v-if="grantAcc" class="muted">{{ grantAcc }} · 已授权 {{ checked.size }} 个</span>
|
||||
</div>
|
||||
<div class="checks" v-if="grantAcc && data.plugins.length">
|
||||
<label v-for="p in data.plugins" :key="p.id" class="ck">
|
||||
<input type="checkbox" :value="p.id" v-model="checked">
|
||||
{{ p.id }} · {{ p.name }}
|
||||
</label>
|
||||
</div>
|
||||
<button v-if="grantAcc" class="primary" style="margin-top:12px" @click="saveGrant">保存授权</button>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<h4>修改密码</h4>
|
||||
<div class="row">
|
||||
<input v-model="oldPwd" type="password" placeholder="原密码">
|
||||
<input v-model="newPwd" type="password" placeholder="新密码">
|
||||
<button class="primary" @click="changePwd">保存新密码</button>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { computed, ref } from 'vue'
|
||||
import { store } from '../store.js'
|
||||
import { adminOverview, adminUpload, adminGrant, adminPassword,
|
||||
adminAccountCreate, adminAccountUpdate, adminAccountReset, adminAccountDelete, adminPluginDelete } from '../api.js'
|
||||
|
||||
const current = computed(() => store.current || '')
|
||||
const data = ref({ plugins: [], accounts: [], admins: [] })
|
||||
const busy = ref(false)
|
||||
const msgRef = ref('')
|
||||
const pid = ref(''); const pname = ref(''); const pver = ref(''); const pfile = ref(null)
|
||||
const grantAcc = ref(''); const checked = ref(new Set())
|
||||
const naAcct = ref(''); const naPwd = ref(''); const naDept = ref(''); const naAdmin = ref(false)
|
||||
const oldPwd = ref(''); const newPwd = ref('')
|
||||
let grantHeld = new Set()
|
||||
|
||||
function toast(msg) {
|
||||
msgRef.value = msg
|
||||
clearTimeout(msgRef._h)
|
||||
msgRef._h = setTimeout(() => (msgRef.value = ''), 2600)
|
||||
}
|
||||
async function changePwd() {
|
||||
if (!oldPwd.value || !newPwd.value) return toast('请输入原密码与新密码')
|
||||
try {
|
||||
await adminPassword({ account: store.current, old_password: oldPwd.value, new_password: newPwd.value })
|
||||
oldPwd.value = ''; newPwd.value = ''
|
||||
toast('密码已修改')
|
||||
} catch (e) { toast('修改失败:' + (e.message || e)) }
|
||||
}
|
||||
async function load() {
|
||||
busy.value = true
|
||||
try { data.value = await adminOverview() } catch (e) { toast('读取失败:' + (e.message || e)) }
|
||||
finally { busy.value = false }
|
||||
}
|
||||
async function upload() {
|
||||
if (!pid.value || !pver.value || !pfile.value) return toast('请填写 ID / 版本并选择包文件')
|
||||
try {
|
||||
await adminUpload(pid.value, pname.value || pid.value, pver.value, pfile.value)
|
||||
toast(`已发布 ${pid.value}@${pver.value}`)
|
||||
await load()
|
||||
} catch (e) { toast('上传失败:' + (e.message || e)) }
|
||||
}
|
||||
function loadGrant() {
|
||||
const acc = grantAcc.value.trim(); if (!acc) return toast('请输入账号')
|
||||
const a = data.value.accounts.find(x => x.account === acc)
|
||||
grantHeld = new Set(a ? a.plugins : [])
|
||||
checked.value = new Set(grantHeld)
|
||||
}
|
||||
async function saveGrant() {
|
||||
const acc = grantAcc.value.trim(); if (!acc) return
|
||||
const want = new Set(checked.value)
|
||||
let n = 0
|
||||
for (const pids of new Set([...want, ...grantHeld])) {
|
||||
const g = want.has(pids)
|
||||
if (g !== grantHeld.has(pids)) {
|
||||
try { await adminGrant({ account: acc, plugin_id: pids, granted: g }); n++ } catch (e) { toast((e.message||e)); }
|
||||
}
|
||||
}
|
||||
grantHeld = want
|
||||
await load()
|
||||
toast(n ? `已更新 ${n} 项` : '无需变更')
|
||||
}
|
||||
async function createAccount() {
|
||||
const acct = naAcct.value.trim(); const pwd = naPwd.value
|
||||
if (!acct || !pwd) return toast('账号与初始密码必填')
|
||||
try {
|
||||
await adminAccountCreate({ account: acct, password: pwd, dept: naDept.value.trim(), is_admin: naAdmin.value })
|
||||
toast(`已建号 ${acct}`); naAcct.value=''; naPwd.value=''; naDept.value=''; naAdmin.value=false
|
||||
await load()
|
||||
} catch (e) { toast('建号失败:' + (e.message || e)) }
|
||||
}
|
||||
async function setDept(acct, dept) {
|
||||
try { await adminAccountUpdate({ account: acct, dept }); toast(`已更新 ${acct} 部门`) }
|
||||
catch (e) { toast(e.message || e) }
|
||||
}
|
||||
async function toggleAdmin(a) {
|
||||
try { await adminAccountUpdate({ account: a.account, is_admin: !a.is_admin }); await load() }
|
||||
catch (e) { toast(e.message || e) }
|
||||
}
|
||||
async function resetPwd(acct) {
|
||||
if (acct === current.value) return toast('请用「修改密码」改自己的密码')
|
||||
const newp = prompt(`重置 ${acct} 的新密码:`)
|
||||
if (!newp) return
|
||||
try { await adminAccountReset({ account: acct, new_password: newp }); toast(`已重置 ${acct} 密码`) }
|
||||
catch (e) { toast(e.message || e) }
|
||||
}
|
||||
async function delAccount(acct) {
|
||||
if (!confirm(`确认删除账号 ${acct}?其插件授权将一并清除`)) return
|
||||
try { await adminAccountDelete({ account: acct }); toast(`已删除 ${acct}`); await load() }
|
||||
catch (e) { toast(e.message || e) }
|
||||
}
|
||||
async function delPlugin(pid) {
|
||||
if (!confirm(`确认删除插件 ${pid}?版本与授权将一并清除`)) return
|
||||
try { await adminPluginDelete({ plugin_id: pid }); toast(`已删除插件 ${pid}`); await load() }
|
||||
catch (e) { toast(e.message || e) }
|
||||
}
|
||||
load()
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.mgmt { display: flex; flex-direction: column; gap: 26px; }
|
||||
.m-head { display: flex; justify-content: space-between; align-items: flex-start; }
|
||||
h3 { font-size: 16px; }
|
||||
h4 { font-size: 13px; font-weight: 600; border-bottom: 1px solid var(--border); padding-bottom: 8px; margin-bottom: 14px; }
|
||||
.m-sub, .muted { color: var(--text-faint); font-size: 12px; }
|
||||
.toast-note { color: #fff; background: #3a3f4a; font-size: 12px; padding: 7px 12px; border-radius: 6px; margin-top: 10px; width: fit-content; }
|
||||
.row { display: flex; gap: 8px; flex-wrap: wrap; align-items: center; }
|
||||
input, button { font: inherit; }
|
||||
input { border: 1px solid var(--border-strong); border-radius: var(--radius-sm); padding: 6px 10px; background: var(--surface); }
|
||||
input:focus { outline: none; border-color: var(--primary); }
|
||||
.btn { padding: 6px 14px; }
|
||||
button { background: var(--surface); border: 1px solid var(--border); border-radius: var(--radius-sm); padding: 6px 14px; cursor: pointer; color: var(--text-sub); }
|
||||
button.primary { background: var(--primary); border-color: var(--primary); color: #fff; }
|
||||
button:disabled { opacity: .5; cursor: not-allowed; }
|
||||
table { width: 100%; border-collapse: collapse; }
|
||||
th, td { text-align: left; padding: 8px 10px; border-bottom: 1px solid var(--border); font-size: 13px; }
|
||||
th { color: var(--text-faint); font-weight: 600; font-size: 12px; }
|
||||
.checks { display: flex; flex-wrap: wrap; gap: 4px 16px; margin-top: 10px; }
|
||||
.ck { display: inline-flex; align-items: center; gap: 6px; font-size: 13px; }
|
||||
.link { border: none; background: none; color: var(--primary); padding: 0; margin-left: 4px; font-size: 12px; }
|
||||
.link.danger { color: #e5484d; }
|
||||
.link.on { color: var(--primary); font-weight: 600; }
|
||||
.ipt-sm { width: 90px; padding: 4px 6px; font-size: 12px; }
|
||||
.edNeed input[type=checkbox] { accent-color: var(--primary); }
|
||||
.m-tip { color: var(--text-faint); font-size: 12px; margin-top: 8px; }
|
||||
.admin-row { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; }
|
||||
.login-card { max-width: 360px; display: flex; flex-direction: column; gap: 12px;
|
||||
border: 1px solid var(--border); border-radius: 10px; padding: 24px; }
|
||||
.login-card h3 { font-size: 15px; }
|
||||
.login-card .row { display: flex; gap: 8px; }
|
||||
</style>
|
||||
@@ -13,6 +13,10 @@ export const store = reactive({
|
||||
lastResult: null, // {ok, error}
|
||||
lastSummary: '', // 完成时后端返回的摘要
|
||||
wsOn: false,
|
||||
// 控制面管理视图(统一后端数据库 API)
|
||||
isAdmin: false,
|
||||
current: (() => { try { return localStorage.getItem('cp_account') || '' } catch (_) { return '' } })(),
|
||||
view: 'plugin', // 'plugin' | 'admin'
|
||||
})
|
||||
|
||||
export function clearLogs() {
|
||||
|
||||
Reference in New Issue
Block a user