1. 重构控制面前端为多页面路由架构,拆分出概览/插件/账号/权限管理页面 2. 引入Element Plus组件库优化UI样式与交互 3. 新增平台登录权限校验,支持按账号授权HR/OA平台访问 4. 新增平台登出接口与个人中心功能 5. 完善账号管理、插件授权相关API与UI交互 6. 新增防火墙、启停、自启动脚本与部署文档
861 lines
36 KiB
Python
861 lines
36 KiB
Python
# -*- coding: utf-8 -*-
|
||
"""内网插件控制面(单文件 FastAPI + SQLite,独立部署于内网服务器)。
|
||
|
||
职责(权限隔离 + 插件分发 + 版本比对),客户端只经本服务接口获取能力,不直连数据库:
|
||
- GET /api/plugins?account=<账号> 按账号返回可用插件清单(权限隔离)
|
||
- GET /api/manifest 全量插件版本清单(供客户端比对更新)
|
||
- GET /api/pkg/<plugin_id>/<version> 下载对应版本插件包(分发,包文件存磁盘)
|
||
|
||
DB:controlplane.db(同目录),三张表随时可重建(self-contained)。
|
||
包文件:packages/ 目录按 {plugin_id}_v{version}.zip 存放,DB 只记元数据索引。
|
||
|
||
可选项:CONTROLPLANE_TOKEN 非空时,客户端须带 X-API-Token 请求头(防内网随意拉取/下载)。
|
||
|
||
运行(本地 .venv):
|
||
python controlplane/app.py # 首次自动建表 + 写入种子示例数据 + 生成示例包
|
||
uvicorn controlplane.app:app --port 8800
|
||
"""
|
||
from __future__ import annotations
|
||
|
||
import base64
|
||
import hashlib
|
||
import hmac
|
||
import io
|
||
import json
|
||
import os
|
||
import re
|
||
import secrets
|
||
import sqlite3
|
||
import sys
|
||
import time
|
||
import zipfile
|
||
from contextlib import asynccontextmanager, contextmanager
|
||
from datetime import datetime
|
||
from pathlib import Path
|
||
from typing import List
|
||
|
||
from fastapi import FastAPI, File, Header, HTTPException, Query, UploadFile
|
||
from fastapi.middleware.cors import CORSMiddleware
|
||
from fastapi.responses import FileResponse
|
||
from fastapi.staticfiles import StaticFiles
|
||
from pydantic import BaseModel
|
||
|
||
# 数据目录定位:打包成 exe(冻结) 时统一放 exe 同目录,保证 controlplane.db / packages/ 持久可写;
|
||
# 源码运行时沿用 controlplane/ 目录。禁止用 PyInstaller 临时解压目录(重启会丢数据)。
|
||
if getattr(sys, "frozen", False):
|
||
_APP_BASE = Path(sys.executable).resolve().parent
|
||
else:
|
||
_APP_BASE = Path(__file__).resolve().parent
|
||
APP_DIR = _APP_BASE
|
||
DB_PATH = APP_DIR / "controlplane.db"
|
||
PKG_DIR = APP_DIR / "packages"
|
||
|
||
|
||
# ==================== 配置固化:加载本模块 env(controlplane/.env;免命令行传参;环境变量优先) ====================
|
||
def _load_dotenv() -> None:
|
||
"""源码模式读 controlplane/.env;exe 模式读 exe 同目录 .env。UTF-8、'#'/'空行'跳过。"""
|
||
env_path = APP_DIR / ".env"
|
||
# APP_DIR 源码态为 controlplane/,exe 态为 exe 同目录,均为本模块专属 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
|
||
pass
|
||
|
||
|
||
_load_dotenv()
|
||
|
||
CONTROLPLANE_TOKEN = os.getenv("CONTROLPLANE_TOKEN", "")
|
||
|
||
# ==================== 管理台会话(签名票据,杜绝凭用户名冒用) ====================
|
||
# 管理接口不再信任 "X-Admin-User: 用户名"(可直接 curl 伪造),改为登录后签发的签名票据。
|
||
# secret 取值优先级:CONTROLPLANE_ADMIN_SECRET(envenv) > CONTROLPLANE_TOKEN > 首次随机生成并持久化
|
||
# 到 .admin_secret 文件(保证重启不回退)。
|
||
_ADMIN_SECRET_CANDIDATE = os.getenv("CONTROLPLANE_ADMIN_SECRET") or os.getenv("CONTROLPLANE_TOKEN") or ""
|
||
|
||
|
||
def _admin_secret() -> str:
|
||
if _ADMIN_SECRET_CANDIDATE:
|
||
return _ADMIN_SECRET_CANDIDATE
|
||
global _ADMIN_SECRET_FALLBACK
|
||
if _ADMIN_SECRET_FALLBACK:
|
||
return _ADMIN_SECRET_FALLBACK
|
||
_f = APP_DIR / ".admin_secret"
|
||
if _f.is_file():
|
||
_ADMIN_SECRET_FALLBACK = _f.read_text(encoding="utf-8").strip()
|
||
else:
|
||
_ADMIN_SECRET_FALLBACK = secrets.token_hex(32)
|
||
_f.write_text(_ADMIN_SECRET_FALLBACK, encoding="utf-8")
|
||
return _ADMIN_SECRET_FALLBACK
|
||
|
||
|
||
_ADMIN_SECRET_FALLBACK = ""
|
||
_ADMIN_TOKEN_TTL = 12 * 3600 # 票据有效期 12h
|
||
|
||
|
||
def _sign_admin_token(account: str) -> str:
|
||
"""签发带过期时间的签名票据:<base64url(json)>.<hmac_sig>,内含账号,防篡改/防伪造。"""
|
||
payload = base64.urlsafe_b64encode(
|
||
json.dumps({"a": account, "e": int(time.time()) + _ADMIN_TOKEN_TTL},
|
||
separators=(",", ":")).encode()).decode().rstrip("=")
|
||
sig = hmac.new(_admin_secret().encode("utf-8"), payload.encode("utf-8"),
|
||
hashlib.sha256).hexdigest()
|
||
return f"{payload}.{sig}"
|
||
|
||
|
||
def _verify_admin_token(tok: str) -> str:
|
||
"""还原票据中的账号;签名无效或过期抛 ValueError。"""
|
||
if "." not in tok:
|
||
raise ValueError("invalid token")
|
||
payload, sig = tok.rsplit(".", 1)
|
||
expect = hmac.new(_admin_secret().encode("utf-8"), payload.encode("utf-8"),
|
||
hashlib.sha256).hexdigest()
|
||
if not secrets.compare_digest(expect, sig):
|
||
raise ValueError("bad signature")
|
||
pad = "=" * (-len(payload) % 4)
|
||
data = json.loads(base64.urlsafe_b64decode(payload + pad))
|
||
if int(data.get("e", 0)) < int(time.time()):
|
||
raise ValueError("expired")
|
||
return str(data.get("a", "") or "")
|
||
|
||
|
||
# ==================== 密码哈希(标准库 pbkdf2,盐 + 多轮) ====================
|
||
_ITER = 120_000
|
||
|
||
|
||
def _hash_password(pwd: str, salt: str = "") -> tuple[str, str]:
|
||
salt = salt or secrets.token_hex(8)
|
||
_salt = salt.encode("utf-8")
|
||
dk = hashlib.pbkdf2_hmac("sha256", pwd.encode("utf-8"), _salt, _ITER)
|
||
return dk.hex(), salt
|
||
|
||
|
||
def _verify_password(pwd: str, salt: str, hexdigest: str) -> bool:
|
||
dk = hashlib.pbkdf2_hmac("sha256", pwd.encode("utf-8"), salt.encode("utf-8"), _ITER)
|
||
return secrets.compare_digest(dk.hex(), hexdigest)
|
||
|
||
|
||
# ==================== DB 访问 ====================
|
||
@contextmanager
|
||
def _db():
|
||
"""打开连接并在退出时 commit + close(sqlite3 原生 with 语义只 commit 不 close,
|
||
长运行服务会累积连接,这里统一收口)。异常时放弃 commit 等价于回滚。"""
|
||
conn = sqlite3.connect(DB_PATH)
|
||
conn.row_factory = sqlite3.Row
|
||
try:
|
||
yield conn
|
||
conn.commit()
|
||
finally:
|
||
conn.close()
|
||
|
||
|
||
def _init_db() -> None:
|
||
"""建表(幂等)。三张表:插件本体、版本、账号权限映射。"""
|
||
with _db() as conn:
|
||
conn.executescript(
|
||
"""
|
||
CREATE TABLE IF NOT EXISTS plugins (
|
||
id TEXT PRIMARY KEY,
|
||
name TEXT NOT NULL,
|
||
latest_version TEXT NOT NULL
|
||
);
|
||
CREATE TABLE IF NOT EXISTS plugin_versions (
|
||
plugin_id TEXT NOT NULL,
|
||
version TEXT NOT NULL,
|
||
filename TEXT NOT NULL,
|
||
uploaded_at TEXT NOT NULL,
|
||
PRIMARY KEY (plugin_id, version)
|
||
);
|
||
CREATE TABLE IF NOT EXISTS account_plugins (
|
||
account TEXT NOT NULL,
|
||
plugin_id TEXT NOT NULL,
|
||
PRIMARY KEY (account, plugin_id)
|
||
);
|
||
CREATE TABLE IF NOT EXISTS account_platforms (
|
||
account TEXT NOT NULL,
|
||
platform_id TEXT NOT NULL,
|
||
PRIMARY KEY (account, platform_id)
|
||
);
|
||
CREATE TABLE IF NOT EXISTS accounts (
|
||
account TEXT PRIMARY KEY,
|
||
password_hash TEXT NOT NULL,
|
||
salt TEXT NOT NULL,
|
||
is_admin INTEGER DEFAULT 0,
|
||
dept TEXT DEFAULT ''
|
||
);
|
||
"""
|
||
)
|
||
conn.commit()
|
||
|
||
|
||
def _seed() -> None:
|
||
"""首次启动写入插件种子 + 默认管理员(puddy),并生成示例包。
|
||
|
||
不再种子 demo 普通账号(alice/bob 曾带弱口令 123456 入生产库),
|
||
普通账号一律由管理员在控制台建号。
|
||
"""
|
||
PKG_DIR.mkdir(exist_ok=True)
|
||
with _db() as conn:
|
||
conn.execute(
|
||
"INSERT OR IGNORE INTO plugins(id, name, latest_version) VALUES (?, ?, ?)",
|
||
("seal_check", "考勤月报封存检查", "1.0.0"),
|
||
)
|
||
conn.execute(
|
||
"INSERT OR IGNORE INTO plugin_versions(plugin_id, version, filename, uploaded_at) "
|
||
"VALUES (?, ?, ?, ?)",
|
||
("seal_check", "1.0.0", "seal_check_v1.0.0.zip", _now()),
|
||
)
|
||
# 默认管理员:仅作首次引导,生产环境建号后应立即改密
|
||
for _acc, _dept in (("puddy", "IT"),):
|
||
_hex, _salt = _hash_password("123456")
|
||
conn.execute(
|
||
"INSERT OR IGNORE INTO accounts(account, password_hash, salt, is_admin, dept) "
|
||
"VALUES (?, ?, ?, ?, ?)", (_acc, _hex, _salt, 1, _dept))
|
||
conn.commit()
|
||
pkg = PKG_DIR / "seal_check_v1.0.0.zip"
|
||
if not pkg.exists():
|
||
pkg.write_bytes(b"# placeholder controlplane package v1.0.0\n")
|
||
|
||
|
||
def _now() -> str:
|
||
return datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
||
|
||
|
||
# ==================== 鉴权(内部凭证 + 管理员账户) ====================
|
||
def _check_token(x_api_token: str = "") -> None:
|
||
"""底座→统一后端的内部调用凭证校验。TOKEN 空则不要求(内网可信场景)。"""
|
||
if CONTROLPLANE_TOKEN and x_api_token != CONTROLPLANE_TOKEN:
|
||
raise HTTPException(401, "鉴权失败:无效或缺失 X-API-Token")
|
||
|
||
|
||
def _require_admin(x_admin_token: str = "", x_api_token: str = "") -> str:
|
||
"""管理操作:校验内部凭证(X-API-Token) + 登录票据(X-Admin-Token)对应账号 is_admin=1。返回账号。"""
|
||
_check_token(x_api_token)
|
||
try:
|
||
account = _verify_admin_token(x_admin_token)
|
||
except Exception:
|
||
raise HTTPException(401, "登录态无效或已过期,请重新登录")
|
||
if not account:
|
||
raise HTTPException(401, "缺少有效登录态")
|
||
with _db() as conn:
|
||
row = conn.execute(
|
||
"SELECT 1 FROM accounts WHERE account = ? AND is_admin = 1", (account,)).fetchone()
|
||
if not row:
|
||
raise HTTPException(403, f"账号 {account} 无管理权限")
|
||
return account
|
||
|
||
|
||
def _resolve_login(x_admin_token: str = "", x_api_token: str = "",
|
||
x_admin_user: str = "") -> str:
|
||
"""解析请求身份(用户自助操作用,管理写操作仍走 _require_admin):
|
||
|
||
1. 优先验签名票据 X-Admin-Token(控制台直连场景);
|
||
2. 兜底接受底座正向代理注入的 X-Admin-User,但仅当 CONTROLPLANE_TOKEN 非空且
|
||
请求携带匹配的 X-API-Token 时成立(防伪造;TOKEN 为空时拒绝,fail-closed)。
|
||
"""
|
||
_check_token(x_api_token)
|
||
try:
|
||
account = _verify_admin_token(x_admin_token)
|
||
if account:
|
||
return account
|
||
except Exception:
|
||
pass
|
||
if (x_admin_user.strip() and CONTROLPLANE_TOKEN
|
||
and x_api_token == CONTROLPLANE_TOKEN):
|
||
return x_admin_user.strip()
|
||
raise ValueError("no identity")
|
||
|
||
|
||
# ==================== 登录防爆破(进程内计数,失败锁定退避) ====================
|
||
_AUTH_FAILS: dict = {} # account -> [连续失败次数, 锁定截止时间戳]
|
||
_AUTH_FAIL_LIMIT = 5 # 连续失败 N 次后锁定
|
||
_AUTH_LOCK_SECS = 300 # 锁定 5 分钟
|
||
|
||
|
||
def _auth_gate(account: str) -> None:
|
||
fails, locked_until = _AUTH_FAILS.get(account, (0, 0.0))
|
||
if locked_until > time.time():
|
||
raise HTTPException(429, f"失败次数过多,账号已临时锁定,请 {int(locked_until - time.time())} 秒后重试")
|
||
|
||
|
||
def _auth_fail(account: str) -> None:
|
||
fails, _ = _AUTH_FAILS.get(account, (0, 0.0))
|
||
fails += 1
|
||
if fails >= _AUTH_FAIL_LIMIT:
|
||
_AUTH_FAILS[account] = (0, time.time() + _AUTH_LOCK_SECS)
|
||
else:
|
||
_AUTH_FAILS[account] = (fails, 0.0)
|
||
|
||
|
||
# ==================== 请求体 ====================
|
||
class PluginOut(BaseModel):
|
||
id: str
|
||
name: str
|
||
version: str
|
||
|
||
|
||
# ==================== 应用 ====================
|
||
@asynccontextmanager
|
||
async def lifespan(app: FastAPI):
|
||
_init_db()
|
||
_seed()
|
||
yield
|
||
|
||
|
||
app = FastAPI(title="37du 内网插件控制面", lifespan=lifespan)
|
||
app.add_middleware(CORSMiddleware, allow_origins=["*"],
|
||
allow_methods=["*"], allow_headers=["*"])
|
||
|
||
|
||
@app.get("/health")
|
||
def health() -> dict:
|
||
return {"ok": True, "db": DB_PATH.name}
|
||
|
||
|
||
@app.get("/api/plugins", response_model=dict)
|
||
def plugins(account: str = Query(..., description="账号"),
|
||
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||
"""按账号返回可用插件清单(权限隔离):无权限的账号返回空列表。"""
|
||
_check_token(x_api_token)
|
||
if not account.strip():
|
||
raise HTTPException(400, "account 不能为空")
|
||
with _db() as conn:
|
||
rows = conn.execute(
|
||
"""
|
||
SELECT p.id, p.name, p.latest_version AS version
|
||
FROM plugins p
|
||
JOIN account_plugins ap ON ap.plugin_id = p.id
|
||
WHERE ap.account = ?
|
||
ORDER BY p.id
|
||
""",
|
||
(account.strip(),),
|
||
).fetchall()
|
||
return {"account": account.strip(), "plugins": [PluginOut(**dict(r)).model_dump() for r in rows]}
|
||
|
||
|
||
@app.get("/api/platforms/allowed", response_model=dict)
|
||
def platforms_allowed(account: str = Query(..., description="账号"),
|
||
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||
"""按账号返回可登录平台白名单(与插件权限同模式)。"""
|
||
_check_token(x_api_token)
|
||
if not account.strip():
|
||
raise HTTPException(400, "account 不能为空")
|
||
with _db() as conn:
|
||
rows = conn.execute(
|
||
"SELECT platform_id FROM account_platforms WHERE account = ? ORDER BY platform_id",
|
||
(account.strip(),),
|
||
).fetchall()
|
||
return {"account": account.strip(), "allowed": [dict(r)["platform_id"] for r in rows]}
|
||
|
||
|
||
@app.get("/api/manifest")
|
||
def manifest(x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||
"""全量插件版本清单:客户端据此比对是否需要拉新包。"""
|
||
_check_token(x_api_token)
|
||
with _db() as conn:
|
||
rows = conn.execute(
|
||
"""
|
||
SELECT p.id, p.name, p.latest_version AS version, pv.uploaded_at
|
||
FROM plugins p
|
||
LEFT JOIN plugin_versions pv ON pv.plugin_id = p.id AND pv.version = p.latest_version
|
||
ORDER BY p.id
|
||
"""
|
||
).fetchall()
|
||
return {"plugins": [dict(r) for r in rows], "generated_at": _now()}
|
||
|
||
|
||
@app.get("/api/pkg/{plugin_id}/{version}")
|
||
def pkg(plugin_id: str, version: str,
|
||
x_api_token: str = Header(default="", alias="X-API-Token")):
|
||
"""下载指定版本插件包。包文件存磁盘,DB 记 filename 索引。"""
|
||
_check_token(x_api_token)
|
||
with _db() as conn:
|
||
row = conn.execute(
|
||
"SELECT filename FROM plugin_versions WHERE plugin_id = ? AND version = ?",
|
||
(plugin_id, version),
|
||
).fetchone()
|
||
if not row:
|
||
raise HTTPException(404, f"未找到插件包 {plugin_id}@{version}")
|
||
path = PKG_DIR / row["filename"]
|
||
if not path.exists():
|
||
raise HTTPException(404, f"包文件缺失:{row['filename']}")
|
||
return FileResponse(path, filename=row["filename"], media_type="application/octet-stream")
|
||
|
||
|
||
# # # # # # # # # ==================== 管理侧(写操作,需正确 token) ==================== # # # # #
|
||
|
||
# 插件包约束:大小上限 / 必含文件 / 保留版本数 / 安全文件名
|
||
_PKG_MAX_BYTES = 200 * 1024 * 1024
|
||
_PKG_REQUIRED_FILES = ("plugin.json", "main.py", "requirements.txt")
|
||
_KEEP_VERSIONS = 3
|
||
_SAFE_NAME_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]*$")
|
||
|
||
|
||
def _validate_pkg_zip(content: bytes) -> None:
|
||
"""插件包完整性校验:体积上限 + ZIP 结构 + 必含文件 + plugin.json 可解析。"""
|
||
if len(content) > _PKG_MAX_BYTES:
|
||
raise HTTPException(400, f"插件包超过大小上限({_PKG_MAX_BYTES // 1024 // 1024}MB)")
|
||
try:
|
||
zf = zipfile.ZipFile(io.BytesIO(content))
|
||
except zipfile.BadZipFile:
|
||
raise HTTPException(400, "上传内容不是有效的 ZIP 包")
|
||
with zf:
|
||
if zf.testzip() is not None:
|
||
raise HTTPException(400, "ZIP 包校验失败(存在损坏条目)")
|
||
names = set(zf.namelist())
|
||
missing = [f for f in _PKG_REQUIRED_FILES if f not in names]
|
||
if missing:
|
||
raise HTTPException(
|
||
400, f"插件包缺少必需文件:{', '.join(missing)}(包根目录需含 plugin.json / main.py / requirements.txt)")
|
||
try:
|
||
json.loads(zf.read("plugin.json").decode("utf-8"))
|
||
except Exception:
|
||
raise HTTPException(400, "plugin.json 不是合法 JSON")
|
||
|
||
|
||
def _prune_versions(conn: sqlite3.Connection, plugin_id: str) -> list:
|
||
"""仅保留最近 _KEEP_VERSIONS 个版本,返回待清理的磁盘文件名列表(调用方负责删文件)。"""
|
||
rows = conn.execute(
|
||
"SELECT version, filename FROM plugin_versions WHERE plugin_id = ?", (plugin_id,)).fetchall()
|
||
stale = sorted(rows, key=lambda r: _version_key(r["version"]), reverse=True)[_KEEP_VERSIONS:]
|
||
for r in stale:
|
||
conn.execute("DELETE FROM plugin_versions WHERE plugin_id = ? AND version = ?",
|
||
(plugin_id, r["version"]))
|
||
return [r["filename"] for r in stale]
|
||
|
||
|
||
def _version_key(v: str):
|
||
"""版本比较键:数字段转 (1, int),非数字段转 (0, str),
|
||
保证任意段间可比较(如 1.0.0-beta 不再触发 int/str TypeError)。"""
|
||
def to_key(s):
|
||
try:
|
||
return (1, int(s))
|
||
except ValueError:
|
||
return (0, str(s).lower())
|
||
return tuple(to_key(x) for x in str(v).split("."))
|
||
|
||
|
||
@app.get("/api/admin/me")
|
||
def admin_me(x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||
x_api_token: str = Header(default="", alias="X-API-Token"),
|
||
x_admin_user: str = Header(default="", alias="X-Admin-User")) -> dict:
|
||
"""查询当前账号信息:管理员标识 + 部门。
|
||
|
||
身份来源:控制台直连走 X-Admin-Token 票据;底座代理走 X-Admin-User 注入(需内部凭证)。
|
||
"""
|
||
try:
|
||
account = _resolve_login(x_admin_token, x_api_token, x_admin_user)
|
||
except Exception:
|
||
account = ""
|
||
if not account:
|
||
return {"account": "", "is_admin": False, "dept": ""}
|
||
with _db() as conn:
|
||
row = conn.execute(
|
||
"SELECT is_admin, dept FROM accounts WHERE account = ?", (account,)).fetchone()
|
||
return {"account": account,
|
||
"is_admin": bool(row and row["is_admin"]),
|
||
"dept": (row["dept"] if row else "") or ""}
|
||
|
||
|
||
class AuthIn(BaseModel):
|
||
account: str
|
||
password: str
|
||
|
||
|
||
@app.post("/api/admin/auth")
|
||
def admin_auth(a: AuthIn,
|
||
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||
"""统一账户登录:所有账号均可登录(需密码正确);是否管理员由 is_admin 决定。"""
|
||
_check_token(x_api_token)
|
||
account = a.account.strip()
|
||
if not account:
|
||
raise HTTPException(400, "account 不能为空")
|
||
_auth_gate(account)
|
||
with _db() as conn:
|
||
row = conn.execute(
|
||
"SELECT password_hash, salt, is_admin, dept FROM accounts WHERE account = ?",
|
||
(account,)).fetchone()
|
||
if not row or not _verify_password(a.password, row["salt"], row["password_hash"]):
|
||
_auth_fail(account)
|
||
raise HTTPException(401, "账号或密码错误")
|
||
_AUTH_FAILS.pop(account, None)
|
||
return {"ok": True, "account": account, "is_admin": bool(row["is_admin"]),
|
||
"token": _sign_admin_token(account)}
|
||
|
||
|
||
class PwdIn(BaseModel):
|
||
account: str
|
||
old_password: str
|
||
new_password: str
|
||
|
||
|
||
@app.post("/api/admin/password")
|
||
def admin_password(p: PwdIn,
|
||
x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||
x_api_token: str = Header(default="", alias="X-API-Token"),
|
||
x_admin_user: str = Header(default="", alias="X-Admin-User")) -> dict:
|
||
"""自助修改密码:任何统一账号可改自己的密码(需旧密码校验通过)。
|
||
|
||
身份来源同 /api/admin/me:控制台票据或底座代理注入;管理写操作(改他人)仍走管理员重置接口。
|
||
"""
|
||
try:
|
||
login = _resolve_login(x_admin_token, x_api_token, x_admin_user)
|
||
except Exception:
|
||
raise HTTPException(401, "登录态无效或已过期,请重新登录")
|
||
if not p.account.strip() or not p.new_password:
|
||
raise HTTPException(400, "account 与新密码不能为空")
|
||
if p.account != login:
|
||
raise HTTPException(403, "只能修改自己的密码")
|
||
with _db() as conn:
|
||
row = conn.execute(
|
||
"SELECT password_hash, salt FROM accounts WHERE account = ?", (login,)).fetchone()
|
||
if not row or not _verify_password(p.old_password, row["salt"], row["password_hash"]):
|
||
raise HTTPException(401, "原密码错误")
|
||
_hex, _salt = _hash_password(p.new_password)
|
||
with _db() as conn:
|
||
conn.execute("UPDATE accounts SET password_hash = ?, salt = ? WHERE account = ?",
|
||
(_hex, _salt, login))
|
||
conn.commit()
|
||
return {"ok": True, "account": login}
|
||
|
||
|
||
# ==================== 账号 CRUD(统一账户,含部门;仅管理员可操作) ====================
|
||
@app.get("/api/admin/accounts")
|
||
def admin_accounts(x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||
"""全部账号(含部门/管理员标记/已授权插件/可登录平台)。"""
|
||
_require_admin(x_admin_token, x_api_token)
|
||
with _db() as conn:
|
||
rows = [dict(r) for r in conn.execute(
|
||
"SELECT account, is_admin, dept FROM accounts ORDER BY account")]
|
||
for a in rows:
|
||
a["plugins"] = [dict(r)["plugin_id"] for r in conn.execute(
|
||
"SELECT plugin_id FROM account_plugins WHERE account = ?", (a["account"],))]
|
||
a["platforms"] = [dict(r)["platform_id"] for r in conn.execute(
|
||
"SELECT platform_id FROM account_platforms WHERE account = ?", (a["account"],))]
|
||
return {"accounts": rows}
|
||
|
||
|
||
class AccountCreateIn(BaseModel):
|
||
account: str
|
||
password: str
|
||
dept: str = ""
|
||
is_admin: bool = False
|
||
|
||
|
||
@app.post("/api/admin/account")
|
||
def admin_account_create(a: AccountCreateIn,
|
||
x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||
"""新建账号:密码必填,可指定部门与是否管理员。"""
|
||
_require_admin(x_admin_token, x_api_token)
|
||
account = a.account.strip()
|
||
if not account or not a.password:
|
||
raise HTTPException(400, "account 与 password 必填")
|
||
with _db() as conn:
|
||
exists = conn.execute("SELECT 1 FROM accounts WHERE account = ?", (account,)).fetchone()
|
||
if exists:
|
||
raise HTTPException(400, f"账号 {account} 已存在")
|
||
_hex, _salt = _hash_password(a.password)
|
||
with _db() as conn:
|
||
conn.execute("INSERT INTO accounts(account, password_hash, salt, is_admin, dept) "
|
||
"VALUES (?, ?, ?, ?, ?)",
|
||
(account, _hex, _salt, int(a.is_admin), (a.dept or "").strip()))
|
||
conn.commit()
|
||
return {"ok": True, "account": account, "dept": (a.dept or "").strip(),
|
||
"is_admin": a.is_admin}
|
||
|
||
|
||
class AccountUpdateIn(BaseModel):
|
||
account: str
|
||
dept: str | None = None
|
||
is_admin: bool | None = None
|
||
|
||
|
||
@app.post("/api/admin/account/update")
|
||
def admin_account_update(a: AccountUpdateIn,
|
||
x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||
"""更新账号:改部门 / 授予或撤销管理员。"""
|
||
login = _require_admin(x_admin_token, x_api_token)
|
||
account = a.account.strip()
|
||
if not account:
|
||
raise HTTPException(400, "account 必填")
|
||
with _db() as conn:
|
||
if not conn.execute("SELECT 1 FROM accounts WHERE account = ?", (account,)).fetchone():
|
||
raise HTTPException(400, f"账号 {account} 不存在")
|
||
if a.dept is not None:
|
||
conn.execute("UPDATE accounts SET dept = ? WHERE account = ?",
|
||
((a.dept or "").strip(), account))
|
||
if a.is_admin is not None:
|
||
# 禁止撤销自己的管理员身份,避免把自己锁在门外
|
||
if a.is_admin:
|
||
conn.execute("UPDATE accounts SET is_admin = 1 WHERE account = ?", (account,))
|
||
else:
|
||
conn.execute("UPDATE accounts SET is_admin = 0 WHERE account = ? AND account <> ?",
|
||
(account, login))
|
||
conn.commit()
|
||
return {"ok": True, "account": account}
|
||
|
||
|
||
class AccountResetIn(BaseModel):
|
||
account: str
|
||
new_password: str
|
||
|
||
|
||
@app.post("/api/admin/account/reset_pwd")
|
||
def admin_account_reset(r: AccountResetIn,
|
||
x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||
"""管理员重置任意账号密码(无需原密码)。"""
|
||
_require_admin(x_admin_token, x_api_token)
|
||
account = r.account.strip()
|
||
if not account or not r.new_password:
|
||
raise HTTPException(400, "account 与新密码必填")
|
||
with _db() as conn:
|
||
if not conn.execute("SELECT 1 FROM accounts WHERE account = ?", (account,)).fetchone():
|
||
raise HTTPException(400, f"账号 {account} 不存在")
|
||
_hex, _salt = _hash_password(r.new_password)
|
||
conn.execute("UPDATE accounts SET password_hash = ?, salt = ? WHERE account = ?",
|
||
(_hex, _salt, account))
|
||
conn.commit()
|
||
return {"ok": True, "account": account}
|
||
|
||
|
||
class AccountDelIn(BaseModel):
|
||
account: str
|
||
|
||
|
||
@app.post("/api/admin/account/delete")
|
||
def admin_account_delete(d: AccountDelIn,
|
||
x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||
"""删除账号:不可删除自己;连带清除其插件授权。"""
|
||
login = _require_admin(x_admin_token, x_api_token)
|
||
account = d.account.strip()
|
||
if not account:
|
||
raise HTTPException(400, "account 必填")
|
||
if account == login:
|
||
raise HTTPException(400, "不能删除当前登录的账号")
|
||
with _db() as conn:
|
||
if not conn.execute("SELECT 1 FROM accounts WHERE account = ?", (account,)).fetchone():
|
||
raise HTTPException(400, f"账号 {account} 不存在")
|
||
conn.execute("DELETE FROM accounts WHERE account = ?", (account,))
|
||
conn.execute("DELETE FROM account_plugins WHERE account = ?", (account,))
|
||
conn.commit()
|
||
return {"ok": True, "account": account}
|
||
|
||
|
||
@app.get("/api/admin/overview")
|
||
def admin_overview(x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||
"""管理台一次性拉取:全部插件(含版本历史、被授予账号)+ 全部账号 + 管理员名单。"""
|
||
_require_admin(x_admin_token, x_api_token)
|
||
with _db() as conn:
|
||
plugins = [dict(r) for r in conn.execute(
|
||
"SELECT id, name, latest_version FROM plugins ORDER BY id")]
|
||
for p in plugins:
|
||
p["versions"] = [dict(r) for r in conn.execute(
|
||
"SELECT version, filename, uploaded_at FROM plugin_versions "
|
||
"WHERE plugin_id = ? ORDER BY version", (p["id"],))]
|
||
p["accounts"] = [dict(r)["account"] for r in conn.execute(
|
||
"SELECT account FROM account_plugins WHERE plugin_id = ?", (p["id"],))]
|
||
accounts = [dict(r) for r in conn.execute(
|
||
"SELECT account, is_admin, dept FROM accounts ORDER BY account")]
|
||
for a in accounts:
|
||
a["plugins"] = [dict(r)["plugin_id"] for r in conn.execute(
|
||
"SELECT plugin_id FROM account_plugins WHERE account = ?", (a["account"],))]
|
||
a["platforms"] = [dict(r)["platform_id"] for r in conn.execute(
|
||
"SELECT platform_id FROM account_platforms WHERE account = ?", (a["account"],))]
|
||
admins = [dict(r)["account"] for r in conn.execute(
|
||
"SELECT account FROM accounts WHERE is_admin = 1 ORDER BY account")]
|
||
return {"plugins": plugins, "accounts": accounts, "admins": admins}
|
||
|
||
|
||
@app.post("/api/admin/pkg")
|
||
async def admin_upload_plugin(upload: UploadFile = File(...),
|
||
plugin_id: str = Query(...), name: str = Query(...),
|
||
version: str = Query(...),
|
||
x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||
"""上传并发布插件包:完整性校验 → 存盘 → 登记版本 → 更新最新版 → 仅保留最近 3 个版本。"""
|
||
_require_admin(x_admin_token, x_api_token)
|
||
plugin_id = plugin_id.strip()
|
||
name = name.strip() or plugin_id
|
||
version = version.strip()
|
||
if not plugin_id or not version:
|
||
raise HTTPException(400, "plugin_id 与 version 不能为空")
|
||
# 只允许安全字符(防止拼进文件路径造成目录穿越)
|
||
if not _SAFE_NAME_RE.match(plugin_id) or not _SAFE_NAME_RE.match(version):
|
||
raise HTTPException(400, "plugin_id/version 仅允许字母数字及 . _ -")
|
||
filename = f"{plugin_id}_v{version}.zip"
|
||
target = PKG_DIR / filename
|
||
content = await upload.read()
|
||
if not content:
|
||
raise HTTPException(400, "上传内容为空")
|
||
_validate_pkg_zip(content)
|
||
target.write_bytes(content)
|
||
|
||
with _db() as conn:
|
||
conn.execute(
|
||
"INSERT INTO plugins(id, name, latest_version) VALUES (?, ?, ?) "
|
||
"ON CONFLICT(id) DO UPDATE SET name = excluded.name", (plugin_id, name, version))
|
||
conn.execute(
|
||
"INSERT INTO plugin_versions(plugin_id, version, filename, uploaded_at) "
|
||
"VALUES (?, ?, ?, ?) ON CONFLICT(plugin_id, version) DO UPDATE SET "
|
||
"filename = excluded.filename, uploaded_at = excluded.uploaded_at",
|
||
(plugin_id, version, filename, _now()))
|
||
cur = conn.execute("SELECT latest_version FROM plugins WHERE id = ?", (plugin_id,))
|
||
if _version_key(cur.fetchone()["latest_version"]) < _version_key(version):
|
||
conn.execute("UPDATE plugins SET latest_version = ? WHERE id = ?", (version, plugin_id))
|
||
stale_files = _prune_versions(conn, plugin_id)
|
||
conn.commit()
|
||
for fn in stale_files: # 超出保留数的旧版本:清 DB 记录 + 清磁盘包
|
||
try:
|
||
(PKG_DIR / fn).unlink(missing_ok=True)
|
||
except OSError:
|
||
pass
|
||
return {"ok": True, "plugin_id": plugin_id, "version": version, "filename": filename}
|
||
|
||
|
||
class GrantIn(BaseModel):
|
||
account: str
|
||
plugin_id: str
|
||
granted: bool
|
||
|
||
|
||
@app.post("/api/admin/account_plugins")
|
||
def admin_grant(g: GrantIn,
|
||
x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||
"""授予或撤销某账号对某插件的权限。granted=True 授,False 撤。"""
|
||
_require_admin(x_admin_token, x_api_token)
|
||
account = g.account.strip()
|
||
plugin_id = g.plugin_id.strip()
|
||
if not account or not plugin_id:
|
||
raise HTTPException(400, "account 与 plugin_id 不能为空")
|
||
with _db() as conn:
|
||
if g.granted:
|
||
# 只允许给已存在的统一账号授权(保证账号/授权一致性,账号在建号时即带密码)
|
||
if not conn.execute("SELECT 1 FROM accounts WHERE account = ?", (account,)).fetchone():
|
||
raise HTTPException(400, f"账号 {account} 不存在,请先建号")
|
||
conn.execute(
|
||
"INSERT OR IGNORE INTO account_plugins(account, plugin_id) VALUES (?, ?)",
|
||
(account, plugin_id))
|
||
else:
|
||
conn.execute("DELETE FROM account_plugins WHERE account = ? AND plugin_id = ?",
|
||
(account, plugin_id))
|
||
conn.commit()
|
||
return {"ok": True, "account": account, "plugin_id": plugin_id, "granted": g.granted}
|
||
|
||
|
||
class PlatformGrantIn(BaseModel):
|
||
account: str
|
||
platform_id: str
|
||
granted: bool
|
||
|
||
|
||
@app.post("/api/admin/account_platforms")
|
||
def admin_platform_grant(g: PlatformGrantIn,
|
||
x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||
"""授予或撤销某账号对某平台的登录权限。granted=True 授,False 撤。"""
|
||
_require_admin(x_admin_token, x_api_token)
|
||
account = g.account.strip()
|
||
platform_id = g.platform_id.strip()
|
||
if not account or not platform_id:
|
||
raise HTTPException(400, "account 与 platform_id 不能为空")
|
||
with _db() as conn:
|
||
if g.granted:
|
||
if not conn.execute("SELECT 1 FROM accounts WHERE account = ?", (account,)).fetchone():
|
||
raise HTTPException(400, f"账号 {account} 不存在,请先建号")
|
||
conn.execute(
|
||
"INSERT OR IGNORE INTO account_platforms(account, platform_id) VALUES (?, ?)",
|
||
(account, platform_id))
|
||
else:
|
||
conn.execute("DELETE FROM account_platforms WHERE account = ? AND platform_id = ?",
|
||
(account, platform_id))
|
||
conn.commit()
|
||
return {"ok": True, "account": account, "platform_id": platform_id, "granted": g.granted}
|
||
|
||
|
||
class PluginDelIn(BaseModel):
|
||
plugin_id: str
|
||
|
||
|
||
@app.post("/api/admin/plugin/delete")
|
||
def admin_plugin_delete(d: PluginDelIn,
|
||
x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||
"""删除插件:连带删除其全部版本记录、授权,并清理磁盘包文件。"""
|
||
_require_admin(x_admin_token, x_api_token)
|
||
plugin_id = d.plugin_id.strip()
|
||
if not plugin_id:
|
||
raise HTTPException(400, "plugin_id 必填")
|
||
with _db() as conn:
|
||
if not conn.execute("SELECT 1 FROM plugins WHERE id = ?", (plugin_id,)).fetchone():
|
||
raise HTTPException(400, f"插件 {plugin_id} 不存在")
|
||
files = [dict(r)["filename"] for r in conn.execute(
|
||
"SELECT filename FROM plugin_versions WHERE plugin_id = ?", (plugin_id,))]
|
||
conn.execute("DELETE FROM plugin_versions WHERE plugin_id = ?", (plugin_id,))
|
||
conn.execute("DELETE FROM plugins WHERE id = ?", (plugin_id,))
|
||
conn.execute("DELETE FROM account_plugins WHERE plugin_id = ?", (plugin_id,))
|
||
conn.commit()
|
||
for fn in files:
|
||
try:
|
||
(PKG_DIR / fn).unlink(missing_ok=True)
|
||
except OSError:
|
||
pass
|
||
return {"ok": True, "plugin_id": plugin_id}
|
||
|
||
|
||
# ==================== 挂载控制面前端产物 ====================
|
||
# 源码模式 => controlplane/frontend/dist;exe 模式 => sys._MEIPASS/frontend/dist(打进 exe)
|
||
if getattr(sys, "frozen", False):
|
||
DIST = Path(getattr(sys, "_MEIPASS", APP_DIR)) / "frontend" / "dist"
|
||
else:
|
||
DIST = APP_DIR / "frontend" / "dist"
|
||
|
||
if DIST.is_dir():
|
||
app.mount("/", StaticFiles(directory=str(DIST), html=True), name="web")
|
||
|
||
|
||
if __name__ == "__main__":
|
||
import uvicorn
|
||
|
||
# PyInstaller --noconsole 下 sys.stdout/stderr 可能为 None,
|
||
# uvicorn 默认 DefaultFormatter 会调用 isatty() 导致启动崩溃,故自定义日志配置绕开颜色检测。
|
||
LOG_CONFIG = {
|
||
"version": 1,
|
||
"disable_existing_loggers": False,
|
||
"formatters": {
|
||
"default": {"format": "%(asctime)s [%(levelname)s] %(name)s: %(message)s"},
|
||
"access": {"format": "%(asctime)s [%(levelname)s] %(name)s: %(message)s"},
|
||
},
|
||
"handlers": {
|
||
"default": {"class": "logging.StreamHandler", "formatter": "default"},
|
||
"access": {"class": "logging.StreamHandler", "formatter": "access"},
|
||
},
|
||
"loggers": {
|
||
"uvicorn": {"handlers": ["default"], "level": "INFO", "propagate": False},
|
||
"uvicorn.error": {"handlers": ["default"], "level": "INFO", "propagate": False},
|
||
"uvicorn.access": {"handlers": ["access"], "level": "INFO", "propagate": False},
|
||
},
|
||
}
|
||
if getattr(sys, "frozen", False):
|
||
if sys.stdout is None:
|
||
sys.stdout = open(os.devnull, "w")
|
||
if sys.stderr is None:
|
||
sys.stderr = open(os.devnull, "w")
|
||
|
||
PORT = int(os.getenv("CONTROLPLANE_PORT", "8800"))
|
||
print(f"[controlplane] http://0.0.0.0:{PORT} sqlite={DB_PATH.name}")
|
||
uvicorn.run(app, host="0.0.0.0", port=PORT, log_config=LOG_CONFIG, log_level="info") |