feat: 搭建控制面管理前端并剥离底座管理功能
1. 新增controlplane/frontend Vue3管理前端,实现登录、账号CRUD、插件上传/管理、权限授权 2. 为controlplane/app.py添加CORS中间件并挂载前端静态产物 3. 重构环境变量加载,统一使用app/common/env.load_app_env() 4. 剥离webhost/的管理UI与代理接口,仅保留基础登录能力 5. 新增环境隔离规范文档与架构蓝图说明
This commit is contained in:
+124
-74
@@ -9,16 +9,19 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import socket
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import uuid
|
||||
from contextlib import asynccontextmanager
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
|
||||
from fastapi import FastAPI, File, HTTPException, Request, Response, UploadFile, WebSocket
|
||||
from fastapi import FastAPI, HTTPException, Request, Response, WebSocket
|
||||
from pydantic import BaseModel
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from fastapi.staticfiles import StaticFiles
|
||||
@@ -26,13 +29,34 @@ from fastapi.staticfiles import StaticFiles
|
||||
from webhost.backend import auth as platform_auth
|
||||
from webhost.backend.hub import HUB
|
||||
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__)
|
||||
|
||||
|
||||
# ==================== 配置固化:加载本模块 env(webhost/.env;免命令行传参;环境变量优先) ====================
|
||||
def _load_dotenv() -> None:
|
||||
"""轻量读取 webhost/.env,灌入 os.environ(仅当变量缺失时)。UTF-8、'#'/'空行'跳过。"""
|
||||
env_path = Path(__file__).resolve().parents[1] / ".env"
|
||||
if not env_path.is_file():
|
||||
return
|
||||
try:
|
||||
for _ln in env_path.read_text(encoding="utf-8").splitlines():
|
||||
_line = _ln.strip()
|
||||
if not _line or _line.startswith("#") or "=" not in _line:
|
||||
continue
|
||||
_k, _v = _line.split("=", 1)
|
||||
_k, _v = _k.strip(), _v.strip()
|
||||
if _k and _k not in os.environ:
|
||||
os.environ[_k] = _v
|
||||
except OSError as _exc: # noqa: BLE001
|
||||
_LOGGER.warning("读取 .env 失败: %s", _exc)
|
||||
|
||||
|
||||
_load_dotenv()
|
||||
|
||||
# ==================== 插件权限源(阶段二:控制面接口;默认全量兜底) ====================
|
||||
PLUGIN_SOURCE = os.getenv("PLUGIN_SOURCE", "all") # all | controlplane
|
||||
CONTROLPLANE_URL = os.getenv("CONTROLPLANE_URL", "").rstrip("/")
|
||||
@@ -199,71 +223,8 @@ def admin_password(b: _PwdIn, request: Request) -> dict:
|
||||
|
||||
@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)
|
||||
"""管理台一次性拉取:全部插件 + 账号 + 管理员。管理入口已在中心机控制面,底座侧置空兜底。"""
|
||||
return {"plugins": [], "accounts": [], "admins": []}
|
||||
|
||||
|
||||
def _plugin_schema(p) -> dict:
|
||||
@@ -291,16 +252,105 @@ def login(pid: str, request: Request) -> dict:
|
||||
|
||||
|
||||
def _run_target(plugin, fields: dict, run_id: str) -> None:
|
||||
ctx = RunContext(HUB, run_id=run_id, plugin_id=plugin.id, auth=platform_auth)
|
||||
"""进程级隔离执行插件:拉起独立 python 子进程,stdout JSON 事件转发 /ws,超时强杀。
|
||||
|
||||
插件在此子进程内 `run()`,本地崩溃(死循环/sys.exit/内存爬升)不会拖垮底座;
|
||||
登录态由子进程直接读取共享 cookie 文件重建,无需主进程中转。
|
||||
"""
|
||||
runner = Path(__file__).with_name("plugin_runner.py")
|
||||
root = Path(__file__).resolve().parents[2]
|
||||
timeout = int(os.getenv("RUN_TIMEOUT", "1800")) # 秒;浏览器类插件默认 30min
|
||||
|
||||
def _publish_event(ev: dict):
|
||||
t = ev.get("ev")
|
||||
if t == "log":
|
||||
HUB.publish({"t": "log", "run_id": run_id, "plugin_id": plugin.id,
|
||||
"level": ev.get("level", "INFO"), "msg": ev.get("msg", "")})
|
||||
elif t == "progress":
|
||||
HUB.publish({"t": "progress", "run_id": run_id, "plugin_id": plugin.id,
|
||||
"pct": int(ev.get("pct", 0))})
|
||||
|
||||
try:
|
||||
result = plugin.run(fields, ctx)
|
||||
proc = subprocess.Popen(
|
||||
[sys.executable, "-u", str(runner), "--plugin", plugin.id,
|
||||
"--run", run_id],
|
||||
cwd=str(root), stdin=subprocess.PIPE, stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE, text=True, encoding="utf-8",
|
||||
errors="replace",
|
||||
)
|
||||
except Exception as e: # noqa: BLE001 子进程拉起失败
|
||||
with RUN_LOCK:
|
||||
RUNS[run_id] = {"status": "done", "result": result, "error": None}
|
||||
HUB.publish({"t": "run_done", "run_id": run_id, "ok": True})
|
||||
except Exception as e: # noqa: BLE001 全局兜底,推送失败给前端
|
||||
RUNS[run_id] = {"status": "error", "result": None,
|
||||
"error": f"拉起执行子进程失败: {e}"}
|
||||
HUB.publish({"t": "run_done", "run_id": run_id, "ok": False,
|
||||
"error": f"拉起执行子进程失败: {e}"})
|
||||
return
|
||||
|
||||
_result: dict = {}
|
||||
_rlock = threading.Lock()
|
||||
|
||||
def _drain_out():
|
||||
for line in proc.stdout:
|
||||
line = line.strip()
|
||||
if not line:
|
||||
continue
|
||||
try:
|
||||
ev = json.loads(line)
|
||||
except ValueError:
|
||||
continue
|
||||
if ev.get("ev") in ("log", "progress"):
|
||||
_publish_event(ev)
|
||||
elif ev.get("ev") == "result":
|
||||
with _rlock:
|
||||
_result.update(ev)
|
||||
|
||||
def _drain_err():
|
||||
for line in proc.stderr:
|
||||
line = line.strip()
|
||||
if line:
|
||||
HUB.publish({"t": "log", "run_id": run_id, "plugin_id": plugin.id,
|
||||
"level": "ERROR", "msg": line})
|
||||
|
||||
t_out = threading.Thread(target=_drain_out, daemon=True, name=f"out-{run_id}")
|
||||
t_err = threading.Thread(target=_drain_err, daemon=True, name=f"err-{run_id}")
|
||||
t_out.start(); t_err.start()
|
||||
|
||||
try:
|
||||
proc.stdin.write(json.dumps(fields, ensure_ascii=False))
|
||||
proc.stdin.close()
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
timed_out = False
|
||||
try:
|
||||
proc.wait(timeout=timeout)
|
||||
except subprocess.TimeoutExpired:
|
||||
timed_out = True
|
||||
try:
|
||||
proc.kill()
|
||||
proc.wait(timeout=5)
|
||||
except (subprocess.TimeoutExpired, OSError):
|
||||
pass
|
||||
|
||||
with _rlock:
|
||||
ev = dict(_result)
|
||||
if ev:
|
||||
ok = bool(ev.get("ok"))
|
||||
with RUN_LOCK:
|
||||
RUNS[run_id] = {"status": "error", "result": None, "error": str(e)}
|
||||
HUB.publish({"t": "run_done", "run_id": run_id, "ok": False, "error": str(e)})
|
||||
RUNS[run_id] = {"status": "done" if ok else "error",
|
||||
"result": ev.get("result"), "error": ev.get("error")}
|
||||
HUB.publish({"t": "run_done", "run_id": run_id, "ok": ok,
|
||||
"error": ev.get("error")})
|
||||
elif timed_out:
|
||||
msg = f"插件执行超时({timeout}s)已强制终止"
|
||||
with RUN_LOCK:
|
||||
RUNS[run_id] = {"status": "error", "result": None, "error": msg}
|
||||
HUB.publish({"t": "run_done", "run_id": run_id, "ok": False, "error": msg})
|
||||
else:
|
||||
msg = f"执行进程异常退出(exit={proc.returncode})且未返回结果"
|
||||
with RUN_LOCK:
|
||||
RUNS[run_id] = {"status": "error", "result": None, "error": msg}
|
||||
HUB.publish({"t": "run_done", "run_id": run_id, "ok": False, "error": msg})
|
||||
|
||||
|
||||
@app.post("/api/runs", status_code=202)
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""插件执行子进程入口(进程级隔离)。
|
||||
|
||||
由底座 main 以 `python -m webhost.backend.plugin_runner --plugin <id>` 拉起,
|
||||
fields 经 stdin(单行 JSON) 传入,插件 `run()` 在本子进程执行:
|
||||
- 死循环 / sys.exit() / 内存爬升 不会拖垮底座(底座可超时 kill 本进程)
|
||||
- log / progress 经 stdout 输出 JSON 行,底座解析后转发 WebSocket
|
||||
- get_session / get_user_id 在本进程内直接读取共享 cookie 文件重建,不依赖主进程
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
|
||||
|
||||
def _bootstrap_paths() -> str:
|
||||
"""把项目根插入 sys.path 并 chdir,保证 desktop/ 与 webhost/ 可被 import。"""
|
||||
root = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
if root not in sys.path:
|
||||
sys.path.insert(0, root)
|
||||
return root
|
||||
|
||||
|
||||
_ROOT = _bootstrap_paths()
|
||||
try:
|
||||
os.chdir(_ROOT)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
def _emit(obj: dict) -> None:
|
||||
"""写一行 JSON 到协议通道(原始 stdout)。插件 print 已改道 stderr,不污染协议。"""
|
||||
try:
|
||||
_PROTO.write(json.dumps(obj, ensure_ascii=False) + "\n")
|
||||
_PROTO.flush()
|
||||
except Exception: # noqa: BLE001 通道已关则静默
|
||||
pass
|
||||
|
||||
|
||||
def _run() -> int:
|
||||
# 协议通道 = 原始 sys.stdout(fd1);把插件的 print 改道到 stderr,防止污染协议行
|
||||
global _PROTO
|
||||
_PROTO = sys.stdout
|
||||
sys.stdout = sys.stderr
|
||||
|
||||
from webhost.backend.plugins import PLUGINS, load_plugins # 延迟 import(需已就位 sys.path)
|
||||
from webhost.backend.plugins.base import RunContext
|
||||
from webhost.backend import auth as platform_auth
|
||||
|
||||
# 解析参数
|
||||
args = dict(a.split("=", 1) for a in sys.argv[1:] if "=" in a)
|
||||
plugin_id = args.get("--plugin") or (sys.argv[sys.argv.index("--plugin") + 1]
|
||||
if "--plugin" in sys.argv else "")
|
||||
if not plugin_id:
|
||||
_emit({"ev": "result", "ok": False, "error": "缺少 --plugin 参数"})
|
||||
return 2
|
||||
|
||||
# fields 经 stdin 传入(单行 JSON)
|
||||
fields: dict = {}
|
||||
try:
|
||||
_line = sys.stdin.readline().strip()
|
||||
if _line:
|
||||
fields = json.loads(_line) or {}
|
||||
except Exception as _e: # noqa: BLE001
|
||||
fields = {}
|
||||
|
||||
class _ChildContext(RunContext):
|
||||
"""子进程版上下文:log/progress 经 stdout 回传;登录态在本进程重建。"""
|
||||
|
||||
def __init__(self, run_id: str, plugin_id: str, auth):
|
||||
super().__init__(hub=None, run_id=run_id, plugin_id=plugin_id, auth=auth)
|
||||
|
||||
def log(self, msg: str, level: str = "INFO"):
|
||||
_emit({"ev": "log", "level": level, "msg": str(msg)})
|
||||
|
||||
def progress(self, pct: int):
|
||||
_emit({"ev": "progress", "pct": int(max(0, min(100, pct)))})
|
||||
|
||||
try:
|
||||
load_plugins()
|
||||
plugin = PLUGINS.find(plugin_id)
|
||||
ctx = _ChildContext(run_id=args.get("--run", ""), plugin_id=plugin_id,
|
||||
auth=platform_auth)
|
||||
result = plugin.run(fields, ctx)
|
||||
_emit({"ev": "result", "ok": True, "result": result})
|
||||
return 0
|
||||
except KeyError:
|
||||
_emit({"ev": "result", "ok": False, "error": f"插件未找到: {plugin_id}"})
|
||||
return 3
|
||||
except Exception as _e: # noqa: BLE001 插件顶层兜底
|
||||
import traceback
|
||||
traceback.print_exc()
|
||||
_emit({"ev": "result", "ok": False, "error": str(_e)})
|
||||
return 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(_run())
|
||||
@@ -63,14 +63,6 @@
|
||||
<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>
|
||||
@@ -78,7 +70,6 @@
|
||||
<main class="main">
|
||||
<div class="page-scroll panel">
|
||||
<PluginPage v-if="store.view === 'plugin'" />
|
||||
<ManagementView v-else-if="store.view === 'admin'" />
|
||||
</div>
|
||||
<LogPanel />
|
||||
</main>
|
||||
@@ -90,7 +81,6 @@
|
||||
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, adminLogout } from './api'
|
||||
|
||||
@@ -39,7 +39,7 @@ export function connectWS(onEvent) {
|
||||
return ws
|
||||
}
|
||||
|
||||
// ===== 控制面管理(统一后端数据库 API,经底座后端代理) =====
|
||||
// ===== 统一账户登录/会话(底座仅保留认证与个人密码,管理走中心机控制面) =====
|
||||
export async function adminMe() {
|
||||
return j('/api/admin/me')
|
||||
}
|
||||
@@ -52,9 +52,6 @@ export async function adminLogout() {
|
||||
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) {
|
||||
@@ -63,31 +60,4 @@ async function jj(url, opts) {
|
||||
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 })
|
||||
}
|
||||
@@ -1,229 +0,0 @@
|
||||
<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>
|
||||
Reference in New Issue
Block a user