1. 移除naive-ui依赖,迁移前端至Element Plus 2. 重构后端数据库层,切换为MySQL替代SQLite 3. 调整项目部署架构,停止exe打包改为源码部署 4. 新增设备上报接口与相关数据库模型 5. 优化配置路径与SQL语法,替换为MySQL占位符格式 6. 调整站点名称与文案,统一为「37du 插件管理平台」 7. 新增SQLite到MySQL迁移脚本
625 lines
33 KiB
Python
625 lines
33 KiB
Python
# -*- coding: utf-8 -*-
|
||
"""管理侧路由(写操作,需正确 token):账号 CRUD / 插件上传与维护 / 授权 / 看板 / 审计 / 运行记录。
|
||
|
||
所有写操作均以 `_require_admin`(X-API-Token + X-Admin-Token 管理员票据)把关。
|
||
"""
|
||
from __future__ import annotations
|
||
|
||
import hashlib
|
||
import json
|
||
from datetime import datetime, timedelta
|
||
from pathlib import Path
|
||
|
||
from fastapi import APIRouter, File, Header, HTTPException, Query, UploadFile
|
||
from fastapi.responses import FileResponse
|
||
|
||
from controlplane import config, schemas
|
||
from controlplane.core.auth import _require_admin, _resolve_login
|
||
from controlplane.core.crypto import _hash_password
|
||
from controlplane.core.db import _audit, _db, _now
|
||
from controlplane.core.pkgutil import (
|
||
_SAFE_NAME_RE, _extract_manifest, _load_manifest, _prune_versions,
|
||
_validate_pkg_zip, _version_key,
|
||
)
|
||
|
||
router = APIRouter()
|
||
|
||
|
||
# ==================== 账号 CRUD(统一账户,含部门;仅管理员可操作) ====================
|
||
@router.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 id, account, is_admin, dept, nickname, dingtalk_uid, must_change_pwd, "
|
||
" avatar, status, created_at "
|
||
"FROM accounts ORDER BY id")]
|
||
for a in rows:
|
||
a["plugins"] = [dict(r)["plugin_id"] for r in conn.execute(
|
||
"SELECT plugin_id FROM account_plugins WHERE account = %s", (a["account"],))]
|
||
a["grants"] = [dict(r) for r in conn.execute(
|
||
"SELECT plugin_id, can_download, can_run FROM account_plugins WHERE account = %s",
|
||
(a["account"],))]
|
||
a["platforms"] = [dict(r)["platform_id"] for r in conn.execute(
|
||
"SELECT platform_id FROM account_platforms WHERE account = %s", (a["account"],))]
|
||
return {"accounts": rows}
|
||
|
||
|
||
@router.post("/api/admin/account")
|
||
def admin_account_create(a: schemas.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 = %s", (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, nickname, "
|
||
"created_at) VALUES (%s, %s, %s, %s, %s, %s, %s)",
|
||
(account, _hex, _salt, int(a.is_admin), (a.dept or "").strip(),
|
||
(a.nickname or "").strip(), _now()))
|
||
conn.commit()
|
||
return {"ok": True, "account": account, "dept": (a.dept or "").strip(),
|
||
"nickname": (a.nickname or "").strip(), "is_admin": a.is_admin}
|
||
|
||
|
||
@router.post("/api/admin/account/update")
|
||
def admin_account_update(a: schemas.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 = %s", (account,)).fetchone():
|
||
raise HTTPException(400, f"账号 {account} 不存在")
|
||
if a.dept is not None:
|
||
conn.execute("UPDATE accounts SET dept = %s WHERE account = %s",
|
||
((a.dept or "").strip(), account))
|
||
if a.nickname is not None:
|
||
conn.execute("UPDATE accounts SET nickname = %s WHERE account = %s",
|
||
((a.nickname or "").strip(), account))
|
||
if a.is_admin is not None:
|
||
# 禁止撤销自己的管理员身份,避免把自己锁在门外
|
||
if a.is_admin:
|
||
conn.execute("UPDATE accounts SET is_admin = 1 WHERE account = %s", (account,))
|
||
else:
|
||
conn.execute("UPDATE accounts SET is_admin = 0 WHERE account = %s AND account <> %s",
|
||
(account, login))
|
||
if a.status is not None:
|
||
# 禁止停用自己,避免把自己锁在门外
|
||
if not a.status and account == login:
|
||
raise HTTPException(400, "不能停用当前登录的账号")
|
||
conn.execute("UPDATE accounts SET status = %s WHERE account = %s",
|
||
(int(bool(a.status)), account))
|
||
conn.commit()
|
||
return {"ok": True, "account": account}
|
||
|
||
|
||
@router.post("/api/admin/account/reset_pwd")
|
||
def admin_account_reset(r: schemas.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 = %s", (account,)).fetchone():
|
||
raise HTTPException(400, f"账号 {account} 不存在")
|
||
_hex, _salt = _hash_password(r.new_password)
|
||
conn.execute("UPDATE accounts SET password_hash = %s, salt = %s WHERE account = %s",
|
||
(_hex, _salt, account))
|
||
conn.commit()
|
||
return {"ok": True, "account": account}
|
||
|
||
|
||
@router.post("/api/admin/account/delete")
|
||
def admin_account_delete(d: schemas.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 = %s", (account,)).fetchone():
|
||
raise HTTPException(400, f"账号 {account} 不存在")
|
||
# account_plugins / account_platforms 由外键 ON DELETE CASCADE 级联清理
|
||
conn.execute("DELETE FROM accounts WHERE account = %s", (account,))
|
||
conn.commit()
|
||
return {"ok": True, "account": account}
|
||
|
||
|
||
# ==================== 头像(自服务可传自己;管理员可传任意账号) ====================
|
||
_AVATAR_EXT = {".jpg", ".jpeg", ".png", ".gif", ".webp"}
|
||
|
||
|
||
@router.post("/api/admin/avatar")
|
||
def admin_avatar_upload(file: UploadFile = File(...),
|
||
account: str = Query(...),
|
||
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:
|
||
"""上传账号头像:自服务传自己;管理员可传任意账号。覆盖旧头像。"""
|
||
try:
|
||
login = _resolve_login(x_admin_token, x_api_token, x_admin_user)
|
||
except Exception:
|
||
raise HTTPException(401, "登录态无效或已过期,请重新登录")
|
||
account = account.strip()
|
||
if not account:
|
||
raise HTTPException(400, "account 不能为空")
|
||
if account != login:
|
||
_require_admin(x_admin_token, x_api_token)
|
||
ext = Path(file.filename or "").suffix.lower()
|
||
if ext not in _AVATAR_EXT:
|
||
raise HTTPException(400, "仅支持图片格式(jpg/png/gif/webp)")
|
||
content = file.file.read()
|
||
if not content or len(content) > 2 * 1024 * 1024:
|
||
raise HTTPException(400, "头像文件为空或超过 2MB")
|
||
with _db() as conn:
|
||
if not conn.execute("SELECT 1 FROM accounts WHERE account = %s", (account,)).fetchone():
|
||
raise HTTPException(400, f"账号 {account} 不存在")
|
||
old = conn.execute("SELECT avatar FROM accounts WHERE account = %s", (account,)).fetchone()
|
||
old_name = (old["avatar"] if old else "") or ""
|
||
config.AVATAR_DIR.mkdir(parents=True, exist_ok=True)
|
||
fname = f"{account}{ext}"
|
||
(config.AVATAR_DIR / fname).write_bytes(content)
|
||
if old_name and old_name != fname: # 换扩展名时清掉旧文件,防残留
|
||
try:
|
||
(config.AVATAR_DIR / old_name).unlink(missing_ok=True)
|
||
except OSError:
|
||
pass
|
||
with _db() as conn:
|
||
conn.execute("UPDATE accounts SET avatar = %s WHERE account = %s", (fname, account))
|
||
conn.commit()
|
||
return {"ok": True, "account": account, "avatar": fname}
|
||
|
||
|
||
@router.get("/api/avatar/{account}")
|
||
def admin_avatar_get(account: str) -> FileResponse:
|
||
"""读取账号头像(前端 img 直接引用;未设置返回 404)。"""
|
||
with _db() as conn:
|
||
row = conn.execute("SELECT avatar FROM accounts WHERE account = %s", (account,)).fetchone()
|
||
if not row or not row["avatar"]:
|
||
raise HTTPException(404, "未设置头像")
|
||
path = config.AVATAR_DIR / row["avatar"]
|
||
if not path.is_file():
|
||
raise HTTPException(404, "头像文件缺失")
|
||
return FileResponse(path)
|
||
|
||
|
||
# ==================== 授权 / 插件维护 ====================
|
||
@router.post("/api/admin/account_plugins")
|
||
def admin_grant(g: schemas.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 撤。
|
||
|
||
MySQL 版合并表:权限位(can_download/can_run)即存在 account_plugins 本身,
|
||
不再有独立 plugin_grants 表;撤销即删除 account_plugins 行。
|
||
"""
|
||
_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 = %s", (account,)).fetchone():
|
||
raise HTTPException(400, f"账号 {account} 不存在,请先建号")
|
||
if not conn.execute("SELECT 1 FROM plugins WHERE id = %s", (plugin_id,)).fetchone():
|
||
raise HTTPException(400, f"插件 {plugin_id} 不存在,请先上传发布")
|
||
conn.execute(
|
||
"INSERT INTO account_plugins(account, plugin_id, can_download, can_run) "
|
||
"VALUES (%s, %s, %s, %s) "
|
||
"ON DUPLICATE KEY UPDATE can_download = VALUES(can_download), "
|
||
"can_run = VALUES(can_run)",
|
||
(account, plugin_id, int(g.can_download), int(g.can_run)))
|
||
else:
|
||
conn.execute("DELETE FROM account_plugins WHERE account = %s AND plugin_id = %s",
|
||
(account, plugin_id))
|
||
conn.commit()
|
||
_audit(account, "grant" if g.granted else "revoke-grant", plugin_id,
|
||
f"can_download={g.can_download},can_run={g.can_run}")
|
||
return {"ok": True, "account": account, "plugin_id": plugin_id, "granted": g.granted}
|
||
|
||
|
||
@router.post("/api/admin/account_platforms")
|
||
def admin_platform_grant(g: schemas.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 = %s", (account,)).fetchone():
|
||
raise HTTPException(400, f"账号 {account} 不存在,请先建号")
|
||
conn.execute(
|
||
"INSERT IGNORE INTO account_platforms(account, platform_id) VALUES (%s, %s)",
|
||
(account, platform_id))
|
||
else:
|
||
conn.execute("DELETE FROM account_platforms WHERE account = %s AND platform_id = %s",
|
||
(account, platform_id))
|
||
conn.commit()
|
||
return {"ok": True, "account": account, "platform_id": platform_id, "granted": g.granted}
|
||
|
||
|
||
@router.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 = config.PKG_DIR / filename
|
||
content = await upload.read()
|
||
if not content:
|
||
raise HTTPException(400, "上传内容为空")
|
||
_validate_pkg_zip(content)
|
||
|
||
# manifest 为插件契约权威来源:plugin.json 内 id 与路径 plugin_id 不一致时拒绝,
|
||
# 否则以 manifest.metadata 覆盖 name/category/icon/description 并整份入库。
|
||
manifest = _extract_manifest(content)
|
||
if manifest:
|
||
mid = str((manifest.get("id") or "")).strip()
|
||
if mid and mid != plugin_id:
|
||
raise HTTPException(400, f"plugin.json 内 id「{mid}」与路径 plugin_id「{plugin_id}」不一致")
|
||
name = str(manifest.get("name") or name).strip() or plugin_id
|
||
manifest_json = json.dumps(manifest, ensure_ascii=False) if manifest else "{}"
|
||
|
||
target.write_bytes(content)
|
||
pkg_sha256 = hashlib.sha256(content).hexdigest() # 供部署端装包后防篡改校验
|
||
|
||
with _db() as conn:
|
||
conn.execute(
|
||
"INSERT INTO plugins(id, name, latest_version, description, category, icon, manifest) "
|
||
"VALUES (%s, %s, %s, %s, %s, %s, %s) ON DUPLICATE KEY UPDATE "
|
||
"name = VALUES(name), manifest = VALUES(manifest)"
|
||
+ (", description = VALUES(description)" if manifest else "")
|
||
+ (", category = VALUES(category)" if manifest else "")
|
||
+ (", icon = VALUES(icon)" if manifest else ""),
|
||
(plugin_id, name, version,
|
||
(manifest or {}).get("description", ""),
|
||
(manifest or {}).get("category", ""),
|
||
(manifest or {}).get("icon", ""),
|
||
manifest_json))
|
||
conn.execute(
|
||
"INSERT INTO plugin_versions(plugin_id, version, filename, uploaded_at, sha256) "
|
||
"VALUES (%s, %s, %s, %s, %s) ON DUPLICATE KEY UPDATE "
|
||
"filename = VALUES(filename), uploaded_at = VALUES(uploaded_at), sha256 = VALUES(sha256)",
|
||
(plugin_id, version, filename, _now(), pkg_sha256))
|
||
cur = conn.execute("SELECT latest_version FROM plugins WHERE id = %s", (plugin_id,))
|
||
if _version_key(cur.fetchone()["latest_version"]) < _version_key(version):
|
||
conn.execute("UPDATE plugins SET latest_version = %s WHERE id = %s", (version, plugin_id))
|
||
stale_files = _prune_versions(conn, plugin_id)
|
||
conn.commit()
|
||
for fn in stale_files: # 超出保留数的旧版本:清 DB 记录 + 清磁盘包
|
||
try:
|
||
(config.PKG_DIR / fn).unlink(missing_ok=True)
|
||
except OSError:
|
||
pass
|
||
return {"ok": True, "plugin_id": plugin_id, "version": version, "filename": filename}
|
||
|
||
|
||
@router.post("/api/admin/plugin/delete")
|
||
def admin_plugin_delete(d: schemas.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 = %s", (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 = %s", (plugin_id,))]
|
||
# 外键 CASCADE 会连带清理 plugin_versions / account_plugins,显式删除仅作兜底保序
|
||
conn.execute("DELETE FROM account_plugins WHERE plugin_id = %s", (plugin_id,))
|
||
conn.execute("DELETE FROM plugin_versions WHERE plugin_id = %s", (plugin_id,))
|
||
conn.execute("DELETE FROM plugins WHERE id = %s", (plugin_id,))
|
||
conn.commit()
|
||
for fn in files:
|
||
try:
|
||
(config.PKG_DIR / fn).unlink(missing_ok=True)
|
||
except OSError:
|
||
pass
|
||
return {"ok": True, "plugin_id": plugin_id}
|
||
|
||
|
||
@router.post("/api/admin/plugin/patch")
|
||
def admin_plugin_patch(d: schemas.PluginPatchIn,
|
||
plugin_id: str = Query(...),
|
||
x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||
"""更新插件元信息/状态/强制更新配置。
|
||
|
||
status: published=正常 / disabled=禁用(停止发布) / revoked=下架(拒绝运行)。
|
||
force_min_version + force_deadline 组合开启强制更新(deadline 已过联线拒启旧版);
|
||
clear_force=True 清除强制更新;仅给其一且未 clear 则报 400。
|
||
"""
|
||
_require_admin(x_admin_token, x_api_token)
|
||
pid = plugin_id.strip()
|
||
if not pid:
|
||
raise HTTPException(400, "plugin_id 必填")
|
||
fields = []
|
||
vals = []
|
||
if d.name is not None and d.name.strip():
|
||
fields.append("name = %s"); vals.append(d.name.strip())
|
||
if d.description:
|
||
fields.append("description = %s"); vals.append(d.description.strip())
|
||
if d.category:
|
||
fields.append("category = %s"); vals.append(d.category.strip())
|
||
if d.icon:
|
||
fields.append("icon = %s"); vals.append(d.icon.strip())
|
||
if d.status in ("published", "disabled", "revoked"):
|
||
fields.append("status = %s"); vals.append(d.status)
|
||
# 强制更新三态:成对开启 / clear_force 清除 / 仅给其一报错
|
||
if d.force_min_version and d.force_deadline:
|
||
fields.append("force_min_version = %s"); vals.append(d.force_min_version.strip())
|
||
fields.append("force_deadline = %s"); vals.append(d.force_deadline.strip())
|
||
elif (d.force_min_version or d.force_deadline) and not d.clear_force:
|
||
raise HTTPException(400, "强制更新需同时提供 force_min_version 与 force_deadline")
|
||
elif d.clear_force:
|
||
fields.append("force_min_version = NULL")
|
||
fields.append("force_deadline = NULL")
|
||
if not fields:
|
||
return {"ok": True} # 无更新项
|
||
vals.append(pid)
|
||
with _db() as conn:
|
||
if not conn.execute("SELECT 1 FROM plugins WHERE id = %s", (pid,)).fetchone():
|
||
raise HTTPException(400, f"插件 {pid} 不存在")
|
||
conn.execute(f"UPDATE plugins SET {', '.join(fields)} WHERE id = %s", vals)
|
||
conn.commit()
|
||
_audit("", "plugin-patch", pid, ", ".join(
|
||
f"{k.split(' ')[0]}={v}" for k, v in zip(fields, vals[:-1])))
|
||
return {"ok": True, "plugin_id": pid}
|
||
|
||
|
||
# ==================== 看板 / 审计 / 运行记录 ====================
|
||
@router.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, description, category, icon, status, latest_version, "
|
||
" force_min_version, force_deadline, manifest "
|
||
"FROM plugins ORDER BY id")]
|
||
for p in plugins:
|
||
m = _load_manifest(p.pop("manifest"))
|
||
p["manifest"] = m
|
||
p["capabilities"] = m.get("capabilities") or []
|
||
p["permissions"] = m.get("permissions") or {}
|
||
props = (m.get("fields") or {}).get("properties") or {}
|
||
p["field_count"] = len(props)
|
||
p["versions"] = [dict(r) for r in conn.execute(
|
||
"SELECT version, filename, sha256, uploaded_at FROM plugin_versions "
|
||
"WHERE plugin_id = %s ORDER BY version", (p["id"],))]
|
||
p["accounts"] = [dict(r)["account"] for r in conn.execute(
|
||
"SELECT account FROM account_plugins WHERE plugin_id = %s", (p["id"],))]
|
||
p["grants"] = {dict(r)["account"]: {"canDownload": bool(dict(r)["can_download"]),
|
||
"canRun": bool(dict(r)["can_run"])}
|
||
for r in conn.execute(
|
||
"SELECT account, can_download, can_run FROM account_plugins "
|
||
"WHERE plugin_id = %s", (p["id"],))}
|
||
accounts = [dict(r) for r in conn.execute(
|
||
"SELECT id, account, is_admin, dept, nickname, avatar, status, created_at "
|
||
"FROM accounts ORDER BY id")]
|
||
for a in accounts:
|
||
a["plugins"] = [dict(r)["plugin_id"] for r in conn.execute(
|
||
"SELECT plugin_id FROM account_plugins WHERE account = %s", (a["account"],))]
|
||
a["platforms"] = [dict(r)["platform_id"] for r in conn.execute(
|
||
"SELECT platform_id FROM account_platforms WHERE account = %s", (a["account"],))]
|
||
a["grants"] = {dict(r)["plugin_id"]: {"canDownload": bool(dict(r)["can_download"]),
|
||
"canRun": bool(dict(r)["can_run"])}
|
||
for r in conn.execute(
|
||
"SELECT plugin_id, can_download, can_run FROM account_plugins "
|
||
"WHERE account = %s", (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}
|
||
|
||
|
||
@router.get("/api/admin/stats")
|
||
def admin_stats(x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||
"""数据看板:账号/插件规模 + 运行统计(次数/时长/成败)+ 近 14 天趋势 + 排行。"""
|
||
_require_admin(x_admin_token, x_api_token)
|
||
with _db() as conn:
|
||
users = dict(conn.execute(
|
||
"SELECT (SELECT COUNT(*) FROM accounts) AS total, "
|
||
"(SELECT COUNT(*) FROM accounts WHERE is_admin = 1) AS admins, "
|
||
"(SELECT COUNT(DISTINCT account) FROM account_plugins) AS authorized").fetchone())
|
||
plugins = dict(conn.execute(
|
||
"SELECT (SELECT COUNT(*) FROM plugins) AS total, "
|
||
"(SELECT COUNT(*) FROM plugins WHERE status = 'published') AS published, "
|
||
"(SELECT COUNT(*) FROM plugins WHERE status = 'disabled') AS disabled, "
|
||
"(SELECT COUNT(*) FROM plugins WHERE status = 'revoked') AS revoked").fetchone())
|
||
runs = dict(conn.execute(
|
||
"SELECT (SELECT COUNT(*) FROM runtime_reports WHERE status = 'start') AS started, "
|
||
"(SELECT COUNT(*) FROM runtime_reports WHERE status IN ('done','success')) AS success, "
|
||
"(SELECT COUNT(*) FROM runtime_reports WHERE status IN ('error','failed')) AS failed, "
|
||
"(SELECT COALESCE(SUM(duration_sec),0) FROM runtime_reports) AS duration_sec, "
|
||
"(SELECT COUNT(DISTINCT account) FROM runtime_reports WHERE account <> '') AS active_users, "
|
||
"(SELECT COUNT(DISTINCT plugin_id) FROM runtime_reports WHERE plugin_id <> '') AS active_plugins").fetchone())
|
||
|
||
# 近 14 天运行趋势(按日:触发次数 / 成功 / 失败)
|
||
trend_rows = conn.execute(
|
||
"SELECT LEFT(at,10) AS day, "
|
||
" SUM(CASE WHEN status = 'start' THEN 1 ELSE 0 END) AS runs, "
|
||
" SUM(CASE WHEN status IN ('done','success') THEN 1 ELSE 0 END) AS success, "
|
||
" SUM(CASE WHEN status IN ('error','failed') THEN 1 ELSE 0 END) AS failed "
|
||
"FROM runtime_reports WHERE at >= CURDATE() - INTERVAL 13 DAY GROUP BY day ORDER BY day"
|
||
).fetchall()
|
||
trend_map = {r["day"]: r for r in trend_rows}
|
||
trend = []
|
||
day = datetime.now() - timedelta(days=13)
|
||
for _i in range(14):
|
||
key = day.strftime("%Y-%m-%d")
|
||
r = trend_map.get(key)
|
||
trend.append({"day": key[5:], "runs": int(r["runs"] or 0) if r else 0,
|
||
"success": int(r["success"] or 0) if r else 0,
|
||
"failed": int(r["failed"] or 0) if r else 0})
|
||
day = day + timedelta(days=1)
|
||
|
||
# 插件排行:按执行次数(以 status='start' 为一次完整触发)
|
||
top_plugins = [dict(r) for r in conn.execute(
|
||
"SELECT plugin_id AS pluginId, "
|
||
" COUNT(*) AS runs, "
|
||
" SUM(CASE WHEN status = 'start' THEN 1 ELSE 0 END) AS triggered, "
|
||
" SUM(CASE WHEN status IN ('done','success') THEN 1 ELSE 0 END) AS success, "
|
||
" SUM(CASE WHEN status IN ('error','failed') THEN 1 ELSE 0 END) AS failed, "
|
||
" COALESCE(SUM(duration_sec),0) AS durationSec "
|
||
"FROM runtime_reports GROUP BY plugin_id "
|
||
"ORDER BY triggered DESC LIMIT 8")]
|
||
pnames = {dict(r)["id"]: dict(r)["name"] for r in conn.execute(
|
||
"SELECT id, name FROM plugins")}
|
||
for tp in top_plugins:
|
||
tp["name"] = pnames.get(tp["pluginId"]) or tp["pluginId"]
|
||
tp["runs"] = int(tp["triggered"] or 0)
|
||
|
||
# 活跃用户排行
|
||
top_users = [{"account": r["account"], "runs": int(r["runs"])}
|
||
for r in conn.execute(
|
||
"SELECT account, COUNT(*) AS runs FROM runtime_reports "
|
||
"WHERE status = 'start' AND account <> '' GROUP BY account "
|
||
"ORDER BY runs DESC LIMIT 8")]
|
||
|
||
# 最近运行列表
|
||
recent = [dict(r) for r in conn.execute(
|
||
"SELECT at, account, plugin_id AS pluginId, version, status, msg, duration_sec AS durationSec "
|
||
"FROM runtime_reports WHERE status <> 'start' "
|
||
"ORDER BY id DESC LIMIT 20")]
|
||
|
||
nick = {dict(r)["account"]: dict(r)["nickname"] for r in conn.execute(
|
||
"SELECT account, nickname FROM accounts")}
|
||
for tu in top_users:
|
||
tu["nickname"] = nick.get(tu["account"], "")
|
||
for rc in recent:
|
||
rc["nickname"] = nick.get(rc.get("account", ""), "")
|
||
|
||
now_day = datetime.now().strftime("%Y-%m-%d")
|
||
return {
|
||
"users": {"total": int(users["total"] or 0), "admins": int(users["admins"] or 0),
|
||
"authorized": int(users["authorized"] or 0)},
|
||
"plugins": {"total": int(plugins["total"] or 0), "published": int(plugins["published"] or 0),
|
||
"disabled": int(plugins["disabled"] or 0), "revoked": int(plugins["revoked"] or 0)},
|
||
"runs": {"total": int(runs["started"] or 0), "success": int(runs["success"] or 0),
|
||
"failed": int(runs["failed"] or 0), "durationSec": int(runs["duration_sec"] or 0),
|
||
"activeUsers": int(runs["active_users"] or 0), "activePlugins": int(runs["active_plugins"] or 0)},
|
||
"trend": trend, "topPlugins": top_plugins, "topUsers": top_users,
|
||
"recent": recent, "today": now_day,
|
||
}
|
||
|
||
|
||
@router.get("/api/admin/audit")
|
||
def admin_audit(limit: int = Query(default=200, ge=1, le=1000),
|
||
x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||
"""审计日志(最新在前,分页取 limit 条)。"""
|
||
_require_admin(x_admin_token, x_api_token)
|
||
with _db() as conn:
|
||
nick = {dict(r)["account"]: dict(r)["nickname"] for r in conn.execute(
|
||
"SELECT account, nickname FROM accounts")}
|
||
rows = [dict(r) for r in conn.execute(
|
||
"SELECT id, account, action, target, detail, at FROM audit_logs "
|
||
"ORDER BY id DESC LIMIT %s", (limit,))]
|
||
for r in rows:
|
||
r["nickname"] = nick.get(r["account"], "")
|
||
return {"auditlogs": rows}
|
||
|
||
|
||
@router.get("/api/admin/reports")
|
||
def admin_reports(limit: int = Query(default=200, ge=1, le=1000),
|
||
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:
|
||
nick = {dict(r)["account"]: dict(r)["nickname"] for r in conn.execute(
|
||
"SELECT account, nickname FROM accounts")}
|
||
rows = [dict(r) for r in conn.execute(
|
||
"SELECT id, account, device_id, plugin_id, version, status, msg, duration_sec, at "
|
||
"FROM runtime_reports ORDER BY id DESC LIMIT %s", (limit,))]
|
||
for r in rows:
|
||
r["nickname"] = nick.get(r["account"], "")
|
||
return {"reports": rows}
|
||
|
||
|
||
@router.get("/api/admin/devices")
|
||
def admin_devices(limit: int = Query(default=200, ge=1, le=1000),
|
||
x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||
"""执行机设备列表(按最近心跳倒序):环境信息 + Chrome 检测结果。"""
|
||
_require_admin(x_admin_token, x_api_token)
|
||
with _db() as conn:
|
||
rows = [dict(r) for r in conn.execute(
|
||
"SELECT device_id, account, hostname, os, ip, chrome_installed, chrome_version, "
|
||
" chrome_ok, last_seen, status, created_at, updated_at "
|
||
"FROM devices ORDER BY last_seen DESC LIMIT %s", (limit,))]
|
||
return {"devices": rows}
|
||
|
||
|
||
@router.post("/api/admin/shell-release")
|
||
async def admin_shell_release(upload: UploadFile = File(...),
|
||
version: str = Query(...),
|
||
notes: str = Query(default=""),
|
||
sha256: str = Query(default=""),
|
||
x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||
"""发布执行机壳子新版安装包:存到 shell/ + 写 version.json(管理员)。
|
||
|
||
供 agent CLI / 管理端从任意机器上传壳子安装包,执行机据此自动下载升级。
|
||
"""
|
||
_require_admin(x_admin_token, x_api_token)
|
||
version = version.strip()
|
||
if not version:
|
||
raise HTTPException(400, "version 不能为空")
|
||
if not _SAFE_NAME_RE.match(version):
|
||
raise HTTPException(400, "version 仅允许字母数字及 . _ -")
|
||
config.SHELL_DIR.mkdir(parents=True, exist_ok=True)
|
||
filename = f"setup-37du-host-{version}.exe"
|
||
content = await upload.read()
|
||
if not content:
|
||
raise HTTPException(400, "上传内容为空")
|
||
if not sha256:
|
||
sha256 = hashlib.sha256(content).hexdigest()
|
||
(config.SHELL_DIR / filename).write_bytes(content)
|
||
(config.SHELL_DIR / "version.json").write_text(
|
||
json.dumps({"version": version, "filename": filename,
|
||
"sha256": sha256, "notes": notes},
|
||
ensure_ascii=False, indent=2), encoding="utf-8")
|
||
_audit("", "shell-release", filename)
|
||
return {"ok": True, "version": version, "filename": filename, "sha256": sha256} |