feat: 重构控制面安全机制与分页规范
本次提交包含多项安全加固和体验优化: 1. 分离管理密钥与传输凭证,避免持 API Token 者伪造管理员票据 2. 钉钉回调地址增加白名单校验,防止开放重定向钓鱼 3. 初始管理员密码改为随机生成并日志记录,移除硬编码 123456 4. 新增登录防爆破计数表,支持 MySQL 多 worker 共享 5. 统一分页规范,新增 usePagedList composable 和 PagerBar 组件 6. 控制面 CORS 收敛为白名单,避免公网环境下任意站点跨域 7. 插件管理、凭证管理等列表接口支持分页和搜索 8. 强制初始密码修改,未改密前禁止使用管理功能 9. 定时任务触发被拒日志节流,避免授权失效时刷屏 10. 健康检查接口移除环境信息泄露,返回固定响应
This commit is contained in:
@@ -14,10 +14,11 @@ 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.auth import _identity, _require_admin, _revoke_account_tokens
|
||||
from controlplane.core.crypto import _hash_password
|
||||
from controlplane.core.db import _audit, _db, _now
|
||||
from controlplane.core.notify import notify_account_created
|
||||
from controlplane.core.paging import count_rows, page_bounds
|
||||
from controlplane.core.pkgutil import (
|
||||
_SAFE_NAME_RE, _extract_manifest, _load_manifest, _prune_versions,
|
||||
_validate_pkg_zip, _version_key,
|
||||
@@ -28,15 +29,24 @@ router = APIRouter()
|
||||
|
||||
# ==================== 账号 CRUD(统一账户,含部门;仅管理员可操作) ====================
|
||||
@router.get("/api/admin/accounts")
|
||||
def admin_accounts(x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||||
def admin_accounts(page: int = Query(default=1, ge=1),
|
||||
page_size: int = Query(default=20, ge=1, le=1000),
|
||||
q: str = Query(default=""),
|
||||
x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||||
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||
"""全部账号(含部门/管理员标记/已授权插件/可登录平台)。"""
|
||||
"""账号列表(统一分页 + 服务端搜索 q:账号/昵称/部门模糊,含已授权插件/可登录平台)。"""
|
||||
_require_admin(x_admin_token, x_api_token)
|
||||
limit, offset = page_bounds(page, page_size)
|
||||
where, args = "", []
|
||||
if q.strip():
|
||||
where = " WHERE (account LIKE %s OR nickname LIKE %s OR dept LIKE %s)"
|
||||
args = ["%" + q.strip() + "%"] * 3
|
||||
with _db() as conn:
|
||||
total = count_rows(conn, "SELECT COUNT(*) AS c FROM accounts" + where, args)
|
||||
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")]
|
||||
"FROM accounts" + where + " ORDER BY id LIMIT %s OFFSET %s", args + [limit, offset])]
|
||||
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"],))]
|
||||
@@ -45,7 +55,7 @@ def admin_accounts(x_admin_token: str = Header(default="", alias="X-Admin-Token"
|
||||
(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}
|
||||
return {"items": rows, "total": total}
|
||||
|
||||
|
||||
@router.post("/api/admin/account")
|
||||
@@ -53,10 +63,12 @@ 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)
|
||||
login = _require_admin(x_admin_token, x_api_token)
|
||||
account = a.account.strip()
|
||||
if not account or not a.password:
|
||||
raise HTTPException(400, "account 与 password 必填")
|
||||
if len(a.password) < 8:
|
||||
raise HTTPException(400, "密码至少 8 位")
|
||||
with _db() as conn:
|
||||
exists = conn.execute("SELECT 1 FROM accounts WHERE account = %s", (account,)).fetchone()
|
||||
if exists:
|
||||
@@ -70,6 +82,8 @@ def admin_account_create(a: schemas.AccountCreateIn,
|
||||
conn.commit()
|
||||
# 钉钉工作通知(异步,失败不阻断建号):新用户收账号密码(按昵称解析),管理员收权限开通提醒
|
||||
notify_account_created(account, (a.nickname or "").strip(), a.password, source="管理台")
|
||||
_audit(login, "account-create", account,
|
||||
f"is_admin={int(a.is_admin)}, dept={(a.dept or '').strip()}")
|
||||
return {"ok": True, "account": account, "dept": (a.dept or "").strip(),
|
||||
"nickname": (a.nickname or "").strip(), "is_admin": a.is_admin}
|
||||
|
||||
@@ -106,6 +120,12 @@ def admin_account_update(a: schemas.AccountUpdateIn,
|
||||
conn.execute("UPDATE accounts SET status = %s WHERE account = %s",
|
||||
(int(bool(a.status)), account))
|
||||
conn.commit()
|
||||
if a.status is not None and not a.status:
|
||||
# 停用账号即吊销其云令牌,防止残留会话继续使用(P1 安全债)
|
||||
_revoke_account_tokens(account)
|
||||
_audit(login, "account-update", account,
|
||||
f"dept={a.dept is not None}, nickname={a.nickname is not None}, "
|
||||
f"is_admin={a.is_admin is not None}, status={a.status is not None}")
|
||||
return {"ok": True, "account": account}
|
||||
|
||||
|
||||
@@ -114,10 +134,12 @@ 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)
|
||||
login = _require_admin(x_admin_token, x_api_token)
|
||||
account = r.account.strip()
|
||||
if not account or not r.new_password:
|
||||
raise HTTPException(400, "account 与新密码必填")
|
||||
if len(r.new_password) < 8:
|
||||
raise HTTPException(400, "新密码至少 8 位")
|
||||
with _db() as conn:
|
||||
if not conn.execute("SELECT 1 FROM accounts WHERE account = %s", (account,)).fetchone():
|
||||
raise HTTPException(400, f"账号 {account} 不存在")
|
||||
@@ -125,6 +147,7 @@ def admin_account_reset(r: schemas.AccountResetIn,
|
||||
conn.execute("UPDATE accounts SET password_hash = %s, salt = %s WHERE account = %s",
|
||||
(_hex, _salt, account))
|
||||
conn.commit()
|
||||
_audit(login, "account-reset-pwd", account)
|
||||
return {"ok": True, "account": account}
|
||||
|
||||
|
||||
@@ -145,6 +168,9 @@ def admin_account_delete(d: schemas.AccountDelIn,
|
||||
# account_plugins / account_platforms 由外键 ON DELETE CASCADE 级联清理
|
||||
conn.execute("DELETE FROM accounts WHERE account = %s", (account,))
|
||||
conn.commit()
|
||||
# 删除账号即吊销其云令牌(防残留令牌继续解析,P1 安全债)
|
||||
_revoke_account_tokens(account)
|
||||
_audit(login, "account-delete", account)
|
||||
return {"ok": True, "account": account}
|
||||
|
||||
|
||||
@@ -155,17 +181,21 @@ _AVATAR_EXT = {".jpg", ".jpeg", ".png", ".gif", ".webp"}
|
||||
@router.post("/api/admin/avatar")
|
||||
def admin_avatar_upload(file: UploadFile = File(...),
|
||||
account: str = Query(...),
|
||||
authorization: str = Header(default="", alias="Authorization"),
|
||||
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)
|
||||
login = _identity(authorization=authorization, x_admin_token=x_admin_token,
|
||||
x_api_token=x_api_token, x_admin_user=x_admin_user)
|
||||
except Exception:
|
||||
raise HTTPException(401, "登录态无效或已过期,请重新登录")
|
||||
account = account.strip()
|
||||
if not account:
|
||||
raise HTTPException(400, "account 不能为空")
|
||||
if not _SAFE_NAME_RE.match(account):
|
||||
raise HTTPException(400, "account 含非法字符(仅允许字母数字及 . _ -,防止文件名穿越)")
|
||||
if account != login:
|
||||
_require_admin(x_admin_token, x_api_token)
|
||||
ext = Path(file.filename or "").suffix.lower()
|
||||
@@ -216,7 +246,7 @@ def admin_grant(g: schemas.GrantIn,
|
||||
MySQL 版合并表:权限位(can_download/can_run)即存在 account_plugins 本身,
|
||||
不再有独立 plugin_grants 表;撤销即删除 account_plugins 行。
|
||||
"""
|
||||
_require_admin(x_admin_token, x_api_token)
|
||||
login = _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:
|
||||
@@ -237,8 +267,9 @@ def admin_grant(g: schemas.GrantIn,
|
||||
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}")
|
||||
# 审计 actor 用操作者 login(可追溯"谁操作的"),target 为插件、detail 记录被授权账号
|
||||
_audit(login, "grant" if g.granted else "revoke-grant", plugin_id,
|
||||
f"account={account},can_download={g.can_download},can_run={g.can_run}")
|
||||
return {"ok": True, "account": account, "plugin_id": plugin_id, "granted": g.granted}
|
||||
|
||||
|
||||
@@ -247,7 +278,7 @@ 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)
|
||||
login = _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:
|
||||
@@ -263,6 +294,8 @@ def admin_platform_grant(g: schemas.PlatformGrantIn,
|
||||
conn.execute("DELETE FROM account_platforms WHERE account = %s AND platform_id = %s",
|
||||
(account, platform_id))
|
||||
conn.commit()
|
||||
# 审计 actor 用操作者 login,target 为平台、detail 记录被授权账号
|
||||
_audit(login, "grant-platform" if g.granted else "revoke-platform", platform_id, account)
|
||||
return {"ok": True, "account": account, "platform_id": platform_id, "granted": g.granted}
|
||||
|
||||
|
||||
@@ -273,7 +306,7 @@ async def admin_upload_plugin(upload: UploadFile = File(...),
|
||||
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)
|
||||
login = _require_admin(x_admin_token, x_api_token)
|
||||
plugin_id = plugin_id.strip()
|
||||
name = name.strip() or plugin_id
|
||||
version = version.strip()
|
||||
@@ -284,7 +317,19 @@ async def admin_upload_plugin(upload: UploadFile = File(...),
|
||||
raise HTTPException(400, "plugin_id/version 仅允许字母数字及 . _ -")
|
||||
filename = f"{plugin_id}_v{version}.zip"
|
||||
target = config.PKG_DIR / filename
|
||||
content = await upload.read()
|
||||
# 流式读取并限长(最大 200MB,与控制面插件包上限一致),避免整包先读入内存(P1 安全债)
|
||||
_MAX_PKG_BYTES = 200 * 1024 * 1024
|
||||
chunks: list[bytes] = []
|
||||
total = 0
|
||||
while True:
|
||||
chunk = await upload.read(1024 * 1024)
|
||||
if not chunk:
|
||||
break
|
||||
total += len(chunk)
|
||||
if total > _MAX_PKG_BYTES:
|
||||
raise HTTPException(413, f"插件包超过大小上限({_MAX_PKG_BYTES // (1024 * 1024)}MB)")
|
||||
chunks.append(chunk)
|
||||
content = b"".join(chunks)
|
||||
if not content:
|
||||
raise HTTPException(400, "上传内容为空")
|
||||
_validate_pkg_zip(content)
|
||||
@@ -330,6 +375,7 @@ async def admin_upload_plugin(upload: UploadFile = File(...),
|
||||
(config.PKG_DIR / fn).unlink(missing_ok=True)
|
||||
except OSError:
|
||||
pass
|
||||
_audit(login, "plugin-publish", plugin_id, f"version={version}, filename={filename}")
|
||||
return {"ok": True, "plugin_id": plugin_id, "version": version, "filename": filename}
|
||||
|
||||
|
||||
@@ -338,7 +384,7 @@ 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)
|
||||
login = _require_admin(x_admin_token, x_api_token)
|
||||
plugin_id = d.plugin_id.strip()
|
||||
if not plugin_id:
|
||||
raise HTTPException(400, "plugin_id 必填")
|
||||
@@ -357,6 +403,7 @@ def admin_plugin_delete(d: schemas.PluginDelIn,
|
||||
(config.PKG_DIR / fn).unlink(missing_ok=True)
|
||||
except OSError:
|
||||
pass
|
||||
_audit(login, "plugin-delete", plugin_id, f"files={len(files)}")
|
||||
return {"ok": True, "plugin_id": plugin_id}
|
||||
|
||||
|
||||
@@ -405,11 +452,46 @@ def admin_plugin_patch(d: schemas.PluginPatchIn,
|
||||
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])))
|
||||
f"{k.split(' ')[0]}={v}" for k, v in zip(fields, vals[:-1])) or "clear_force")
|
||||
return {"ok": True, "plugin_id": pid}
|
||||
|
||||
|
||||
# ==================== 看板 / 审计 / 运行记录 ====================
|
||||
@router.get("/api/admin/plugins")
|
||||
def admin_plugins(page: int = Query(default=1, ge=1),
|
||||
page_size: int = Query(default=20, ge=1, le=1000),
|
||||
q: str = Query(default=""),
|
||||
x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||||
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||
"""插件列表(统一分页 + 服务端搜索 q:ID/名称模糊;含状态/版本/强制更新/能力声明/版本历史/授权账号)。"""
|
||||
_require_admin(x_admin_token, x_api_token)
|
||||
limit, offset = page_bounds(page, page_size)
|
||||
where, args = "", []
|
||||
if q.strip():
|
||||
where = " WHERE (id LIKE %s OR name LIKE %s)"
|
||||
args = ["%" + q.strip() + "%"] * 2
|
||||
with _db() as conn:
|
||||
total = count_rows(conn, "SELECT COUNT(*) AS c FROM plugins" + where, args)
|
||||
rows = [dict(r) for r in conn.execute(
|
||||
"SELECT id, name, description, category, icon, status, latest_version, "
|
||||
" force_min_version, force_deadline, manifest "
|
||||
"FROM plugins" + where + " ORDER BY id LIMIT %s OFFSET %s", args + [limit, offset])]
|
||||
for p in rows:
|
||||
m = _load_manifest(p.pop("manifest"))
|
||||
p["manifest"] = m
|
||||
p["capabilities"] = m.get("capabilities") 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) for r in conn.execute(
|
||||
"SELECT ap.account, a.nickname FROM account_plugins ap "
|
||||
"LEFT JOIN accounts a ON a.account = ap.account "
|
||||
"WHERE ap.plugin_id = %s ORDER BY ap.account", (p["id"],))]
|
||||
return {"items": rows, "total": total}
|
||||
|
||||
|
||||
@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:
|
||||
@@ -430,31 +512,54 @@ def admin_overview(x_admin_token: str = Header(default="", alias="X-Admin-Token"
|
||||
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/grant_data")
|
||||
def admin_grant_data(x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||||
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||
"""授权页轻量数据:全部插件(id/name/status,一次查询无 N+1)+ 全部账号(含昵称/部门)。
|
||||
替代授权页对 /overview 全量聚合的依赖,插件/账号多时依然轻快。"""
|
||||
_require_admin(x_admin_token, x_api_token)
|
||||
with _db() as conn:
|
||||
plugins = [dict(r) for r in conn.execute(
|
||||
"SELECT id, name, status FROM plugins ORDER BY id")]
|
||||
accounts = [dict(r) for r in conn.execute(
|
||||
"SELECT account, nickname, dept, status FROM accounts "
|
||||
"WHERE status = 1 ORDER BY account")]
|
||||
return {"plugins": plugins, "accounts": accounts}
|
||||
|
||||
|
||||
@router.get("/api/admin/account_grants")
|
||||
def admin_account_grants(account: str = Query(default=""),
|
||||
x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||||
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||
"""某账号的现有授权明细:已授权插件(含 can_run/can_download)+ 已授权平台。"""
|
||||
_require_admin(x_admin_token, x_api_token)
|
||||
account = account.strip()
|
||||
with _db() as conn:
|
||||
grants = [dict(r) for r in conn.execute(
|
||||
"SELECT plugin_id, can_run, can_download FROM account_plugins "
|
||||
"WHERE account = %s ORDER BY plugin_id", (account,))]
|
||||
platforms = [dict(r)["platform_id"] for r in conn.execute(
|
||||
"SELECT platform_id FROM account_platforms "
|
||||
"WHERE account = %s ORDER BY platform_id", (account,))]
|
||||
return {
|
||||
"plugins": [{"plugin_id": g["plugin_id"],
|
||||
"canRun": bool(g["can_run"]),
|
||||
"canDownload": bool(g["can_download"])} for g in grants],
|
||||
"platforms": platforms,
|
||||
}
|
||||
|
||||
|
||||
@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:
|
||||
@@ -520,18 +625,17 @@ def admin_stats(x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||||
"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")]
|
||||
# 活跃用户排行
|
||||
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")]
|
||||
|
||||
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 {
|
||||
@@ -543,56 +647,107 @@ def admin_stats(x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||||
"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,
|
||||
"today": now_day,
|
||||
}
|
||||
|
||||
|
||||
# ==================== 审计 / 运行上报(统一分页 + 服务端筛选) ====================
|
||||
def _audit_where(action: str, q: str) -> tuple[str, list]:
|
||||
"""审计筛选条件:action 精确 + q 模糊(账号/对象/详情)。"""
|
||||
where, args = [], []
|
||||
if action.strip():
|
||||
where.append("action = %s")
|
||||
args.append(action.strip())
|
||||
if q.strip():
|
||||
where.append("(account LIKE %s OR target LIKE %s OR detail LIKE %s)")
|
||||
args += ["%" + q.strip() + "%"] * 3
|
||||
return (" WHERE " + " AND ".join(where)) if where else "", args
|
||||
|
||||
|
||||
def _report_where(status: str, q: str) -> tuple[str, list]:
|
||||
"""运行上报筛选条件:status 支持逗号分隔多值(如 done,success)+ q 模糊(账号/设备/插件/消息)。"""
|
||||
where, args = [], []
|
||||
if status.strip():
|
||||
vals = [s.strip() for s in status.split(",") if s.strip()]
|
||||
if len(vals) == 1:
|
||||
where.append("status = %s")
|
||||
args.append(vals[0])
|
||||
elif len(vals) > 1:
|
||||
where.append("status IN (%s)" % ", ".join(["%s"] * len(vals)))
|
||||
args += vals
|
||||
if q.strip():
|
||||
where.append("(account LIKE %s OR device_id LIKE %s OR plugin_id LIKE %s OR msg LIKE %s)")
|
||||
args += ["%" + q.strip() + "%"] * 4
|
||||
return (" WHERE " + " AND ".join(where)) if where else "", args
|
||||
|
||||
|
||||
@router.get("/api/admin/audit")
|
||||
def admin_audit(limit: int = Query(default=200, ge=1, le=1000),
|
||||
def admin_audit(page: int = Query(default=1, ge=1),
|
||||
page_size: int = Query(default=20, ge=1, le=1000),
|
||||
action: str = Query(default=""),
|
||||
q: str = Query(default=""),
|
||||
x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||||
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||
"""审计日志(最新在前,分页取 limit 条)。"""
|
||||
"""审计日志(统一分页 + 服务端筛选:action 操作类型、q 账号/对象/详情关键字,today 今日条数)。"""
|
||||
_require_admin(x_admin_token, x_api_token)
|
||||
limit, offset = page_bounds(page, page_size)
|
||||
where, args = _audit_where(action, q)
|
||||
with _db() as conn:
|
||||
total = count_rows(conn, "SELECT COUNT(*) AS c FROM audit_logs" + where, args)
|
||||
today = count_rows(conn, "SELECT COUNT(*) AS c FROM audit_logs WHERE at >= CURDATE()")
|
||||
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,))]
|
||||
"SELECT id, account, action, target, detail, at FROM audit_logs" + where +
|
||||
" ORDER BY id DESC LIMIT %s OFFSET %s", args + [limit, offset])]
|
||||
for r in rows:
|
||||
r["nickname"] = nick.get(r["account"], "")
|
||||
return {"auditlogs": rows}
|
||||
return {"items": rows, "total": total, "today": today}
|
||||
|
||||
|
||||
@router.get("/api/admin/reports")
|
||||
def admin_reports(limit: int = Query(default=200, ge=1, le=1000),
|
||||
def admin_reports(page: int = Query(default=1, ge=1),
|
||||
page_size: int = Query(default=20, ge=1, le=1000),
|
||||
status: str = Query(default=""),
|
||||
q: str = Query(default=""),
|
||||
x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||||
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||
"""运行上报记录(最新在前)。"""
|
||||
"""运行上报记录(统一分页 + 服务端筛选:status 状态、q 账号/设备/插件/消息,today 今日条数)。"""
|
||||
_require_admin(x_admin_token, x_api_token)
|
||||
limit, offset = page_bounds(page, page_size)
|
||||
where, args = _report_where(status, q)
|
||||
with _db() as conn:
|
||||
total = count_rows(conn, "SELECT COUNT(*) AS c FROM runtime_reports" + where, args)
|
||||
today = count_rows(conn, "SELECT COUNT(*) AS c FROM runtime_reports WHERE at >= CURDATE()")
|
||||
failed = count_rows(conn, "SELECT COUNT(*) AS c FROM runtime_reports "
|
||||
"WHERE status IN ('error','failed')")
|
||||
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,))]
|
||||
"SELECT id, account, device_id AS deviceId, plugin_id AS pluginId, version, status, msg, "
|
||||
"duration_sec AS durationSec, at "
|
||||
"FROM runtime_reports" + where + " ORDER BY id DESC LIMIT %s OFFSET %s",
|
||||
args + [limit, offset])]
|
||||
for r in rows:
|
||||
r["nickname"] = nick.get(r["account"], "")
|
||||
return {"reports": rows}
|
||||
return {"items": rows, "total": total, "today": today, "failed": failed}
|
||||
|
||||
|
||||
@router.get("/api/admin/devices")
|
||||
def admin_devices(limit: int = Query(default=200, ge=1, le=1000),
|
||||
def admin_devices(page: int = Query(default=1, ge=1),
|
||||
page_size: int = Query(default=20, 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 检测结果。"""
|
||||
"""执行机设备列表(统一分页,按最近心跳倒序):环境信息 + Chrome 检测结果。"""
|
||||
_require_admin(x_admin_token, x_api_token)
|
||||
limit, offset = page_bounds(page, page_size)
|
||||
with _db() as conn:
|
||||
total = count_rows(conn, "SELECT COUNT(*) AS c FROM devices")
|
||||
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}
|
||||
"FROM devices ORDER BY last_seen DESC LIMIT %s OFFSET %s", (limit, offset))]
|
||||
return {"items": rows, "total": total}
|
||||
|
||||
|
||||
@router.post("/api/admin/shell-release")
|
||||
@@ -606,7 +761,7 @@ async def admin_shell_release(upload: UploadFile = File(...),
|
||||
|
||||
供 agent CLI / 管理端从任意机器上传壳子安装包,执行机据此自动下载升级。
|
||||
"""
|
||||
_require_admin(x_admin_token, x_api_token)
|
||||
login = _require_admin(x_admin_token, x_api_token)
|
||||
version = version.strip()
|
||||
if not version:
|
||||
raise HTTPException(400, "version 不能为空")
|
||||
@@ -614,7 +769,19 @@ async def admin_shell_release(upload: UploadFile = File(...),
|
||||
raise HTTPException(400, "version 仅允许字母数字及 . _ -")
|
||||
config.SHELL_DIR.mkdir(parents=True, exist_ok=True)
|
||||
filename = f"setup-37du-host-{version}.exe"
|
||||
content = await upload.read()
|
||||
# 流式读取并限长(壳子安装包上限 1GB,防磁盘/内存耗尽,P1 安全债)
|
||||
_MAX_SHELL_BYTES = 1024 * 1024 * 1024
|
||||
chunks: list[bytes] = []
|
||||
total = 0
|
||||
while True:
|
||||
chunk = await upload.read(1024 * 1024)
|
||||
if not chunk:
|
||||
break
|
||||
total += len(chunk)
|
||||
if total > _MAX_SHELL_BYTES:
|
||||
raise HTTPException(413, f"壳子安装包超过大小上限({_MAX_SHELL_BYTES // (1024 * 1024)}MB)")
|
||||
chunks.append(chunk)
|
||||
content = b"".join(chunks)
|
||||
if not content:
|
||||
raise HTTPException(400, "上传内容为空")
|
||||
if not sha256:
|
||||
@@ -624,5 +791,5 @@ async def admin_shell_release(upload: UploadFile = File(...),
|
||||
json.dumps({"version": version, "filename": filename,
|
||||
"sha256": sha256, "notes": notes},
|
||||
ensure_ascii=False, indent=2), encoding="utf-8")
|
||||
_audit("", "shell-release", filename)
|
||||
_audit(login, "shell-release", filename)
|
||||
return {"ok": True, "version": version, "filename": filename, "sha256": sha256}
|
||||
@@ -10,8 +10,9 @@ from fastapi import APIRouter, Header, HTTPException
|
||||
|
||||
from controlplane import config, schemas
|
||||
from controlplane.core.auth import (
|
||||
_AUTH_FAILS, _auth_fail, _auth_gate, _check_token,
|
||||
_cloud_account, _issue_cloud_token, _resolve_login, _require_admin, _sign_admin_token,
|
||||
_auth_fail, _auth_gate, _auth_reset, _check_token,
|
||||
_cloud_account, _identity, _issue_cloud_token,
|
||||
_require_admin, _sign_admin_token,
|
||||
)
|
||||
from controlplane.core.crypto import _hash_password, _verify_password
|
||||
from controlplane.core.db import _db
|
||||
@@ -36,26 +37,28 @@ def admin_me(authorization: str = Header(default="", alias="Authorization"),
|
||||
身份来源依次:登录时签发的用户云令牌(Bearer) → 签名票据(X-Admin-Token) →
|
||||
底座注入的 X-Admin-User(仅当配了 CONTROLPLANE_TOKEN 时可信)。
|
||||
"""
|
||||
account = _cloud_account(authorization)
|
||||
try:
|
||||
account = _identity(authorization, x_admin_token, x_api_token, x_admin_user)
|
||||
except Exception:
|
||||
account = ""
|
||||
if not account:
|
||||
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": "", "nickname": "", "avatar": ""}
|
||||
return {"account": "", "is_admin": False, "dept": "", "nickname": "", "avatar": "",
|
||||
"must_change_pwd": False}
|
||||
with _db() as conn:
|
||||
row = conn.execute(
|
||||
"SELECT is_admin, dept, nickname, status, avatar FROM accounts WHERE account = %s",
|
||||
"SELECT is_admin, dept, nickname, status, avatar, must_change_pwd "
|
||||
"FROM accounts WHERE account = %s",
|
||||
(account,)).fetchone()
|
||||
# 账号停用:视为未登录(执行机/控制面前端据此自动登出)
|
||||
if not row or not row["status"]:
|
||||
return {"account": "", "is_admin": False, "dept": "", "nickname": "", "avatar": ""}
|
||||
return {"account": "", "is_admin": False, "dept": "", "nickname": "", "avatar": "",
|
||||
"must_change_pwd": False}
|
||||
return {"account": account,
|
||||
"is_admin": bool(row["is_admin"]),
|
||||
"dept": (row["dept"] if row else "") or "",
|
||||
"nickname": (row["nickname"] if row else "") or "",
|
||||
"avatar": (row["avatar"] if row else "") or ""}
|
||||
"avatar": (row["avatar"] if row else "") or "",
|
||||
"must_change_pwd": bool(row["must_change_pwd"])}
|
||||
|
||||
|
||||
@router.get("/api/admin/platforms")
|
||||
@@ -85,7 +88,7 @@ def admin_auth(a: schemas.AuthIn,
|
||||
raise HTTPException(401, "账号或密码错误")
|
||||
if not row["status"]:
|
||||
raise HTTPException(403, "账号已停用,请联系管理员")
|
||||
_AUTH_FAILS.pop(account, None)
|
||||
_auth_reset(account)
|
||||
_nickname = (row["nickname"] or "")
|
||||
return {"ok": True, "account": account, "is_admin": bool(row["is_admin"]),
|
||||
"dept": (row["dept"] or ""), "nickname": _nickname,
|
||||
@@ -102,14 +105,14 @@ def admin_password(p: schemas.PwdIn,
|
||||
x_api_token: str = Header(default="", alias="X-API-Token"),
|
||||
x_admin_user: str = Header(default="", alias="X-Admin-User")) -> dict:
|
||||
"""自助修改密码:任何统一账号可改自己的密码(需旧密码校验通过)。"""
|
||||
login = _cloud_account(authorization)
|
||||
if not login:
|
||||
try:
|
||||
login = _resolve_login(x_admin_token, x_api_token, x_admin_user)
|
||||
except Exception:
|
||||
raise HTTPException(401, "登录态无效或已过期,请重新登录")
|
||||
try:
|
||||
login = _identity(authorization, 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 len(p.new_password) < 8:
|
||||
raise HTTPException(400, "新密码至少 8 位")
|
||||
if p.account != login:
|
||||
raise HTTPException(403, "只能修改自己的密码")
|
||||
with _db() as conn:
|
||||
@@ -153,7 +156,7 @@ def auth_exchange(d: schemas.AuthExchangeIn) -> dict:
|
||||
# 找建账号(与 /api/admin/dingtalk/auth 同语义):已存在则同步昵称;不存在则自动建号并通知
|
||||
with _db() as conn:
|
||||
row = conn.execute(
|
||||
"SELECT nickname, status, must_change_pwd FROM accounts WHERE account = %s",
|
||||
"SELECT nickname, status, must_change_pwd, is_admin FROM accounts WHERE account = %s",
|
||||
(account,)).fetchone()
|
||||
if row:
|
||||
if not row["status"]:
|
||||
@@ -163,6 +166,7 @@ def auth_exchange(d: schemas.AuthExchangeIn) -> dict:
|
||||
(nickname, account))
|
||||
conn.commit()
|
||||
created, must_change = False, bool(row["must_change_pwd"])
|
||||
is_admin = bool(row["is_admin"])
|
||||
else:
|
||||
# 自动建号(空壳):初始密码取默认值,强制首次改密
|
||||
pwd = config.DINGTALK_DEFAULT_PASSWORD
|
||||
@@ -172,9 +176,9 @@ def auth_exchange(d: schemas.AuthExchangeIn) -> dict:
|
||||
"dingtalk_uid, must_change_pwd) VALUES (%s, %s, %s, 0, '', %s, %s, 1)",
|
||||
(account, _hex, _salt, nickname, unionid))
|
||||
conn.commit()
|
||||
created, must_change = True, True
|
||||
created, must_change, is_admin = True, True, False
|
||||
notify_account_created(account, nickname, pwd, unionid, source="钉钉扫码")
|
||||
token = _issue_cloud_token(account, nickname)
|
||||
return {"token": token, "account": account, "nickname": nickname,
|
||||
"exists": True, "created": created, "must_change_pwd": must_change,
|
||||
"is_admin": False}
|
||||
"exists": not created, "created": created, "must_change_pwd": must_change,
|
||||
"is_admin": is_admin}
|
||||
@@ -14,12 +14,13 @@ from __future__ import annotations
|
||||
|
||||
import json
|
||||
|
||||
from fastapi import APIRouter, Header, HTTPException
|
||||
from fastapi import APIRouter, Header, HTTPException, Query
|
||||
|
||||
from controlplane import schemas
|
||||
from controlplane.core.auth import _cloud_account, _resolve_login, _require_admin
|
||||
from controlplane.core.auth import _cloud_account, _identity, _require_admin
|
||||
from controlplane.core.crypto import rsa_encrypt
|
||||
from controlplane.core.db import _db, _now
|
||||
from controlplane.core.db import _audit, _db, _now
|
||||
from controlplane.core.paging import count_rows, page_bounds
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
@@ -74,7 +75,7 @@ def creds_seed(b: schemas.CredsSeedIn,
|
||||
仅当 pubkey_pem 非空时才需要用现有公钥给新增值加密留档;这里统一存明文源,
|
||||
/creds 下发时实时用该账号公钥加密,故无需在此预加密。
|
||||
"""
|
||||
_require_admin(x_admin_token, x_api_token)
|
||||
login = _require_admin(x_admin_token, x_api_token)
|
||||
account = b.account.strip()
|
||||
if not account:
|
||||
raise HTTPException(400, "account 不能为空")
|
||||
@@ -91,24 +92,34 @@ def creds_seed(b: schemas.CredsSeedIn,
|
||||
"INSERT INTO client_creds(account, pubkey_pem, creds, updated_at) VALUES (%s, '', %s, %s)",
|
||||
(account, json.dumps(allowed, ensure_ascii=False), _now()))
|
||||
conn.commit()
|
||||
# 敏感明文源写入属高危操作,审计留痕(不记录明文值本身)
|
||||
_audit(login, "creds-seed", account, f"keys={sorted(allowed)}")
|
||||
return {"ok": True, "account": account, "seeded_keys": sorted(allowed)}
|
||||
|
||||
|
||||
@router.get("/api/admin/creds/manage")
|
||||
def creds_manage(x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||||
def creds_manage(page: int = Query(default=1, ge=1),
|
||||
page_size: int = Query(default=20, 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:
|
||||
"""管理台:列出已注册账号及其敏感凭证明文源(管理员回显,供页面编辑;值仅管理台可见)。"""
|
||||
"""管理台:列出已注册账号及其敏感凭证明文源(统一分页,items/total;值仅管理台可见)。"""
|
||||
_require_admin(x_admin_token, x_api_token)
|
||||
limit, offset = page_bounds(page, page_size)
|
||||
with _db() as conn:
|
||||
total = count_rows(conn, "SELECT COUNT(*) AS c FROM client_creds")
|
||||
rows = conn.execute(
|
||||
"SELECT account, pubkey_pem, creds, updated_at FROM client_creds ORDER BY account").fetchall()
|
||||
"SELECT c.account, c.pubkey_pem, c.creds, c.updated_at, a.nickname "
|
||||
"FROM client_creds c LEFT JOIN accounts a ON a.account = c.account "
|
||||
"ORDER BY c.account LIMIT %s OFFSET %s", (limit, offset)).fetchall()
|
||||
return {
|
||||
"accounts": [{
|
||||
"items": [{
|
||||
"account": r["account"],
|
||||
"nickname": r["nickname"] or "",
|
||||
"has_pubkey": bool(r["pubkey_pem"]),
|
||||
"creds": json.loads(r["creds"] or "{}"),
|
||||
"updated_at": str(r["updated_at"] or ""),
|
||||
} for r in rows],
|
||||
"total": total,
|
||||
"allowed_keys": list(_ALLOWED_KEYS),
|
||||
}
|
||||
|
||||
@@ -123,12 +134,10 @@ def creds_fetch(authorization: str = Header(default="", alias="Authorization"),
|
||||
解析出账号后校验 is_admin=1,非管理员一律 403(员工无法拉取,堵住越权窃取口子)。
|
||||
用账号上报的 RSA 公钥把每个明文值 OAEP 加密为 base64;无公钥或无明文源返回空。
|
||||
"""
|
||||
account = _cloud_account(authorization)
|
||||
if not account:
|
||||
try:
|
||||
account = _resolve_login(x_admin_token, x_api_token, x_admin_user)
|
||||
except Exception:
|
||||
account = ""
|
||||
try:
|
||||
account = _identity(authorization, x_admin_token, x_api_token, x_admin_user)
|
||||
except Exception:
|
||||
account = ""
|
||||
if not account:
|
||||
raise HTTPException(401, "登录态无效或已过期,请重新登录")
|
||||
with _db() as conn:
|
||||
|
||||
@@ -6,9 +6,10 @@
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import ipaddress
|
||||
import re
|
||||
import secrets
|
||||
from urllib.parse import quote, urlencode
|
||||
from urllib.parse import quote, urlencode, urlparse
|
||||
|
||||
from fastapi import APIRouter, Header, HTTPException, Query
|
||||
from fastapi.responses import RedirectResponse
|
||||
@@ -23,6 +24,27 @@ from controlplane.core.notify import notify_account_created
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
def _safe_back_url(url: str) -> bool:
|
||||
"""回跳地址白名单:仅允许 http(s) + 回环 / 内网私有网段 / 配置的控制面域名。
|
||||
|
||||
防止开放重定向钓鱼(原实现仅校验 http(s) 前缀,可被引导到任意站点并携带身份信息)。
|
||||
"""
|
||||
if not url or not (url.startswith("http://") or url.startswith("https://")):
|
||||
return False
|
||||
host = (urlparse(url).hostname or "").lower()
|
||||
if host in ("localhost", "127.0.0.1", "::1"):
|
||||
return True
|
||||
if config.DINGTALK_CALLBACK:
|
||||
cb_host = (urlparse(config.DINGTALK_CALLBACK).hostname or "").lower()
|
||||
if host == cb_host:
|
||||
return True
|
||||
try:
|
||||
ip = ipaddress.ip_address(host)
|
||||
return bool(ip.is_loopback or ip.is_private)
|
||||
except ValueError:
|
||||
return False
|
||||
|
||||
|
||||
@router.post("/api/admin/dingtalk/auth")
|
||||
def admin_dingtalk_auth(d: schemas.DingTalkIn,
|
||||
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||
@@ -80,8 +102,8 @@ def dingtalk_scan(back: str = Query(..., description="扫码成功后的回跳
|
||||
"""扫码入口:302 到钉钉扫码登录页;state 携带部署机回跳地址,扫码成功后由 /cb 带回。"""
|
||||
if not config.DINGTALK_APP_KEY or not config.DINGTALK_APP_SECRET:
|
||||
raise HTTPException(503, "未配置钉钉开放平台应用(DINGTALK_APP_KEY / DINGTALK_APP_SECRET)")
|
||||
if not (back.startswith("http://") or back.startswith("https://")):
|
||||
raise HTTPException(400, "回跳地址非法(防止开放重定向)")
|
||||
if not _safe_back_url(back):
|
||||
raise HTTPException(400, "回跳地址非法(仅允许回环/内网/控制面域名,防止开放重定向)")
|
||||
if not config.DINGTALK_CALLBACK:
|
||||
raise HTTPException(400, "未配置 DINGTALK_CALLBACK(钉钉后台登记的回调地址)")
|
||||
login_url = "https://login.dingtalk.com/oauth2/challenge.htm?" + urlencode({
|
||||
@@ -97,8 +119,8 @@ def dingtalk_scan(back: str = Query(..., description="扫码成功后的回跳
|
||||
@router.get("/api/admin/dingtalk/cb")
|
||||
def dingtalk_cb(code: str = Query(...), state: str = Query(...)) -> RedirectResponse:
|
||||
"""钉钉回调:换 token 拉工号/姓名后,302 回部署机(state 里的回跳地址)携带身份。"""
|
||||
if not (state.startswith("http://") or state.startswith("https://")):
|
||||
raise HTTPException(400, "非法回跳地址")
|
||||
if not _safe_back_url(state):
|
||||
raise HTTPException(400, "非法回跳地址(仅允许回环/内网/控制面域名)")
|
||||
info = _dingtalk_userinfo(code)
|
||||
qs = urlencode({"account": info["account"] or "", "nickname": info["nickname"],
|
||||
"unionid": info["unionid"] or ""})
|
||||
@@ -144,8 +166,8 @@ def dingtalk_login_url(back: str = Query(...),
|
||||
_check_token(x_api_token)
|
||||
if not config.DINGTALK_APP_KEY or not config.DINGTALK_APP_SECRET:
|
||||
raise HTTPException(503, "控制面未配置钉钉开放平台应用(DINGTALK_APP_KEY / DINGTALK_APP_SECRET)")
|
||||
if not (back.startswith("http://") or back.startswith("https://")):
|
||||
raise HTTPException(400, "回跳地址非法(防止开放重定向)")
|
||||
if not _safe_back_url(back):
|
||||
raise HTTPException(400, "回跳地址非法(仅允许回环/内网/控制面域名)")
|
||||
login_url = "https://login.dingtalk.com/oauth2/challenge.htm?" + urlencode({
|
||||
"redirect_uri": back,
|
||||
"response_type": "code",
|
||||
|
||||
@@ -8,11 +8,13 @@ from __future__ import annotations
|
||||
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import APIRouter, Header, HTTPException
|
||||
from fastapi import APIRouter, Header, HTTPException, Query
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from controlplane.core.auth import _check_token, _require_admin
|
||||
from controlplane.core.db import _db, _now
|
||||
from controlplane.core.db import _audit, _db, _now
|
||||
from controlplane.core.paging import page_bounds
|
||||
from controlplane.core.pkgutil import _version_key
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
@@ -46,19 +48,23 @@ def _rows_to_dicts(rows) -> list[dict]:
|
||||
|
||||
@router.get("/api/admin/file-sources")
|
||||
def file_sources_list(category: str = "",
|
||||
page: int = Query(default=1, ge=1),
|
||||
page_size: int = Query(default=20, 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:
|
||||
"""按 category 列出大文件源(可按 category 过滤,分组也可由 category 字段区分)。"""
|
||||
_require_admin(x_admin_token, x_api_token)
|
||||
"""按 category 列出大文件源(统一分页:先按版本号数值语义排序,再切片 items/total)。"""
|
||||
login = _require_admin(x_admin_token, x_api_token)
|
||||
with _db() as conn:
|
||||
if category.strip():
|
||||
rows = conn.execute(
|
||||
"SELECT * FROM file_sources WHERE category = %s ORDER BY version, id",
|
||||
(category.strip(),)).fetchall()
|
||||
"SELECT * FROM file_sources WHERE category = %s", (category.strip(),)).fetchall()
|
||||
else:
|
||||
rows = conn.execute(
|
||||
"SELECT * FROM file_sources ORDER BY category, version, id").fetchall()
|
||||
return {"category": category, "files": _rows_to_dicts(rows)}
|
||||
rows = conn.execute("SELECT * FROM file_sources").fetchall()
|
||||
# 版本号按数值语义排序("1.10" > "1.9"),避免字符串排序取错(P2 修复)
|
||||
rows = sorted(rows, key=lambda r: (_version_key(r["version"]), r["id"]), reverse=True)
|
||||
total = len(rows)
|
||||
limit, offset = page_bounds(page, page_size)
|
||||
return {"category": category, "items": _rows_to_dicts(rows[offset:offset + limit]), "total": total}
|
||||
|
||||
|
||||
@router.post("/api/admin/file-sources")
|
||||
@@ -66,7 +72,7 @@ def file_sources_upsert(b: FileSourceIn,
|
||||
x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||||
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||
"""登记/覆盖一条大文件源(同一 category+version 去重)。"""
|
||||
_require_admin(x_admin_token, x_api_token)
|
||||
login = _require_admin(x_admin_token, x_api_token)
|
||||
category, version = b.category.strip(), b.version.strip()
|
||||
url = b.url.strip()
|
||||
if not category:
|
||||
@@ -92,6 +98,7 @@ def file_sources_upsert(b: FileSourceIn,
|
||||
b.notes.strip(), int(b.enabled), _now()))
|
||||
fid = cur.lastrowid
|
||||
conn.commit()
|
||||
_audit(login, "file-source-upsert", f"{category}@{version}", url)
|
||||
return {"ok": True, "id": fid, "category": category, "version": version}
|
||||
|
||||
|
||||
@@ -100,7 +107,7 @@ def file_sources_patch(fid: int, b: FileSourcePatch,
|
||||
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)
|
||||
login = _require_admin(x_admin_token, x_api_token)
|
||||
fields, vals = [], []
|
||||
if b.enabled is not None:
|
||||
fields.append("enabled = %s"); vals.append(int(b.enabled))
|
||||
@@ -115,6 +122,7 @@ def file_sources_patch(fid: int, b: FileSourcePatch,
|
||||
conn.commit()
|
||||
if cur.rowcount == 0:
|
||||
raise HTTPException(404, "记录不存在")
|
||||
_audit(login, "file-source-patch", str(fid), f"enabled={b.enabled}, notes={b.notes is not None}")
|
||||
return {"ok": True, "id": fid}
|
||||
|
||||
|
||||
@@ -123,12 +131,13 @@ def file_sources_delete(fid: int,
|
||||
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)
|
||||
login = _require_admin(x_admin_token, x_api_token)
|
||||
with _db() as conn:
|
||||
cur = conn.execute("DELETE FROM file_sources WHERE id = %s", (fid,))
|
||||
conn.commit()
|
||||
if cur.rowcount == 0:
|
||||
raise HTTPException(404, "记录不存在")
|
||||
_audit(login, "file-source-delete", str(fid))
|
||||
return {"ok": True, "id": fid}
|
||||
|
||||
|
||||
@@ -141,13 +150,13 @@ def file_sources_public_latest(category: str,
|
||||
"""
|
||||
_check_token(x_api_token)
|
||||
with _db() as conn:
|
||||
rows = conn.execute(
|
||||
rows = [dict(r) for r in conn.execute(
|
||||
"SELECT id, category, version, filename, url, sha256, notes FROM file_sources "
|
||||
"WHERE category = %s AND enabled = 1 ORDER BY version DESC, id DESC LIMIT 1",
|
||||
(category.strip(),)).fetchall()
|
||||
"WHERE category = %s AND enabled = 1", (category.strip(),))]
|
||||
if not rows:
|
||||
return {"available": False, "category": category.strip()}
|
||||
r = rows[0]
|
||||
# 版本号按数值语义取最新("1.10" > "1.9"),避免字符串排序取错(P2 修复)
|
||||
r = max(rows, key=lambda r: (_version_key(r["version"]), r["id"]))
|
||||
return {
|
||||
"available": True,
|
||||
"category": r["category"], "version": r["version"],
|
||||
|
||||
@@ -4,11 +4,10 @@ from __future__ import annotations
|
||||
|
||||
from fastapi import APIRouter
|
||||
|
||||
from controlplane import config
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
@router.get("/health")
|
||||
def health() -> dict:
|
||||
return {"ok": True, "db": "mysql", "host": config.MYSQL_HOST, "database": config.MYSQL_DB}
|
||||
"""健康检查:不泄露任何环境信息(原实现返回 MYSQL_HOST/库名,公网可探,P2 收敛)。"""
|
||||
return {"ok": True}
|
||||
@@ -13,7 +13,7 @@ import json
|
||||
from fastapi import APIRouter, Header, HTTPException
|
||||
from pydantic import BaseModel
|
||||
|
||||
from controlplane.core.auth import _cloud_account, _resolve_login
|
||||
from controlplane.core.auth import _identity
|
||||
from controlplane.core.db import _db, _now
|
||||
|
||||
router = APIRouter()
|
||||
@@ -23,18 +23,13 @@ class _BackupIn(BaseModel):
|
||||
data: dict = {}
|
||||
|
||||
|
||||
def _identity(authorization: str = "", x_admin_token: str = "",
|
||||
x_api_token: str = "", x_admin_user: str = "") -> str:
|
||||
"""解析请求身份;无效则抛 401。"""
|
||||
account = _cloud_account(authorization)
|
||||
if not account:
|
||||
try:
|
||||
account = _resolve_login(x_admin_token, x_api_token, x_admin_user)
|
||||
except Exception:
|
||||
account = ""
|
||||
if not account:
|
||||
def _require_identity(authorization: str = "", x_admin_token: str = "",
|
||||
x_api_token: str = "", x_admin_user: str = "") -> str:
|
||||
"""统一身份解析(core.auth._identity),无效则抛 401。"""
|
||||
try:
|
||||
return _identity(authorization, x_admin_token, x_api_token, x_admin_user)
|
||||
except Exception:
|
||||
raise HTTPException(401, "登录态无效或已过期,请重新登录")
|
||||
return account
|
||||
|
||||
|
||||
@router.post("/api/schedules/backup")
|
||||
@@ -44,7 +39,7 @@ def sched_backup_save(b: _BackupIn,
|
||||
x_api_token: str = Header(default="", alias="X-API-Token"),
|
||||
x_admin_user: str = Header(default="", alias="X-Admin-User")) -> dict:
|
||||
"""覆盖保存某账号的定时任务全量配置(执行机变更后异步推送)。"""
|
||||
account = _identity(authorization, x_admin_token, x_api_token, x_admin_user)
|
||||
account = _require_identity(authorization, x_admin_token, x_api_token, x_admin_user)
|
||||
payload = b.data if isinstance(b.data, dict) else {}
|
||||
if not isinstance(payload.get("schedules"), list):
|
||||
raise HTTPException(400, "data.schedules 必须为数组")
|
||||
@@ -63,7 +58,7 @@ def sched_backup_load(authorization: str = Header(default="", alias="Authorizati
|
||||
x_api_token: str = Header(default="", alias="X-API-Token"),
|
||||
x_admin_user: str = Header(default="", alias="X-Admin-User")) -> dict:
|
||||
"""读取某账号备份的定时任务全量配置(执行机启动时合并恢复缺失任务)。"""
|
||||
account = _identity(authorization, x_admin_token, x_api_token, x_admin_user)
|
||||
account = _require_identity(authorization, x_admin_token, x_api_token, x_admin_user)
|
||||
with _db() as conn:
|
||||
row = conn.execute(
|
||||
"SELECT data FROM schedule_backups WHERE account = %s", (account,)).fetchone()
|
||||
|
||||
@@ -18,6 +18,7 @@ X-API-Token 请求头。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import os
|
||||
import sys
|
||||
from contextlib import asynccontextmanager
|
||||
@@ -38,9 +39,16 @@ from controlplane.apis import meta as api_meta
|
||||
from controlplane.apis import plugins as api_plugins
|
||||
from controlplane.apis import schedules as api_schedules
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(app: FastAPI):
|
||||
if not config.CONTROLPLANE_TOKEN:
|
||||
# 内部凭证为空时客户端接口无鉴权(P0 安全债)。不阻断本地开发,但生产必须配置:
|
||||
# 公网部署时请务必在 controlplane/.env 设置 CONTROLPLANE_TOKEN。
|
||||
_LOGGER.error(
|
||||
"CONTROLPLANE_TOKEN 未配置:全部客户端接口将无鉴权放行,生产环境禁止!")
|
||||
_init_db()
|
||||
_seed()
|
||||
# 内网文件服务器离线监控:心跳超时判离线并钉钉告警管理员(daemon 线程)
|
||||
@@ -49,7 +57,12 @@ async def lifespan(app: FastAPI):
|
||||
|
||||
|
||||
app = FastAPI(title="37du 插件管理平台", lifespan=lifespan)
|
||||
app.add_middleware(CORSMiddleware, allow_origins=["*"],
|
||||
# CORS 收敛为白名单(原 allow_origins=["*"],控制面走公网时任何站点可跨域调接口)。
|
||||
# 默认放行本地控制面前端(8090 静态站);公网/反代部署用 CORS_ALLOW_ORIGINS 配置实际来源。
|
||||
_CORS_ORIGINS = [o.strip() for o in os.getenv(
|
||||
"CORS_ALLOW_ORIGINS",
|
||||
"http://127.0.0.1:8090,http://localhost:8090").split(",") if o.strip()]
|
||||
app.add_middleware(CORSMiddleware, allow_origins=_CORS_ORIGINS,
|
||||
allow_methods=["*"], allow_headers=["*"])
|
||||
|
||||
app.include_router(api_meta.router)
|
||||
|
||||
@@ -58,7 +58,11 @@ def _verify_admin_token(tok: str) -> str:
|
||||
|
||||
|
||||
def _require_admin(x_admin_token: str = "", x_api_token: str = "") -> str:
|
||||
"""管理操作:仅校验登录票据(X-Admin-Token)对应账号 is_admin=1(浏览器管理面免 X-API-Token)。返回账号。"""
|
||||
"""管理操作:仅校验登录票据(X-Admin-Token)对应账号 is_admin=1(浏览器管理面免 X-API-Token)。返回账号。
|
||||
|
||||
停用账号立即失效(status=0 拒绝);must_change_pwd=1(仍持初始密码)拒绝管理操作,
|
||||
强制先改密(P0/P1 安全债)。
|
||||
"""
|
||||
try:
|
||||
account = _verify_admin_token(x_admin_token)
|
||||
except Exception:
|
||||
@@ -67,9 +71,14 @@ def _require_admin(x_admin_token: str = "", x_api_token: str = "") -> str:
|
||||
raise HTTPException(401, "缺少有效登录态")
|
||||
with _db() as conn:
|
||||
row = conn.execute(
|
||||
"SELECT 1 FROM accounts WHERE account = %s AND is_admin = 1", (account,)).fetchone()
|
||||
if not row:
|
||||
"SELECT is_admin, status, must_change_pwd FROM accounts WHERE account = %s",
|
||||
(account,)).fetchone()
|
||||
if not row or not row["is_admin"]:
|
||||
raise HTTPException(403, f"账号 {account} 无管理权限")
|
||||
if not row["status"]:
|
||||
raise HTTPException(403, "账号已停用,请联系管理员")
|
||||
if row["must_change_pwd"]:
|
||||
raise HTTPException(403, "请先修改初始密码后再执行管理操作")
|
||||
return account
|
||||
|
||||
|
||||
@@ -93,25 +102,50 @@ def _resolve_login(x_admin_token: str = "", x_api_token: str = "",
|
||||
raise ValueError("no identity")
|
||||
|
||||
|
||||
# ==================== 登录防爆破(进程内计数,失败锁定退避) ====================
|
||||
_AUTH_FAILS: dict = {} # account -> [连续失败次数, 锁定截止时间戳]
|
||||
# ==================== 登录防爆破(MySQL 共享计数,gunicorn 多 worker 通用) ====================
|
||||
# 原进程内 dict 计数在多 worker 下可绕过、且无锁读写不原子;改落库 auth_fail_counts 表
|
||||
# (原子 UPSERT),锁定到期后自动重置计数,避免"锁定过期仍累计导致永久锁定"。
|
||||
_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())} 秒后重试")
|
||||
"""登录前检查:DB 记录处于锁定中则拒绝。计数失败不阻断(安全兜底:宁可放宽)。"""
|
||||
try:
|
||||
with _db() as conn:
|
||||
row = conn.execute(
|
||||
"SELECT 1 FROM auth_fail_counts WHERE account = %s AND locked_until > NOW()",
|
||||
(account,)).fetchone()
|
||||
except Exception: # noqa: BLE001
|
||||
return
|
||||
if row:
|
||||
raise HTTPException(429, "失败次数过多,账号已临时锁定,请 5 分钟后再试")
|
||||
|
||||
|
||||
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)
|
||||
"""记录一次登录失败;连续达到阈值则锁定(原子 UPSERT,多 worker 一致)。"""
|
||||
try:
|
||||
with _db() as conn:
|
||||
conn.execute(
|
||||
"INSERT INTO auth_fail_counts(account, fails, locked_until) VALUES (%s, 1, NULL) "
|
||||
"ON DUPLICATE KEY UPDATE "
|
||||
"fails = IF(locked_until IS NOT NULL AND locked_until <= NOW(), 1, fails + 1), "
|
||||
"locked_until = IF(fails + 1 >= %s, "
|
||||
"DATE_ADD(NOW(), INTERVAL %s SECOND), NULL)",
|
||||
(account, _AUTH_FAIL_LIMIT, _AUTH_LOCK_SECS))
|
||||
conn.commit()
|
||||
except Exception: # noqa: BLE001 计数失败不阻断登录流程
|
||||
pass
|
||||
|
||||
|
||||
def _auth_reset(account: str) -> None:
|
||||
"""登录成功后清除失败计数。"""
|
||||
try:
|
||||
with _db() as conn:
|
||||
conn.execute("DELETE FROM auth_fail_counts WHERE account = %s", (account,))
|
||||
conn.commit()
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
|
||||
|
||||
# ==================== 云端会话 token(员工端扫码登录,§2.2) ====================
|
||||
@@ -136,8 +170,9 @@ def _auth_account_lookup(account: str) -> dict:
|
||||
def _cloud_account(bearer: str) -> str:
|
||||
"""从 Bearer 云端会话 token 解出工号(§2.2);无效/过期/缺失返回空串。
|
||||
|
||||
查 cloud_tokens 表(落库共享):签发与解析不再受 worker 进程限制。
|
||||
库不可用时返回空串(身份解析失败不抛异常,交由各路由的兜底逻辑处理)。
|
||||
查 cloud_tokens 表(落库共享)并 JOIN accounts 校验账号存在且未停用:删号/停用后
|
||||
残留令牌立即失效(P1 安全债)。库不可用时返回空串(身份解析失败不抛异常,
|
||||
交由各路由的兜底逻辑处理)。
|
||||
"""
|
||||
token = (bearer or "").strip()
|
||||
if token.lower().startswith("bearer "):
|
||||
@@ -147,7 +182,9 @@ def _cloud_account(bearer: str) -> str:
|
||||
try:
|
||||
with _db() as conn:
|
||||
row = conn.execute(
|
||||
"SELECT account FROM cloud_tokens WHERE token = %s AND expires_at > NOW()",
|
||||
"SELECT t.account FROM cloud_tokens t "
|
||||
"JOIN accounts a ON a.account = t.account "
|
||||
"WHERE t.token = %s AND t.expires_at > NOW() AND a.status = 1",
|
||||
(token,)).fetchone()
|
||||
except Exception: # noqa: BLE001 库异常按“无身份”处理,不阻断请求
|
||||
return ""
|
||||
@@ -168,4 +205,25 @@ def _issue_cloud_token(account: str, nickname: str) -> str:
|
||||
"INSERT INTO cloud_tokens(token, account, nickname, expires_at) VALUES (%s, %s, %s, %s)",
|
||||
(token, account, nickname, expires.strftime("%Y-%m-%d %H:%M:%S")))
|
||||
conn.commit()
|
||||
return token
|
||||
return token
|
||||
|
||||
|
||||
def _identity(authorization: str = "", x_admin_token: str = "",
|
||||
x_api_token: str = "", x_admin_user: str = "") -> str:
|
||||
"""统一身份解析(三源,消除各路由复制粘贴):Bearer 云令牌 → X-Admin-Token →
|
||||
X-Admin-User(+X-API-Token)。返回账号;无有效身份抛 ValueError(调用方决定 401/空响应)。
|
||||
"""
|
||||
acct = _cloud_account(authorization)
|
||||
if acct:
|
||||
return acct
|
||||
return _resolve_login(x_admin_token, x_api_token, x_admin_user)
|
||||
|
||||
|
||||
def _revoke_account_tokens(account: str) -> None:
|
||||
"""吊销某账号全部云令牌(删号/停用时调用,防止残留令牌继续解析)。"""
|
||||
try:
|
||||
with _db() as conn:
|
||||
conn.execute("DELETE FROM cloud_tokens WHERE account = %s", (account,))
|
||||
conn.commit()
|
||||
except Exception: # noqa: BLE001 吊销失败不阻断主流程
|
||||
pass
|
||||
@@ -62,7 +62,24 @@ MYSQL_USER = os.getenv("MYSQL_USER", "root")
|
||||
MYSQL_PASSWORD = os.getenv("MYSQL_PASSWORD", "")
|
||||
MYSQL_DB = os.getenv("MYSQL_DB") or os.getenv("MYSQL_DATABASE") or "37du_center"
|
||||
# 钉钉扫码自动建号的初始密码;新号无插件权限、仅空壳,首次登录须改密。
|
||||
DINGTALK_DEFAULT_PASSWORD = os.getenv("DINGTALK_DEFAULT_PASSWORD", "123456")
|
||||
# 未配置时首次启动生成随机密码并持久化到 .dingtalk_default_pwd(重启复用,保证未改密
|
||||
# 用户拿到的初始密码稳定),经钉钉工作通知下发给本人。不再使用硬编码 123456(P0 安全债)。
|
||||
def _dingtalk_default_password() -> str:
|
||||
_v = os.getenv("DINGTALK_DEFAULT_PASSWORD", "").strip()
|
||||
if _v:
|
||||
return _v
|
||||
_f = APP_DIR / ".dingtalk_default_pwd"
|
||||
if _f.is_file():
|
||||
return _f.read_text(encoding="utf-8").strip()
|
||||
_pwd = secrets.token_urlsafe(9) # 约 12 位,大小写字母+数字,无易混淆字符
|
||||
try:
|
||||
_f.write_text(_pwd, encoding="utf-8")
|
||||
except OSError:
|
||||
pass
|
||||
return _pwd
|
||||
|
||||
|
||||
DINGTALK_DEFAULT_PASSWORD = _dingtalk_default_password()
|
||||
# 钉钉开放平台应用(真实扫码;未配置则钉钉扫码入口自动隐藏,仅保留账号密码登录)。
|
||||
# 同一套 KEY/SECRET 即可:扫码换 unionid/昵称 → gettoken 企业内部 token
|
||||
# → getbyunionid 取 userid → v2/user/get 取 job_number(工号),无需第二组凭证。
|
||||
@@ -96,9 +113,12 @@ CREDS_DEFAULT = {
|
||||
"CREDS_DINGTALK_AGENT_ID", "CREDS_DINGTALK_CORP_ID")
|
||||
}
|
||||
|
||||
# 管理台会话票据签名密钥:CONTROLPLANE_ADMIN_SECRET > CONTROLPLANE_TOKEN > 首次随机生成并
|
||||
# 持久化到 .admin_secret(保证重启不回退,杜绝凭用户名 X-Admin-User 直接伪造身份)。
|
||||
_ADMIN_SECRET_CANDIDATE = os.getenv("CONTROLPLANE_ADMIN_SECRET") or os.getenv("CONTROLPLANE_TOKEN") or ""
|
||||
# 管理台会话票据签名密钥:CONTROLPLANE_ADMIN_SECRET > .admin_secret 文件(首次随机生成并持久化,
|
||||
# 保证重启不回退,杜绝凭用户名 X-Admin-User 直接伪造身份)。
|
||||
# 注意:不再回退 CONTROLPLANE_TOKEN —— 传输凭证与管理密钥必须分离,否则持 X-API-Token 的执行机
|
||||
# 可本地 HMAC 自签任意管理员票据全量接管系统(P0 安全债)。变更该密钥会使已签发的管理票据
|
||||
# 全部失效(管理员需重新登录一次),普通用户的云令牌与底座 X-API-Token 不受影响。
|
||||
_ADMIN_SECRET_CANDIDATE = os.getenv("CONTROLPLANE_ADMIN_SECRET") or ""
|
||||
_ADMIN_SECRET_FALLBACK: str = ""
|
||||
_ADMIN_TOKEN_TTL = 12 * 3600 # 票据有效期 12h
|
||||
|
||||
|
||||
@@ -11,6 +11,9 @@ from __future__ import annotations
|
||||
|
||||
from contextlib import contextmanager
|
||||
from datetime import datetime
|
||||
import logging
|
||||
import secrets
|
||||
import time
|
||||
|
||||
import pymysql
|
||||
from pymysql.cursors import DictCursor
|
||||
@@ -18,8 +21,10 @@ from pymysql.cursors import DictCursor
|
||||
from controlplane.core import config
|
||||
from controlplane.core.crypto import _hash_password
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
# 初始迁移版本:全量 DDL 建齐后登记;后续增量 DDL 在此追加新版本并配套迁移逻辑
|
||||
_SCHEMA_VERSION = "20260919_002"
|
||||
_SCHEMA_VERSION = "20260920_001"
|
||||
|
||||
# 全量 DDL(15 张表,MySQL 5.7 兼容;与 tools/schema_mysql.sql 逐条一致)
|
||||
_DDL_TABLES = (
|
||||
@@ -258,16 +263,26 @@ _DDL_TABLES = (
|
||||
KEY idx_last_seen (last_seen)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='内网文件服务器状态(心跳上报+离线监控)'
|
||||
""",
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS auth_fail_counts (
|
||||
account VARCHAR(64) NOT NULL COMMENT '登录账号(工号,主键)',
|
||||
fails INT UNSIGNED NOT NULL DEFAULT 0 COMMENT '连续失败次数',
|
||||
locked_until DATETIME NULL COMMENT '锁定截止时间(NULL=未锁定)',
|
||||
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
|
||||
PRIMARY KEY (account)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='登录防爆破共享计数(落库,gunicorn 多 worker 通用)'
|
||||
""",
|
||||
)
|
||||
|
||||
|
||||
def _connect(server: bool = False) -> pymysql.connections.Connection:
|
||||
"""建立 PyMySQL 连接;server=True 时不指定 database(用于建库)。"""
|
||||
"""建立 PyMySQL 连接(带连接超时,防 MySQL 挂起时无限阻塞);server=True 时不指定 database(用于建库)。"""
|
||||
return pymysql.connect(
|
||||
host=config.MYSQL_HOST, port=config.MYSQL_PORT,
|
||||
user=config.MYSQL_USER, password=config.MYSQL_PASSWORD,
|
||||
database=None if server else config.MYSQL_DB,
|
||||
charset="utf8mb4", cursorclass=DictCursor, autocommit=False)
|
||||
charset="utf8mb4", cursorclass=DictCursor, autocommit=False,
|
||||
connect_timeout=10)
|
||||
|
||||
|
||||
class _DbConn:
|
||||
@@ -299,13 +314,26 @@ class _DbConn:
|
||||
|
||||
@contextmanager
|
||||
def _db():
|
||||
"""打开连接并在退出时 commit + close(统一收口,避免长运行服务累积连接)。
|
||||
"""打开连接(建立失败自动重试 3 次)并在退出时 commit + close(统一收口)。
|
||||
|
||||
与旧 sqlite3 语义一致:异常时不 commit 等价于回滚。
|
||||
与旧 sqlite3 语义一致:异常时不 commit 等价于回滚;仅连接建立阶段重试,
|
||||
业务块内异常不重试(语义不变),避免把业务失败误当连接故障无限重放。
|
||||
"""
|
||||
if not config.MYSQL_HOST:
|
||||
raise RuntimeError("未配置 MySQL 连接(MYSQL_HOST),请查看 desktop/controlplane/.env")
|
||||
conn = _connect()
|
||||
conn = None
|
||||
last_exc = None
|
||||
for _attempt in range(3):
|
||||
try:
|
||||
conn = _connect()
|
||||
break
|
||||
except Exception as _exc: # noqa: BLE001 连接失败重试(对齐 AGENTS.md 最大重试 3 次)
|
||||
last_exc = _exc
|
||||
conn = None
|
||||
if _attempt < 2:
|
||||
time.sleep(0.5 * (_attempt + 1))
|
||||
if conn is None:
|
||||
raise RuntimeError(f"MySQL 连接失败(重试 3 次后放弃):{last_exc}")
|
||||
try:
|
||||
yield _DbConn(conn)
|
||||
conn.commit()
|
||||
@@ -361,12 +389,15 @@ def _seed() -> None:
|
||||
"VALUES (%s, %s, %s, %s)",
|
||||
("seal_check", "1.0.0", "seal_check_v1.0.0.zip", _now()),
|
||||
)
|
||||
# 默认管理员:仅作首次引导,生产环境建号后应立即改密
|
||||
# 默认管理员:仅作首次引导,密码随机生成并记入日志(不再硬编码 123456,P0 安全债)。
|
||||
# 已有库不重跑本种子(INSERT IGNORE 幂等);生产环境建号后应立即改密。
|
||||
for _acc, _dept in (("puddy", "IT"),):
|
||||
_hex, _salt = _hash_password("123456")
|
||||
_pwd = secrets.token_urlsafe(9) # 约 12 位随机密码
|
||||
_hex, _salt = _hash_password(_pwd)
|
||||
conn.execute(
|
||||
"INSERT IGNORE INTO accounts(account, password_hash, salt, is_admin, dept) "
|
||||
"VALUES (%s, %s, %s, %s, %s)", (_acc, _hex, _salt, 1, _dept))
|
||||
_LOGGER.warning("首次引导:初始管理员 %s 初始密码为 %s(请立即登录修改)", _acc, _pwd)
|
||||
conn.commit()
|
||||
pkg = config.PKG_DIR / "seal_check_v1.0.0.zip"
|
||||
if not pkg.exists():
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""统一分页规范(控制面管理端列表接口)。
|
||||
|
||||
约定:
|
||||
- 请求参数统一:``page``(第 1 页起)、``page_size``(默认 20,上限 1000)
|
||||
- 响应统一:``{"items": [...], "total": int}``
|
||||
|
||||
路由用法示例:
|
||||
from fastapi import Query
|
||||
from controlplane.core.paging import page_bounds
|
||||
|
||||
@router.get("/api/admin/xxx")
|
||||
def admin_xxx(page: int = Query(default=1, ge=1),
|
||||
page_size: int = Query(default=20, ge=1, le=1000), ...):
|
||||
_require_admin(...)
|
||||
limit, offset = page_bounds(page, page_size)
|
||||
with _db() as conn:
|
||||
total = count_rows(conn, "SELECT COUNT(*) AS c FROM t")
|
||||
rows = [dict(r) for r in conn.execute(
|
||||
"SELECT ... ORDER BY id DESC LIMIT %s OFFSET %s", (limit, offset))]
|
||||
return {"items": rows, "total": total}
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
|
||||
def page_bounds(page: int, page_size: int) -> tuple[int, int]:
|
||||
"""page(1 起) 与 page_size -> (limit, offset),带防抖(page>=1,page_size 1..1000)。"""
|
||||
page = max(1, int(page))
|
||||
page_size = min(max(1, int(page_size)), 1000)
|
||||
return page_size, (page - 1) * page_size
|
||||
|
||||
|
||||
def count_rows(conn, sql: str, args=()) -> int:
|
||||
"""统一取总数:sql 为 ``SELECT COUNT(*) AS c ...``,返回 int。"""
|
||||
return int(conn.execute(sql, args).fetchone()["c"])
|
||||
Binary file not shown.
+26
@@ -9,6 +9,7 @@
|
||||
"version": "0.1.0",
|
||||
"dependencies": {
|
||||
"@element-plus/icons-vue": "^2.3.2",
|
||||
"echarts": "^6.1.0",
|
||||
"element-plus": "^2.14.5",
|
||||
"vue": "^3.5.13"
|
||||
},
|
||||
@@ -1170,6 +1171,16 @@
|
||||
"integrity": "sha512-QDTCU0M0MxR3hQfnlDJfwekQiaanm1ubOD231u73WBckQ/fsamwRLiE2GBz6D3a/xF1NgfiDLJjXBa1hYOYTtQ==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/echarts": {
|
||||
"version": "6.1.0",
|
||||
"resolved": "https://registry.npmjs.org/echarts/-/echarts-6.1.0.tgz",
|
||||
"integrity": "sha512-q0yaFPggC9FUdsWH4blavRWFmxdrIodbkoKNAjJudAI6CA9gNPxHtV2RcZNEepZVlk4yvBYkOkbk6HIVpIyHZA==",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"tslib": "2.3.0",
|
||||
"zrender": "6.1.0"
|
||||
}
|
||||
},
|
||||
"node_modules/element-plus": {
|
||||
"version": "2.14.5",
|
||||
"resolved": "https://registry.npmjs.org/element-plus/-/element-plus-2.14.5.tgz",
|
||||
@@ -1470,6 +1481,12 @@
|
||||
"url": "https://github.com/sponsors/SuperchupuDev"
|
||||
}
|
||||
},
|
||||
"node_modules/tslib": {
|
||||
"version": "2.3.0",
|
||||
"resolved": "https://registry.npmjs.org/tslib/-/tslib-2.3.0.tgz",
|
||||
"integrity": "sha512-N82ooyxVNm6h1riLCoyS9e3fuJ3AMG2zIZs2Gd1ATcSFjSA23Q0fzjjZeh0jbJvWVDZ0cJT8yaNNaaXHzueNjg==",
|
||||
"license": "0BSD"
|
||||
},
|
||||
"node_modules/vite": {
|
||||
"version": "6.4.3",
|
||||
"resolved": "https://registry.npmjs.org/vite/-/vite-6.4.3.tgz",
|
||||
@@ -1571,6 +1588,15 @@
|
||||
"resolved": "https://registry.npmjs.org/vue-component-type-helpers/-/vue-component-type-helpers-3.3.11.tgz",
|
||||
"integrity": "sha512-LwcxzeliO9fkQcpJG0PoX8X5kmAhKmH9wkpDLxNabwzkQ9Zeib2YVHwFV4pcWmMLfXVfjr/dSV+DaJ3cIPgSNA==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/zrender": {
|
||||
"version": "6.1.0",
|
||||
"resolved": "https://registry.npmjs.org/zrender/-/zrender-6.1.0.tgz",
|
||||
"integrity": "sha512-oEGMDB6pOP2S6OwRR4PdVv610zrjnA3Bh+JnSG12fYJlBKjtNAoEb5fSUoCOOINlH96I2fU38/A2UpRKs67xYQ==",
|
||||
"license": "BSD-3-Clause",
|
||||
"dependencies": {
|
||||
"tslib": "2.3.0"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,6 +10,7 @@
|
||||
},
|
||||
"dependencies": {
|
||||
"@element-plus/icons-vue": "^2.3.2",
|
||||
"echarts": "^6.1.0",
|
||||
"element-plus": "^2.14.5",
|
||||
"vue": "^3.5.13"
|
||||
},
|
||||
|
||||
@@ -43,7 +43,7 @@
|
||||
</transition>
|
||||
</main>
|
||||
</div>
|
||||
<PasswordDialog v-model="pwdOpen" />
|
||||
<PasswordDialog v-model="pwdOpen" :force="pwdForce" />
|
||||
</div>
|
||||
</template>
|
||||
|
||||
@@ -113,17 +113,24 @@ function onMenu(key) {
|
||||
const initial = computed(() => (store.nickname || store.current || '')[0]?.toUpperCase() || '?')
|
||||
|
||||
const pwdOpen = ref(false)
|
||||
const pwdForce = ref(false)
|
||||
function onCommand(cmd) {
|
||||
if (cmd === 'pwd') pwdOpen.value = true
|
||||
if (cmd === 'pwd') { pwdForce.value = false; pwdOpen.value = true }
|
||||
else if (cmd === 'logout') {
|
||||
clearSession()
|
||||
message.success('已退出登录')
|
||||
}
|
||||
}
|
||||
|
||||
function onLogin() {
|
||||
function onLogin(r) {
|
||||
route.value = '#/overview'
|
||||
location.hash = '#/overview'
|
||||
// 服务端强制:仍持初始密码(must_change_pwd=1)时拒绝一切管理操作,必须先改密
|
||||
if (r && r.must_change_pwd) {
|
||||
pwdForce.value = true
|
||||
pwdOpen.value = true
|
||||
message.warning('首次登录请先修改初始密码,修改成功后才能使用管理功能')
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(async () => {
|
||||
@@ -132,7 +139,15 @@ onMounted(async () => {
|
||||
try {
|
||||
const me = await adminMe()
|
||||
if (!me.account || !me.is_admin) clearSession()
|
||||
else { store.isAdmin = true; store.nickname = me.nickname || '' }
|
||||
else {
|
||||
store.isAdmin = true; store.nickname = me.nickname || ''
|
||||
// 刷新后仍需先改初始密码(服务端拒绝一切管理操作)
|
||||
if (me.must_change_pwd) {
|
||||
pwdForce.value = true
|
||||
pwdOpen.value = true
|
||||
message.warning('请先修改初始密码,修改成功后才能使用管理功能')
|
||||
}
|
||||
}
|
||||
} catch (_) { /* 后端 down:保持本地态 */ }
|
||||
})
|
||||
</script>
|
||||
|
||||
@@ -26,6 +26,14 @@ function adminHeaders(extra = {}) {
|
||||
return { 'X-Admin-Token': store.token || '', ...extra }
|
||||
}
|
||||
|
||||
// 统一分页规范:所有列表接口 page(page≥1) + page_size,返回 {items, total}
|
||||
function pagedQuery(params = {}) {
|
||||
const qs = new URLSearchParams()
|
||||
if (params.page) qs.set('page', params.page)
|
||||
if (params.page_size) qs.set('page_size', params.page_size)
|
||||
return qs.toString()
|
||||
}
|
||||
|
||||
export async function adminLogin(account, password) {
|
||||
return req('/api/admin/auth', {
|
||||
method: 'POST',
|
||||
@@ -46,6 +54,12 @@ export async function adminMe() {
|
||||
export async function adminOverview() {
|
||||
return req('/api/admin/overview', { headers: adminHeaders() })
|
||||
}
|
||||
export async function adminGrantData() {
|
||||
return req('/api/admin/grant_data', { headers: adminHeaders() })
|
||||
}
|
||||
export async function adminAccountGrants(account) {
|
||||
return req('/api/admin/account_grants?account=' + encodeURIComponent(account), { headers: adminHeaders() })
|
||||
}
|
||||
export async function adminPlatforms() {
|
||||
return req('/api/admin/platforms', { headers: adminHeaders() })
|
||||
}
|
||||
@@ -63,8 +77,17 @@ export async function adminPlatformGrant(body) {
|
||||
body: JSON.stringify(body)
|
||||
})
|
||||
}
|
||||
export async function adminAccounts() {
|
||||
return req('/api/admin/accounts', { headers: adminHeaders() })
|
||||
export async function adminAccounts(page = 1, pageSize = 20, q = '') {
|
||||
const qs = new URLSearchParams()
|
||||
qs.set('page', page); qs.set('page_size', pageSize)
|
||||
if (q) qs.set('q', q)
|
||||
return req('/api/admin/accounts?' + qs.toString(), { headers: adminHeaders() })
|
||||
}
|
||||
export async function adminPlugins(page = 1, pageSize = 20, q = '') {
|
||||
const qs = new URLSearchParams()
|
||||
qs.set('page', page); qs.set('page_size', pageSize)
|
||||
if (q) qs.set('q', q)
|
||||
return req('/api/admin/plugins?' + qs.toString(), { headers: adminHeaders() })
|
||||
}
|
||||
export async function adminAccountCreate(body) {
|
||||
return req('/api/admin/account', {
|
||||
@@ -115,17 +138,25 @@ export async function adminPluginPatch(pluginId, body) {
|
||||
body: JSON.stringify(body)
|
||||
})
|
||||
}
|
||||
export async function adminAudit(limit = 300) {
|
||||
return req('/api/admin/audit?limit=' + limit, { headers: adminHeaders() })
|
||||
export async function adminAudit(page = 1, pageSize = 20, filters = {}) {
|
||||
const qs = new URLSearchParams()
|
||||
qs.set('page', page); qs.set('page_size', pageSize)
|
||||
if (filters.action) qs.set('action', filters.action)
|
||||
if (filters.q) qs.set('q', filters.q)
|
||||
return req('/api/admin/audit?' + qs.toString(), { headers: adminHeaders() })
|
||||
}
|
||||
export async function adminReports(limit = 300) {
|
||||
return req('/api/admin/reports?limit=' + limit, { headers: adminHeaders() })
|
||||
export async function adminReports(page = 1, pageSize = 20, filters = {}) {
|
||||
const qs = new URLSearchParams()
|
||||
qs.set('page', page); qs.set('page_size', pageSize)
|
||||
if (filters.status) qs.set('status', filters.status)
|
||||
if (filters.q) qs.set('q', filters.q)
|
||||
return req('/api/admin/reports?' + qs.toString(), { headers: adminHeaders() })
|
||||
}
|
||||
export async function adminStats() {
|
||||
return req('/api/admin/stats', { headers: adminHeaders() })
|
||||
}
|
||||
export async function adminCredsList() {
|
||||
return req('/api/admin/creds/manage', { headers: adminHeaders() })
|
||||
export async function adminCredsList(page = 1, pageSize = 20) {
|
||||
return req('/api/admin/creds/manage?' + pagedQuery({ page, page_size: pageSize }), { headers: adminHeaders() })
|
||||
}
|
||||
export async function adminCredsSeed(body) {
|
||||
return req('/api/admin/creds/seed', {
|
||||
@@ -134,8 +165,12 @@ export async function adminCredsSeed(body) {
|
||||
body: JSON.stringify(body)
|
||||
})
|
||||
}
|
||||
export async function adminFileSources(category = '') {
|
||||
const qs = category ? '?category=' + encodeURIComponent(category) : ''
|
||||
export async function adminFileSources(category = '', page = 1, pageSize = 20) {
|
||||
const parts = []
|
||||
if (category) parts.push('category=' + encodeURIComponent(category))
|
||||
const pq = pagedQuery({ page, page_size: pageSize })
|
||||
if (pq) parts.push(pq)
|
||||
const qs = parts.length ? '?' + parts.join('&') : ''
|
||||
return req('/api/admin/file-sources' + qs, { headers: adminHeaders() })
|
||||
}
|
||||
export async function adminFileSourceCreate(body) {
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
<template>
|
||||
<div class="pager-bar" v-if="total > 0">
|
||||
<el-pagination background layout="total, sizes, prev, pager, next"
|
||||
:total="total" :current-page="page" :page-size="pageSize"
|
||||
:page-sizes="[10, 20, 50, 100]"
|
||||
@current-change="p => emit('change', p, pageSize)"
|
||||
@size-change="s => emit('change', 1, s)" />
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
// 统一分页条:配合后端 page/page_size 分页接口({items,total})。
|
||||
// 用法:<PagerBar :total="total" :page="page" :page-size="pageSize"
|
||||
// @change="(p, s) => { page = p; pageSize = s; load() }" />
|
||||
defineProps({ total: { type: Number, default: 0 }, page: { type: Number, default: 1 }, pageSize: { type: Number, default: 20 } })
|
||||
const emit = defineEmits(['change'])
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.pager-bar { display: flex; justify-content: flex-end; padding: 12px 4px 2px; }
|
||||
</style>
|
||||
@@ -1,5 +1,10 @@
|
||||
<template>
|
||||
<el-dialog v-model="visible" title="修改密码" width="440px" align-center destroy-on-close @closed="reset">
|
||||
<el-dialog v-model="visible" title="修改密码" width="440px" align-center destroy-on-close
|
||||
:close-on-click-modal="!force" :close-on-press-escape="!force" :show-close="!force"
|
||||
@closed="onClosed">
|
||||
<el-alert v-if="force" type="warning" :closable="false" class="force-tip" show-icon>
|
||||
首次登录请先修改初始密码,修改成功后才能使用管理功能。
|
||||
</el-alert>
|
||||
<el-alert v-if="store.current" type="info" :closable="false" class="acct-tip" show-icon>
|
||||
当前账号:<b class="mono">{{ store.current }}</b>
|
||||
</el-alert>
|
||||
@@ -8,7 +13,7 @@
|
||||
<el-input v-model="form.oldPwd" type="password" placeholder="请输入原密码" show-password @keyup.enter="submit" />
|
||||
</el-form-item>
|
||||
<el-form-item label="新密码" prop="newPwd">
|
||||
<el-input v-model="form.newPwd" type="password" placeholder="至少 6 位,不与原密码相同" show-password @keyup.enter="submit" />
|
||||
<el-input v-model="form.newPwd" type="password" placeholder="至少 8 位,不与原密码相同" show-password @keyup.enter="submit" />
|
||||
</el-form-item>
|
||||
<el-form-item label="确认新密码" prop="newPwd2">
|
||||
<el-input v-model="form.newPwd2" type="password" placeholder="再次输入新密码" show-password @keyup.enter="submit" />
|
||||
@@ -16,7 +21,7 @@
|
||||
</el-form>
|
||||
<template #footer>
|
||||
<div class="modal-foot">
|
||||
<el-button @click="visible = false">取消</el-button>
|
||||
<el-button v-if="!force" @click="visible = false">取消</el-button>
|
||||
<el-button type="primary" :loading="busy" @click="submit">保存</el-button>
|
||||
</div>
|
||||
</template>
|
||||
@@ -29,16 +34,19 @@ import { ElMessage as message } from 'element-plus'
|
||||
import { store } from '../store'
|
||||
import { adminPassword } from '../api'
|
||||
|
||||
// force=true 强制改密模式(首次登录 must_change_pwd):不可取消/关闭,改密成功前不允许进入管理面
|
||||
const props = defineProps({ force: { type: Boolean, default: false } })
|
||||
const visible = defineModel({ type: Boolean, default: false })
|
||||
const formRef = ref()
|
||||
const busy = ref(false)
|
||||
const changed = ref(false)
|
||||
const form = reactive({ oldPwd: '', newPwd: '', newPwd2: '' })
|
||||
|
||||
const rules = {
|
||||
oldPwd: { required: true, message: '请输入原密码' },
|
||||
newPwd: [
|
||||
{ required: true, message: '请输入新密码' },
|
||||
{ min: 6, message: '新密码至少 6 位' },
|
||||
{ min: 8, message: '新密码至少 8 位' },
|
||||
{ validator: (_r, v, cb) => (v && v === form.oldPwd ? cb(new Error('新密码不能与原密码相同')) : cb()), message: '新密码不能与原密码相同' },
|
||||
],
|
||||
newPwd2: [
|
||||
@@ -52,11 +60,17 @@ function reset() {
|
||||
formRef.value?.resetFields()
|
||||
}
|
||||
|
||||
function onClosed() {
|
||||
// 强制模式下未改密成功不允许关闭:自动重新打开
|
||||
if (props.force && !changed.value) visible.value = true
|
||||
}
|
||||
|
||||
async function submit() {
|
||||
try { await formRef.value.validate() } catch (_) { return }
|
||||
busy.value = true
|
||||
try {
|
||||
await adminPassword({ account: store.current, old_password: form.oldPwd, new_password: form.newPwd })
|
||||
changed.value = true
|
||||
message.success('密码已修改,下次登录请使用新密码')
|
||||
visible.value = false
|
||||
} catch (e) {
|
||||
@@ -68,6 +82,7 @@ async function submit() {
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.force-tip { margin-bottom: 14px; }
|
||||
.acct-tip { margin-bottom: 16px; }
|
||||
.modal-foot { display: flex; justify-content: flex-end; gap: 10px; }
|
||||
</style>
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
// 统一分页列表 composable:对接后端 page/page_size → {items,total} 契约。
|
||||
//
|
||||
// 统一管理:items/total/page/pageSize/busy 状态 + load/onPageChange/reset 行为;
|
||||
// 自动处理越界回退(删除/筛选后当前页为空时回到最后一页);
|
||||
// 请求竞态控制(快速翻页/切筛选时丢弃过期响应);
|
||||
// 错误统一走 onError 回调(不向上抛),各页面不再各自 try/catch。
|
||||
//
|
||||
// 用法:
|
||||
// const { items: accounts, total, page, size: pageSize, busy, load: refresh, onPageChange, reset } =
|
||||
// usePagedList((p, s) => adminAccounts(p, s), {
|
||||
// onError: e => message.error('读取失败:' + (e.message || e)),
|
||||
// })
|
||||
// 模板中直接使用解构出的 ref(自动解包),PagerBar 绑定 :total :page :page-size @change="onPageChange"。
|
||||
import { ref } from 'vue'
|
||||
|
||||
export function usePagedList(fetcher, opts = {}) {
|
||||
const onError = typeof opts.onError === 'function' ? opts.onError : () => {}
|
||||
const items = ref([])
|
||||
const total = ref(0)
|
||||
const page = ref(1)
|
||||
const size = ref(opts.pageSize || 20)
|
||||
const busy = ref(false)
|
||||
// 响应里除 items/total 外的附加字段(如 today/failed)透传到 meta
|
||||
const meta = ref({})
|
||||
// 请求序号:只接受最后一次发起的响应,丢弃过期响应
|
||||
let seq = 0
|
||||
|
||||
async function load() {
|
||||
const my = ++seq
|
||||
busy.value = true
|
||||
try {
|
||||
const r = await fetcher(page.value, size.value)
|
||||
if (my !== seq) return // 已过期(期间又发起了新请求)
|
||||
items.value = r.items || []
|
||||
total.value = r.total || 0
|
||||
meta.value = r
|
||||
// 越界回退:数据被删/筛选变化导致当前页为空,且总数>0 → 回到最后一页
|
||||
if (!items.value.length && page.value > 1 && total.value > 0) {
|
||||
const last = Math.max(1, Math.ceil(total.value / size.value))
|
||||
if (last !== page.value) {
|
||||
page.value = last
|
||||
return load()
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
if (my === seq) onError(e)
|
||||
} finally {
|
||||
if (my === seq) busy.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function onPageChange(p, s) {
|
||||
if (p === page.value && s === size.value) return
|
||||
page.value = p
|
||||
size.value = s
|
||||
load()
|
||||
}
|
||||
|
||||
// 筛选条件/外部数据变化后回到第一页重新加载
|
||||
function reset() {
|
||||
page.value = 1
|
||||
load()
|
||||
}
|
||||
|
||||
return { items, total, page, size, busy, meta, load, onPageChange, reset }
|
||||
}
|
||||
@@ -6,11 +6,17 @@
|
||||
<p>建号 · 部门 / 管理员维护 · 密码重置(不能操作自己的账号)</p>
|
||||
</div>
|
||||
<div class="head-acts">
|
||||
<el-button :loading="overviewBusy" :icon="Refresh" @click="refresh">刷新</el-button>
|
||||
<el-button :loading="busy" :icon="Refresh" @click="refresh">刷新</el-button>
|
||||
<el-button type="primary" :icon="Plus" @click="openCreate">新建账号</el-button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 账号搜索(服务端模糊:账号/昵称/部门) -->
|
||||
<div class="search-bar cp-card cp-rise">
|
||||
<el-input v-model="kw" placeholder="搜索账号 / 昵称 / 部门" clearable :prefix-icon="Search" style="width: 300px" @keyup.enter="onSearch" @clear="onSearch" />
|
||||
<span v-if="kw" class="dim-sm">搜索中:{{ kw }}</span>
|
||||
</div>
|
||||
|
||||
<!-- 账号卡片 -->
|
||||
<div class="acct-grid" v-if="accounts.length">
|
||||
<div class="acct-card cp-card cp-rise" v-for="(a, i) in accounts" :key="a.account" :style="{ animationDelay: i * 40 + 'ms' }">
|
||||
@@ -46,8 +52,8 @@
|
||||
|
||||
<div class="acct-tags" v-if="a.plugins?.length">
|
||||
<span class="tag-label">插件</span>
|
||||
<el-tag v-for="p in a.plugins.slice(0, 3)" :key="p" size="small" type="primary" effect="light" round class="mono">{{ p }}</el-tag>
|
||||
<span v-if="a.plugins.length > 3" class="more mono">+{{ a.plugins.length - 3 }}</span>
|
||||
<el-tag v-for="p in a.plugins.slice(0, 2)" :key="p" size="small" type="primary" effect="light" round class="mono">{{ p }}</el-tag>
|
||||
<span v-if="a.plugins.length > 2" class="more mono">+{{ a.plugins.length - 2 }}</span>
|
||||
</div>
|
||||
<div class="acct-tags" v-else>
|
||||
<span class="tag-label">插件</span>
|
||||
@@ -65,7 +71,8 @@
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<el-empty v-else-if="!overviewBusy" description="暂无账号,点击右上角「新建账号」" :image-size="90" class="cp-card" />
|
||||
<el-empty v-else-if="!busy" description="暂无账号,点击右上角「新建账号」" :image-size="90" class="cp-card" />
|
||||
<PagerBar v-if="total > 0" :total="total" :page="page" :page-size="pageSize" @change="onPageChange" />
|
||||
|
||||
<!-- 新建账号 -->
|
||||
<el-dialog v-model="createOpen" title="新建账号" width="440px" align-center destroy-on-close @closed="resetCreate">
|
||||
@@ -77,7 +84,7 @@
|
||||
<el-input v-model="form.nickname" placeholder="真实姓名,方便识别(可填钉钉名)" />
|
||||
</el-form-item>
|
||||
<el-form-item label="初始密码" prop="password">
|
||||
<el-input v-model="form.password" type="password" placeholder="至少 6 位" show-password />
|
||||
<el-input v-model="form.password" type="password" placeholder="至少 8 位" show-password />
|
||||
</el-form-item>
|
||||
<el-form-item label="部门">
|
||||
<el-input v-model="form.dept" placeholder="如 财务部 / IT" />
|
||||
@@ -121,9 +128,9 @@
|
||||
<!-- 重置密码 -->
|
||||
<el-dialog v-model="resetOpen" title="重置密码" width="420px" align-center destroy-on-close>
|
||||
<el-alert type="info" :closable="false" class="reset-tip" show-icon>
|
||||
为账号 <b class="mono">{{ resetTarget }}</b> 设置新密码(至少 6 位)
|
||||
为账号 <b class="mono">{{ resetTarget }}</b> 设置新密码(至少 8 位)
|
||||
</el-alert>
|
||||
<el-input v-model="resetPwdVal" type="password" placeholder="新密码(至少 6 位)" show-password @keyup.enter="confirmReset" />
|
||||
<el-input v-model="resetPwdVal" type="password" placeholder="新密码(至少 8 位)" show-password @keyup.enter="confirmReset" />
|
||||
<template #footer>
|
||||
<div class="modal-foot">
|
||||
<el-button @click="resetOpen = false">取消</el-button>
|
||||
@@ -137,18 +144,19 @@
|
||||
<script setup>
|
||||
import { computed, onMounted, reactive, ref } from 'vue'
|
||||
import { ElMessage as message, ElMessageBox as dialog } from 'element-plus'
|
||||
import { Refresh, Plus, Camera, EditPen, Edit, Delete } from '@element-plus/icons-vue'
|
||||
import { store, overview, overviewBusy, loadOverview } from '../store'
|
||||
import { adminAccountCreate, adminAccountUpdate, adminAccountReset, adminAccountDelete, adminAvatarUpload } from '../api'
|
||||
import { Refresh, Plus, Camera, EditPen, Edit, Delete, Search } from '@element-plus/icons-vue'
|
||||
import { store } from '../store'
|
||||
import { adminAccounts, adminAccountCreate, adminAccountUpdate, adminAccountReset, adminAccountDelete, adminAvatarUpload } from '../api'
|
||||
import { fmtTime } from '../format'
|
||||
import PagerBar from '../components/PagerBar.vue'
|
||||
import { usePagedList } from '../composables/usePagedList'
|
||||
|
||||
const current = computed(() => store.current || '')
|
||||
const accounts = computed(() => overview.value?.accounts || [])
|
||||
const kw = ref('')
|
||||
const list = usePagedList((p, s) => adminAccounts(p, s, kw.value), { onError: e => message.error('读取失败:' + (e.message || e)) })
|
||||
const { items: accounts, total, page, size: pageSize, busy, load: refresh, onPageChange, reset } = list
|
||||
const busySwitch = ref('')
|
||||
|
||||
async function refresh() {
|
||||
try { await loadOverview(true) } catch (e) { message.error('读取失败:' + (e.message || e)) }
|
||||
}
|
||||
function onSearch() { reset() }
|
||||
|
||||
// ---------- 头像(显示 + 上传) ----------
|
||||
const _fileInput = (() => {
|
||||
@@ -188,7 +196,7 @@ const rules = {
|
||||
account: { required: true, message: '请输入账号' },
|
||||
password: [
|
||||
{ required: true, message: '请输入初始密码' },
|
||||
{ min: 6, message: '密码至少 6 位' },
|
||||
{ min: 8, message: '密码至少 8 位' },
|
||||
],
|
||||
}
|
||||
function openCreate() { createOpen.value = true }
|
||||
@@ -244,7 +252,7 @@ function resetPwd(a) {
|
||||
}
|
||||
async function confirmReset() {
|
||||
const p = resetPwdVal.value
|
||||
if (p.length < 6) { message.warning('密码至少 6 位'); return }
|
||||
if (p.length < 8) { message.warning('密码至少 8 位'); return }
|
||||
resetting.value = true
|
||||
try {
|
||||
await adminAccountReset({ account: resetTarget.value, new_password: p })
|
||||
@@ -271,6 +279,7 @@ onMounted(refresh)
|
||||
<style scoped>
|
||||
.head-acts { display: flex; gap: 10px; }
|
||||
|
||||
.search-bar { display: flex; align-items: center; gap: 12px; padding: 14px 18px; margin-bottom: 16px; }
|
||||
.acct-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fill, minmax(330px, 1fr));
|
||||
|
||||
@@ -23,12 +23,12 @@
|
||||
<el-tabs v-model="tab">
|
||||
<el-tab-pane label="操作审计" name="audit">
|
||||
<div class="toolbar">
|
||||
<el-select v-model="actionFilter" clearable placeholder="操作类型" style="width: 150px">
|
||||
<el-select v-model="actionFilter" clearable placeholder="操作类型" style="width: 150px" @change="onAuditFilter">
|
||||
<el-option v-for="(lb, key) in DETAIL_LABEL" :key="key" :label="lb" :value="key" />
|
||||
</el-select>
|
||||
<el-input v-model="search" placeholder="搜索账号 / 对象 / 详情" clearable :prefix-icon="Search" style="width: 240px" />
|
||||
<el-input v-model="search" placeholder="搜索账号 / 对象 / 详情" clearable :prefix-icon="Search" style="width: 240px" @keyup.enter="onAuditFilter" @clear="onAuditFilter" />
|
||||
</div>
|
||||
<el-table :data="filteredAudits" size="small" :row-key="r => r.id">
|
||||
<el-table :data="audits" size="small" v-loading="auditBusy" :row-key="r => r.id">
|
||||
<el-table-column label="时间" width="170">
|
||||
<template #default="{ row }"><span class="mono dim-sm">{{ fmtTime(row.at) }}</span></template>
|
||||
</el-table-column>
|
||||
@@ -55,16 +55,26 @@
|
||||
</template>
|
||||
</el-table-column>
|
||||
</el-table>
|
||||
<PagerBar :total="auditTotal" :page="auditPage" :page-size="auditPageSize" @change="onAuditPage" />
|
||||
</el-tab-pane>
|
||||
|
||||
<el-tab-pane label="运行上报" name="report">
|
||||
<el-table :data="reports" size="small" :row-key="r => r.id">
|
||||
<div class="toolbar">
|
||||
<el-select v-model="statusFilter" clearable placeholder="状态" style="width: 130px" @change="onReportFilter">
|
||||
<el-option label="成功" value="done,success" />
|
||||
<el-option label="失败" value="error,failed" />
|
||||
<el-option label="运行中" value="running" />
|
||||
<el-option label="已触发" value="start" />
|
||||
</el-select>
|
||||
<el-input v-model="reportSearch" placeholder="搜索账号 / 设备 / 插件 / 消息" clearable :prefix-icon="Search" style="width: 260px" @keyup.enter="onReportFilter" @clear="onReportFilter" />
|
||||
</div>
|
||||
<el-table :data="reports" size="small" v-loading="reportBusy" :row-key="r => r.id">
|
||||
<el-table-column label="时间" width="170">
|
||||
<template #default="{ row }"><span class="mono dim-sm">{{ fmtTime(row.at) }}</span></template>
|
||||
</el-table-column>
|
||||
<el-table-column label="状态" width="110">
|
||||
<template #default="{ row }">
|
||||
<span class="status-dot"><i :style="{ background: statusColor(row.status) }"></i><span :style="{ color: statusColor(row.status) }">{{ row.status || '—' }}</span></span>
|
||||
<span class="status-dot"><i :style="{ background: statusColor(row.status) }"></i><span :style="{ color: statusColor(row.status) }">{{ statusLabel(row.status) }}</span></span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="账号" width="140">
|
||||
@@ -80,13 +90,13 @@
|
||||
<template #default="{ row }"><span class="mono dim-sm">{{ row.device_id || '—' }}</span></template>
|
||||
</el-table-column>
|
||||
<el-table-column label="插件" width="150" show-overflow-tooltip>
|
||||
<template #default="{ row }"><span class="mono">{{ row.plugin_id || '—' }}</span></template>
|
||||
<template #default="{ row }"><span class="mono">{{ row.pluginId || '—' }}</span></template>
|
||||
</el-table-column>
|
||||
<el-table-column label="版本" width="90">
|
||||
<template #default="{ row }"><span class="mono">{{ row.version || '—' }}</span></template>
|
||||
</el-table-column>
|
||||
<el-table-column label="时长" width="90">
|
||||
<template #default="{ row }"><span class="mono">{{ typeof row.duration_sec === 'number' ? fmtDur(row.duration_sec) : '—' }}</span></template>
|
||||
<template #default="{ row }"><span class="mono">{{ typeof row.durationSec === 'number' ? fmtDur(row.durationSec) : '—' }}</span></template>
|
||||
</el-table-column>
|
||||
<el-table-column label="消息" min-width="200" show-overflow-tooltip>
|
||||
<template #default="{ row }">
|
||||
@@ -94,6 +104,7 @@
|
||||
</template>
|
||||
</el-table-column>
|
||||
</el-table>
|
||||
<PagerBar :total="reportTotal" :page="reportPage" :page-size="reportPageSize" @change="onReportPage" />
|
||||
</el-tab-pane>
|
||||
</el-tabs>
|
||||
</div>
|
||||
@@ -102,20 +113,36 @@
|
||||
|
||||
<script setup>
|
||||
import { computed, onMounted, ref } from 'vue'
|
||||
import { Refresh, Search, Document, DataLine, CircleCloseFilled, WarningFilled } from '@element-plus/icons-vue'
|
||||
import { Refresh, Search, Document, DataLine, CircleCloseFilled } from '@element-plus/icons-vue'
|
||||
import { ElMessage as message } from 'element-plus'
|
||||
import { adminAudit, adminReports } from '../api'
|
||||
import { fmtTime } from '../format'
|
||||
import PagerBar from '../components/PagerBar.vue'
|
||||
import { usePagedList } from '../composables/usePagedList'
|
||||
|
||||
const tab = ref('audit')
|
||||
const busy = ref(false)
|
||||
const loaded = ref(false)
|
||||
const audits = ref([])
|
||||
const reports = ref([])
|
||||
|
||||
// 两个分页列表(服务端筛选:筛选/搜索条件作为闭包实时传给 fetcher)
|
||||
const actionFilter = ref('')
|
||||
const search = ref('')
|
||||
const statusFilter = ref('')
|
||||
const reportSearch = ref('')
|
||||
|
||||
const auditsList = usePagedList((p, s) => adminAudit(p, s, { action: actionFilter.value, q: search.value }), { onError: e => message.error('读取审计失败:' + (e.message || e)) })
|
||||
const reportsList = usePagedList((p, s) => adminReports(p, s, { status: statusFilter.value, q: reportSearch.value }), { onError: e => message.error('读取上报失败:' + (e.message || e)) })
|
||||
const { items: audits, total: auditTotal, page: auditPage, size: auditPageSize, busy: auditBusy, meta: auditMeta } = auditsList
|
||||
const { items: reports, total: reportTotal, page: reportPage, size: reportPageSize, busy: reportBusy, meta: reportMeta } = reportsList
|
||||
|
||||
const DETAIL_LABEL = {
|
||||
// 新命名(2026-09 服务端重构后)
|
||||
'account-reset-pwd': '重置密码', 'grant-platform': '平台授权', 'revoke-platform': '撤销平台授权',
|
||||
'plugin-publish': '上传发布', 'plugin-delete': '删除插件',
|
||||
'creds-seed': '更新凭证',
|
||||
'file-source-upsert': '登记文件源', 'file-source-patch': '更新文件源', 'file-source-delete': '删除文件源',
|
||||
'shell-release': '发布壳子',
|
||||
// 历史命名(旧版本审计记录兼容)
|
||||
grant: '授权', 'revoke-grant': '撤销授权', 'plugin-patch': '更新插件',
|
||||
'download-ticket': '下载', 'upload-pkg': '上传', 'account-create': '建号',
|
||||
'account-update': '改号', 'account-reset': '重置密码', 'account-delete': '删除',
|
||||
@@ -123,11 +150,18 @@ const DETAIL_LABEL = {
|
||||
}
|
||||
function actType(a) {
|
||||
return { grant: 'primary', 'revoke-grant': 'danger', 'plugin-patch': 'warning',
|
||||
'download-ticket': 'success', 'upload-pkg': 'success', login: 'primary' }[a] || 'info'
|
||||
'download-ticket': 'success', 'upload-pkg': 'success', login: 'primary',
|
||||
'plugin-publish': 'success', 'plugin-delete': 'danger',
|
||||
'grant-platform': 'primary', 'revoke-platform': 'danger',
|
||||
'account-reset-pwd': 'warning', 'creds-seed': 'warning',
|
||||
'shell-release': 'success' }[a] || 'info'
|
||||
}
|
||||
function statusColor(s) {
|
||||
return { start: '#2f5cf0', running: '#2f5cf0', done: '#1d9d5c', success: '#1d9d5c', error: '#d6453d', failed: '#d6453d' }[s] || '#9aa2b4'
|
||||
}
|
||||
function statusLabel(s) {
|
||||
return ({ done: '成功', success: '成功', error: '失败', failed: '失败', running: '运行中', start: '已触发' })[s] || s
|
||||
}
|
||||
function fmtDur(sec) {
|
||||
sec = +sec || 0
|
||||
if (sec < 60) return sec + 's'
|
||||
@@ -136,36 +170,27 @@ function fmtDur(sec) {
|
||||
return `${Math.floor(m / 60)}h${m % 60}m`
|
||||
}
|
||||
|
||||
const kpis = computed(() => {
|
||||
const today = new Date().toISOString().slice(0, 10)
|
||||
const tActs = audits.value.filter(a => (a.at || '').slice(0, 10) === today).length
|
||||
const tReports = reports.value.filter(r => (r.at || '').slice(0, 10) === today).length
|
||||
const fails = reports.value.filter(r => r.status === 'error' || r.status === 'failed').length
|
||||
return [
|
||||
{ label: '审计记录', value: audits.value.length, icon: Document, color: '#2f5cf0', bg: 'linear-gradient(135deg,#e8edfe,#d7e1fd)' },
|
||||
{ label: '今日操作', value: tActs, icon: DataLine, color: '#0f9f9b', bg: 'linear-gradient(135deg,#e4f6f5,#d2efee)' },
|
||||
{ label: '运行上报', value: reports.value.length, icon: DataLine, color: '#7c5cf6', bg: 'linear-gradient(135deg,#f0ebfe,#e4dcfd)' },
|
||||
{ label: '今日上报', value: tReports, icon: DataLine, color: '#d97706', bg: 'linear-gradient(135deg,#fbf0df,#f6e4c8)' },
|
||||
{ label: '上报失败', value: fails, icon: CircleCloseFilled, color: '#d6453d', bg: 'linear-gradient(135deg,#fbe9e8,#f6d8d6)' },
|
||||
]
|
||||
})
|
||||
// KPI 全用后端统计值(total/today/failed),不依赖当前页 slice,保证分页后口径不变
|
||||
const kpis = computed(() => [
|
||||
{ label: '审计记录', value: auditTotal.value, icon: Document, color: '#2f5cf0', bg: 'linear-gradient(135deg,#e8edfe,#d7e1fd)' },
|
||||
{ label: '今日操作', value: auditMeta.value.today || 0, icon: DataLine, color: '#0f9f9b', bg: 'linear-gradient(135deg,#e4f6f5,#d2efee)' },
|
||||
{ label: '运行上报', value: reportTotal.value, icon: DataLine, color: '#7c5cf6', bg: 'linear-gradient(135deg,#f0ebfe,#e4dcfd)' },
|
||||
{ label: '今日上报', value: reportMeta.value.today || 0, icon: DataLine, color: '#d97706', bg: 'linear-gradient(135deg,#fbf0df,#f6e4c8)' },
|
||||
{ label: '上报失败', value: reportMeta.value.failed || 0, icon: CircleCloseFilled, color: '#d6453d', bg: 'linear-gradient(135deg,#fbe9e8,#f6d8d6)' },
|
||||
])
|
||||
|
||||
const filteredAudits = computed(() => {
|
||||
let list = audits.value
|
||||
if (actionFilter.value) list = list.filter(a => a.action === actionFilter.value)
|
||||
const kw = search.value.trim().toLowerCase()
|
||||
if (kw) list = list.filter(a => [a.account, a.nickname, a.target, a.detail].join(' ').toLowerCase().includes(kw))
|
||||
return list
|
||||
})
|
||||
// 筛选变化 → 回到第一页(服务端重新查询)
|
||||
function onAuditFilter() { auditsList.reset() }
|
||||
function onReportFilter() { reportsList.reset() }
|
||||
function onAuditPage(p, s) { auditsList.onPageChange(p, s) }
|
||||
function onReportPage(p, s) { reportsList.onPageChange(p, s) }
|
||||
|
||||
async function refresh() {
|
||||
busy.value = true
|
||||
try {
|
||||
const [a, r] = await Promise.all([adminAudit(), adminReports()])
|
||||
audits.value = a.auditlogs || []
|
||||
reports.value = r.reports || []
|
||||
await Promise.all([auditsList.load(), reportsList.load()])
|
||||
loaded.value = true
|
||||
} catch (e) { message.error('读取失败:' + (e.message || e)) }
|
||||
} catch (_) { /* 子加载器已提示 */ }
|
||||
finally { busy.value = false }
|
||||
}
|
||||
onMounted(refresh)
|
||||
|
||||
@@ -10,9 +10,9 @@
|
||||
|
||||
<div class="cp-card panel cp-rise">
|
||||
<el-table :data="rows" v-loading="busy" size="default" style="width: 100%">
|
||||
<el-table-column prop="account" label="执行机账号" width="150">
|
||||
<el-table-column prop="account" label="执行机账号" width="180">
|
||||
<template #default="{ row }">
|
||||
<span class="mono">{{ row.account }}</span>
|
||||
<span class="mono">{{ row.nickname ? `${row.nickname} · ${row.account}` : row.account }}</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="公钥" width="90">
|
||||
@@ -37,6 +37,7 @@
|
||||
<el-empty description="暂无账号,客户端启动注册后自动出现" :image-size="80" />
|
||||
</template>
|
||||
</el-table>
|
||||
<PagerBar :total="total" :page="page" :page-size="pageSize" @change="onPageChange" />
|
||||
</div>
|
||||
|
||||
<el-dialog v-model="dlg" :title="`编辑凭证 · ${editing?.account || ''}`" width="540px">
|
||||
@@ -61,6 +62,8 @@ import { onMounted, ref } from 'vue'
|
||||
import { Refresh, EditPen } from '@element-plus/icons-vue'
|
||||
import { ElMessage as message } from 'element-plus'
|
||||
import { adminCredsList, adminCredsSeed } from '../api'
|
||||
import PagerBar from '../components/PagerBar.vue'
|
||||
import { usePagedList } from '../composables/usePagedList'
|
||||
|
||||
const KEY_COLS = [
|
||||
{ key: 'DINGTALK_APPKEY', label: 'AppKey' },
|
||||
@@ -70,22 +73,13 @@ const KEY_COLS = [
|
||||
]
|
||||
|
||||
const keyCols = KEY_COLS
|
||||
const busy = ref(false)
|
||||
const rows = ref([])
|
||||
const list = usePagedList((p, s) => adminCredsList(p, s), { onError: e => message.error('读取失败:' + (e.message || e)) })
|
||||
const { items: rows, total, page, size: pageSize, busy, load: refresh, onPageChange } = list
|
||||
const dlg = ref(false)
|
||||
const saving = ref(false)
|
||||
const editing = ref(null)
|
||||
const form = ref({})
|
||||
|
||||
async function refresh() {
|
||||
busy.value = true
|
||||
try {
|
||||
const r = await adminCredsList()
|
||||
rows.value = r.accounts || []
|
||||
} catch (e) { message.error('读取失败:' + (e.message || e)) }
|
||||
finally { busy.value = false }
|
||||
}
|
||||
|
||||
function openEdit(row) {
|
||||
editing.value = row
|
||||
form.value = {}
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
<p>内网大文件(壳子/Chrome 等)直链登记。中心机只存链接,文件本身走内网文件服务器</p>
|
||||
</div>
|
||||
<div class="head-actions">
|
||||
<el-select v-model="filter" placeholder="按分类过滤" style="width: 150px" clearable @change="refresh">
|
||||
<el-select v-model="filter" placeholder="按分类过滤" style="width: 150px" clearable @change="onFilterChange">
|
||||
<el-option v-for="c in categories" :key="c" :label="c" :value="c" />
|
||||
</el-select>
|
||||
<el-button :loading="busy" :icon="Refresh" @click="refresh">刷新</el-button>
|
||||
@@ -57,6 +57,7 @@
|
||||
<el-empty description="暂无登记的大文件源" :image-size="80" />
|
||||
</template>
|
||||
</el-table>
|
||||
<PagerBar :total="total" :page="page" :page-size="pageSize" @change="onPageChange" />
|
||||
</div>
|
||||
|
||||
<el-dialog v-model="dlg" title="登记内网直链" width="560px">
|
||||
@@ -96,32 +97,30 @@
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { onMounted, ref } from 'vue'
|
||||
import { onMounted, ref, watch } from 'vue'
|
||||
import { Refresh, Plus, Delete } from '@element-plus/icons-vue'
|
||||
import { ElMessage as message, ElMessageBox } from 'element-plus'
|
||||
import { adminFileSources, adminFileSourceCreate, adminFileSourcePatch, adminFileSourceDelete } from '../api'
|
||||
import PagerBar from '../components/PagerBar.vue'
|
||||
import { usePagedList } from '../composables/usePagedList'
|
||||
|
||||
const CATS = ['shell', 'chrome']
|
||||
const categories = CATS
|
||||
const busy = ref(false)
|
||||
const rows = ref([])
|
||||
const filter = ref('')
|
||||
const list = usePagedList((p, s) => adminFileSources(filter.value || '', p, s), { onError: e => message.error('读取失败:' + (e.message || e)) })
|
||||
const { items: rows, total, page, size: pageSize, busy, load: refresh, onPageChange, reset } = list
|
||||
const dlg = ref(false)
|
||||
const saving = ref(false)
|
||||
const form = ref({})
|
||||
|
||||
async function refresh() {
|
||||
busy.value = true
|
||||
try {
|
||||
const r = await adminFileSources(filter.value || '')
|
||||
rows.value = r.files || []
|
||||
const seen = new Set(CATS)
|
||||
;(r.files || []).forEach((f) => seen.add(f.category))
|
||||
categories.length = 0
|
||||
;[...seen].sort().forEach((c) => categories.push(c))
|
||||
} catch (e) { message.error('读取失败:' + (e.message || e)) }
|
||||
finally { busy.value = false }
|
||||
}
|
||||
function onFilterChange() { reset() }
|
||||
// 分类下拉:由当前页数据补充实际出现的分类
|
||||
watch(rows, () => {
|
||||
const seen = new Set(CATS)
|
||||
;(rows.value || []).forEach((f) => seen.add(f.category))
|
||||
categories.length = 0
|
||||
;[...seen].sort().forEach((c) => categories.push(c))
|
||||
})
|
||||
|
||||
function catType(c) {
|
||||
return { shell: 'success', chrome: 'warning' }[c] || 'info'
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
<h3>权限授权 <span class="badge">Grants</span></h3>
|
||||
<p>按账号勾选可用插件与可登录平台,保存时仅提交差异项</p>
|
||||
</div>
|
||||
<el-button :loading="overviewBusy" :icon="Refresh" @click="refresh">刷新</el-button>
|
||||
<el-button :loading="grantDataBusy" :icon="Refresh" @click="refresh">刷新</el-button>
|
||||
</div>
|
||||
|
||||
<div class="cp-card panel cp-rise">
|
||||
@@ -25,10 +25,13 @@
|
||||
<div class="section">
|
||||
<div class="section-head">
|
||||
<div class="card-title">插件授权</div>
|
||||
<el-checkbox :model-value="allChecked" :indeterminate="someChecked" @change="toggleAll">全选</el-checkbox>
|
||||
<div class="gh-sec-right">
|
||||
<el-input v-model="pluginKw" placeholder="搜索插件 ID / 名称" clearable :prefix-icon="Search" size="small" style="width: 210px" />
|
||||
<el-checkbox :model-value="allChecked" :indeterminate="someChecked" @change="toggleAll">全选</el-checkbox>
|
||||
</div>
|
||||
</div>
|
||||
<el-checkbox-group v-model="grantedIds" class="plist">
|
||||
<div class="prow" v-for="p in plugins" :key="p.id" :class="{ on: grantedIds.includes(p.id) }">
|
||||
<el-checkbox-group v-model="grantedIds" class="plist" v-loading="grantsBusy">
|
||||
<div class="prow" v-for="p in visiblePlugins" :key="p.id" :class="{ on: grantedIds.includes(p.id) }">
|
||||
<el-checkbox :value="p.id" class="pck">
|
||||
<span class="pname mono">{{ p.id }}</span>
|
||||
<span class="psub dim">{{ p.name }}</span>
|
||||
@@ -45,7 +48,7 @@
|
||||
</div>
|
||||
</div>
|
||||
</el-checkbox-group>
|
||||
<el-empty v-if="!plugins.length" description="暂无插件,请先在「插件管理」上传" :image-size="60" />
|
||||
<el-empty v-if="!visiblePlugins.length" description="暂无插件,请先在「插件管理」上传" :image-size="60" />
|
||||
</div>
|
||||
|
||||
<!-- 平台授权 -->
|
||||
@@ -82,19 +85,28 @@
|
||||
|
||||
<script setup>
|
||||
import { computed, onMounted, ref, watch } from 'vue'
|
||||
import { Refresh, User, Check } from '@element-plus/icons-vue'
|
||||
import { Refresh, Search, User, Check } from '@element-plus/icons-vue'
|
||||
import { ElMessage as message } from 'element-plus'
|
||||
import { overview, overviewBusy, loadOverview } from '../store'
|
||||
import { adminGrant, adminPlatformGrant, adminPlatforms } from '../api'
|
||||
import { adminGrant, adminPlatformGrant, adminPlatforms, adminGrantData, adminAccountGrants } from '../api'
|
||||
|
||||
const PLATFORM_OPTS = ref([])
|
||||
const grantDataBusy = ref(false)
|
||||
const grantsBusy = ref(false)
|
||||
|
||||
const plugins = computed(() => overview.value?.plugins || [])
|
||||
const accounts = computed(() => overview.value?.accounts || [])
|
||||
// 轻量数据源(/grant_data 一次查询,不依赖 overview 全量聚合)
|
||||
const plugins = ref([]) // {id,name,status}
|
||||
const accounts = ref([]) // {account,nickname,dept,status}
|
||||
const accountOptions = computed(() => accounts.value.map(a => ({
|
||||
label: a.dept ? `${a.account} · ${a.dept}` : a.account,
|
||||
label: [a.nickname, a.account, a.dept].filter(Boolean).join(' · '),
|
||||
value: a.account,
|
||||
})))
|
||||
// 插件搜索(数据为全量,前端过滤安全)
|
||||
const pluginKw = ref('')
|
||||
const visiblePlugins = computed(() => {
|
||||
const kw = pluginKw.value.trim().toLowerCase()
|
||||
if (!kw) return plugins.value
|
||||
return plugins.value.filter(p => [p.id, p.name].join(' ').toLowerCase().includes(kw))
|
||||
})
|
||||
|
||||
const account = ref('')
|
||||
const grantedIds = ref([])
|
||||
@@ -111,26 +123,38 @@ function setGrant(pid, patch) {
|
||||
function canRun(pid) { return grantState.value[pid]?.canRun !== false }
|
||||
function canDownload(pid) { return grantState.value[pid]?.canDownload !== false }
|
||||
|
||||
// 全选 / 半选
|
||||
const allChecked = computed(() => plugins.value.length > 0 && grantedIds.value.length === plugins.value.length)
|
||||
const someChecked = computed(() => grantedIds.value.length > 0 && !allChecked.value)
|
||||
// 全选 / 半选(基于当前可见插件:搜索后全选 = 全选搜索结果)
|
||||
const allChecked = computed(() => visiblePlugins.value.length > 0 &&
|
||||
visiblePlugins.value.every(p => grantedIds.value.includes(p.id)))
|
||||
const someChecked = computed(() => visiblePlugins.value.some(p => grantedIds.value.includes(p.id)) && !allChecked.value)
|
||||
function toggleAll(v) {
|
||||
grantedIds.value = v ? plugins.value.map(p => p.id) : []
|
||||
const visible = visiblePlugins.value.map(p => p.id)
|
||||
grantedIds.value = v
|
||||
? [...new Set([...grantedIds.value, ...visible])]
|
||||
: grantedIds.value.filter(id => !visible.includes(id))
|
||||
}
|
||||
|
||||
// 选中账号即自动载入其现有授权
|
||||
watch(account, (acc) => {
|
||||
const a = accounts.value.find(x => x.account === acc)
|
||||
const state = {}
|
||||
;(a?.plugins || []).forEach(pid => {
|
||||
const g = a?.grants?.[pid] || {}
|
||||
state[pid] = { granted: true, canRun: g.canRun !== false, canDownload: g.canDownload !== false }
|
||||
})
|
||||
heldGrantState = JSON.parse(JSON.stringify(state))
|
||||
grantState.value = JSON.parse(JSON.stringify(state))
|
||||
grantedIds.value = [...(a?.plugins || [])]
|
||||
heldPlatforms = new Set(a?.platforms || [])
|
||||
platChecked.value = [...heldPlatforms]
|
||||
// 选中账号即拉取其现有授权(按账号 2 次查询,无 N+1)
|
||||
watch(account, async (acc) => {
|
||||
if (!acc) {
|
||||
grantState.value = {}; grantedIds.value = []; platChecked.value = []
|
||||
heldGrantState = {}; heldPlatforms = new Set()
|
||||
return
|
||||
}
|
||||
grantsBusy.value = true
|
||||
try {
|
||||
const r = await adminAccountGrants(acc)
|
||||
const state = {}
|
||||
;(r.plugins || []).forEach(g => {
|
||||
state[g.plugin_id] = { granted: true, canRun: g.canRun !== false, canDownload: g.canDownload !== false }
|
||||
})
|
||||
heldGrantState = JSON.parse(JSON.stringify(state))
|
||||
grantState.value = JSON.parse(JSON.stringify(state))
|
||||
grantedIds.value = [...(r.plugins || []).map(g => g.plugin_id)]
|
||||
heldPlatforms = new Set(r.platforms || [])
|
||||
platChecked.value = [...heldPlatforms]
|
||||
} catch (e) { message.error('读取授权失败:' + (e.message || e)) }
|
||||
finally { grantsBusy.value = false }
|
||||
})
|
||||
|
||||
// 勾选/取消勾选插件时同步 granted 状态
|
||||
@@ -165,13 +189,14 @@ const platDirty = computed(() => {
|
||||
const dirtyCount = computed(() => pluginDirty.value.length + platDirty.value.length)
|
||||
|
||||
async function refresh() {
|
||||
try { await loadOverview(true) } catch (e) { message.error('读取失败:' + (e.message || e)) }
|
||||
}
|
||||
async function loadPlatforms() {
|
||||
grantDataBusy.value = true
|
||||
try {
|
||||
const r = await adminPlatforms()
|
||||
PLATFORM_OPTS.value = (r.platforms || []).map(p => ({ id: p.id, label: p.label }))
|
||||
} catch (e) { message.error('平台列表读取失败:' + (e.message || e)) }
|
||||
const [gd, pf] = await Promise.all([adminGrantData(), adminPlatforms()])
|
||||
plugins.value = gd.plugins || []
|
||||
accounts.value = gd.accounts || []
|
||||
PLATFORM_OPTS.value = (pf.platforms || []).map(p => ({ id: p.id, label: p.label }))
|
||||
} catch (e) { message.error('读取失败:' + (e.message || e)) }
|
||||
finally { grantDataBusy.value = false }
|
||||
}
|
||||
|
||||
async function savePluginDiff() {
|
||||
@@ -216,7 +241,7 @@ async function saveAll() {
|
||||
} catch (e) { message.error('保存失败:' + (e.message || e)) }
|
||||
finally { saving.value = false }
|
||||
}
|
||||
onMounted(() => { refresh(); loadPlatforms() })
|
||||
onMounted(refresh)
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
@@ -230,6 +255,7 @@ onMounted(() => { refresh(); loadPlatforms() })
|
||||
.section { margin-top: 24px; }
|
||||
.section-head { display: flex; justify-content: space-between; align-items: center; margin-bottom: 14px; }
|
||||
.section-head .card-title { margin-bottom: 0; }
|
||||
.gh-sec-right { display: flex; align-items: center; gap: 14px; }
|
||||
|
||||
/* 插件授权行 */
|
||||
.plist { display: flex; flex-direction: column; gap: 8px; }
|
||||
|
||||
@@ -8,18 +8,56 @@
|
||||
<el-button :loading="overviewBusy" :icon="Refresh" @click="refresh">刷新</el-button>
|
||||
</div>
|
||||
|
||||
<div class="stat-grid" v-if="ov">
|
||||
<div class="stat-card cp-card cp-rise" v-for="(s, i) in stats" :key="s.label" :class="{ wide: s.wide }" :style="{ animationDelay: i * 60 + 'ms' }">
|
||||
<div class="stat-ic" :style="{ background: s.bg, color: s.color }">
|
||||
<el-icon :size="20"><component :is="s.icon" /></el-icon>
|
||||
<template v-if="ov">
|
||||
<!-- 统计卡(4 列,与下方图表区对齐) -->
|
||||
<div class="stat-grid">
|
||||
<div class="stat-card cp-card cp-rise" v-for="(s, i) in stats" :key="s.label" :style="{ animationDelay: i * 60 + 'ms' }">
|
||||
<div class="stat-ic" :style="{ background: s.bg, color: s.color }">
|
||||
<el-icon :size="20"><component :is="s.icon" /></el-icon>
|
||||
</div>
|
||||
<div class="stat-meta">
|
||||
<div class="stat-num mono">{{ s.value }}</div>
|
||||
<div class="stat-label">{{ s.label }}</div>
|
||||
</div>
|
||||
<span class="stat-glow" :style="{ background: s.color }"></span>
|
||||
</div>
|
||||
<div class="stat-meta">
|
||||
<div class="stat-num mono" :class="{ sm: s.small }">{{ s.value }}</div>
|
||||
<div class="stat-label">{{ s.label }}</div>
|
||||
</div>
|
||||
<span class="stat-glow" :style="{ background: s.color }"></span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 图表区(两列独立高度,不拉伸) -->
|
||||
<div class="ov-grid">
|
||||
<div class="cp-card cp-rise chart-card">
|
||||
<div class="card-title">插件状态分布 <span class="sub">已发布 / 停用 / 已撤销</span></div>
|
||||
<div ref="pieEl" class="pie-chart"></div>
|
||||
<div class="pie-legend">
|
||||
<span v-for="c in pieLegend" :key="c.name">
|
||||
<i :style="{ background: c.color }"></i>{{ c.name }} <b class="mono">{{ c.value }}</b>
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="cp-card cp-rise chart-card">
|
||||
<div class="card-title">授权覆盖 <span class="sub">已授权插件账号 / 账号总数</span></div>
|
||||
<div ref="gaugeEl" class="gauge-chart"></div>
|
||||
<div class="gauge-num mono">
|
||||
<b>{{ authCount }}</b><span class="dim"> / {{ (ov.accounts || []).length }} 个账号已授权插件</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 最近动态 -->
|
||||
<div class="page-head sub cp-rise">
|
||||
<div><h4>最近动态</h4></div>
|
||||
</div>
|
||||
<div class="cp-card cp-rise feed-card">
|
||||
<div class="feed-item" v-for="v in recentUploads" :key="v.key">
|
||||
<span class="feed-dot"></span>
|
||||
<span class="feed-text mono">{{ v.plugin }}</span>
|
||||
<el-tag size="small" effect="plain" round type="primary" class="mono">v{{ v.version }}</el-tag>
|
||||
<span class="feed-time mono dim-sm">{{ fmtTime(v.uploaded_at) }}</span>
|
||||
</div>
|
||||
<div v-if="!recentUploads.length" class="empty">暂无上传记录</div>
|
||||
</div>
|
||||
</template>
|
||||
<el-skeleton v-else-if="overviewBusy" animated :rows="3" style="margin-top: 20px" />
|
||||
|
||||
<div class="tip-card cp-card cp-rise">
|
||||
@@ -33,9 +71,16 @@
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { computed, onMounted } from 'vue'
|
||||
import { Refresh, InfoFilled, Box, Collection, User, UserFilled, UploadFilled } from '@element-plus/icons-vue'
|
||||
import { computed, nextTick, onBeforeUnmount, onMounted, ref, watch } from 'vue'
|
||||
import { Refresh, InfoFilled, Box, Collection, User, UserFilled } from '@element-plus/icons-vue'
|
||||
import { ElMessage as message } from 'element-plus'
|
||||
// ECharts 按需引入(环图)
|
||||
import * as echarts from 'echarts/core'
|
||||
import { PieChart } from 'echarts/charts'
|
||||
import { TooltipComponent, LegendComponent } from 'echarts/components'
|
||||
import { CanvasRenderer } from 'echarts/renderers'
|
||||
echarts.use([PieChart, TooltipComponent, LegendComponent, CanvasRenderer])
|
||||
|
||||
import { store, overview, overviewBusy, loadOverview } from '../store'
|
||||
import { fmtTime } from '../format'
|
||||
|
||||
@@ -47,56 +92,115 @@ const stats = computed(() => {
|
||||
{ label: '版本总数', value: plugins.reduce((n, p) => n + (p.versions?.length || 0), 0), icon: Collection, color: '#7c5cf6', bg: 'linear-gradient(135deg,#f0ebfe,#e4dcfd)' },
|
||||
{ label: '账号', value: (ov.value?.accounts || []).length, icon: User, color: '#0f9f9b', bg: 'linear-gradient(135deg,#e4f6f5,#d2efee)' },
|
||||
{ label: '管理员', value: (ov.value?.admins || []).length, icon: UserFilled, color: '#1d9d5c', bg: 'linear-gradient(135deg,#e5f6ed,#d2efe0)' },
|
||||
{ label: '最近上传', value: latest(), icon: UploadFilled, color: '#d97706', bg: 'linear-gradient(135deg,#fbf0df,#f6e4c8)', small: true, wide: true },
|
||||
]
|
||||
})
|
||||
function latest() {
|
||||
const all = (ov.value?.plugins || []).flatMap(p => p.versions || []).map(v => v.uploaded_at).filter(Boolean)
|
||||
if (!all.length) return '—'
|
||||
return fmtTime(all.sort().at(-1))
|
||||
|
||||
// 最近上传(按时间倒序取 6 条)
|
||||
const recentUploads = computed(() => {
|
||||
const items = []
|
||||
for (const p of ov.value?.plugins || []) {
|
||||
for (const v of p.versions || []) {
|
||||
items.push({ key: p.id + v.version, plugin: p.id, version: v.version, uploaded_at: v.uploaded_at })
|
||||
}
|
||||
}
|
||||
return items.filter(i => i.uploaded_at).sort((a, b) => (a.uploaded_at < b.uploaded_at ? 1 : -1)).slice(0, 6)
|
||||
})
|
||||
|
||||
const authCount = computed(() => (ov.value?.accounts || []).filter(a => a.plugins?.length).length)
|
||||
const pieLegend = computed(() => [
|
||||
{ name: '已发布', color: '#1d9d5c', value: countStatus('published') },
|
||||
{ name: '停用', color: '#d97706', value: countStatus('disabled') },
|
||||
{ name: '已撤销', color: '#d6453d', value: countStatus('revoked') },
|
||||
])
|
||||
function countStatus(s) { return (ov.value?.plugins || []).filter(p => p.status === s).length }
|
||||
|
||||
// ---------- ECharts ----------
|
||||
const pieEl = ref(null)
|
||||
const gaugeEl = ref(null)
|
||||
let pieChart = null
|
||||
let gaugeChart = null
|
||||
|
||||
function renderCharts() {
|
||||
if (!ov.value) return
|
||||
const pieData = pieLegend.value.filter(c => c.value > 0)
|
||||
if (pieEl.value) {
|
||||
if (!pieChart) pieChart = echarts.init(pieEl.value)
|
||||
pieChart.setOption({
|
||||
tooltip: { trigger: 'item', formatter: '{b}: {c} ({d}%)' },
|
||||
series: [{
|
||||
type: 'pie', radius: ['58%', '78%'], center: ['50%', '50%'],
|
||||
avoidLabelOverlap: true,
|
||||
itemStyle: { borderRadius: 6, borderColor: '#fffdf8', borderWidth: 2 },
|
||||
label: { show: false }, emphasis: { label: { show: false } },
|
||||
data: pieData.map(c => ({ name: c.name, value: c.value, itemStyle: { color: c.color } })),
|
||||
}],
|
||||
})
|
||||
}
|
||||
const acc = (ov.value.accounts || []).length
|
||||
const authed = authCount.value
|
||||
const rate = acc ? Math.round(authed / acc * 100) : 0
|
||||
if (gaugeEl.value) {
|
||||
if (!gaugeChart) gaugeChart = echarts.init(gaugeEl.value)
|
||||
gaugeChart.setOption({
|
||||
series: [{
|
||||
type: 'pie', radius: ['62%', '80%'], center: ['50%', '50%'],
|
||||
silent: true,
|
||||
label: { show: true, position: 'center', formatter: rate + '%', fontSize: 26, fontWeight: 800, color: '#232a3a' },
|
||||
data: [
|
||||
{ value: authed, itemStyle: { color: '#2f5cf0' } },
|
||||
{ value: acc - authed, itemStyle: { color: 'rgba(35,42,58,.08)' } },
|
||||
],
|
||||
}],
|
||||
})
|
||||
}
|
||||
}
|
||||
// immediate:overview 有缓存(store 模块级)且 force 重拉失败时,ov 不变化也能渲染已有数据
|
||||
watch(ov, () => nextTick(renderCharts), { immediate: true })
|
||||
const onResize = () => { pieChart && pieChart.resize(); gaugeChart && gaugeChart.resize() }
|
||||
|
||||
async function refresh() {
|
||||
try { await loadOverview(true) } catch (e) { message.error('读取失败:' + (e.message || e)) }
|
||||
}
|
||||
onMounted(refresh)
|
||||
onMounted(() => { refresh(); window.addEventListener('resize', onResize) })
|
||||
onBeforeUnmount(() => { window.removeEventListener('resize', onResize); pieChart && pieChart.dispose(); gaugeChart && gaugeChart.dispose(); pieChart = gaugeChart = null })
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.stat-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fill, minmax(236px, 1fr));
|
||||
gap: 18px;
|
||||
}
|
||||
.stat-card {
|
||||
display: flex; align-items: center; gap: 16px;
|
||||
padding: 20px;
|
||||
overflow: hidden;
|
||||
}
|
||||
.stat-card.wide { grid-column: span 2; }
|
||||
.stat-ic {
|
||||
width: 48px; height: 48px; border-radius: 14px; flex-shrink: 0;
|
||||
display: grid; place-items: center;
|
||||
box-shadow: inset 0 0 0 1px rgba(255, 255, 255, .7);
|
||||
}
|
||||
.stat-grid { display: grid; grid-template-columns: repeat(4, 1fr); gap: 18px; }
|
||||
@media (max-width: 1100px) { .stat-grid { grid-template-columns: repeat(2, 1fr); } }
|
||||
.stat-card { display: flex; align-items: center; gap: 16px; padding: 20px; overflow: hidden; }
|
||||
.stat-ic { width: 48px; height: 48px; border-radius: 14px; flex-shrink: 0; display: grid; place-items: center; box-shadow: inset 0 0 0 1px rgba(255, 255, 255, .7); }
|
||||
.stat-meta { min-width: 0; }
|
||||
.stat-num { font-size: 27px; font-weight: 800; letter-spacing: .3px; line-height: 1.15; color: var(--cp-ink-1); }
|
||||
.stat-num.sm { font-size: 18px; font-weight: 700; white-space: nowrap; line-height: 1.4; }
|
||||
.stat-label { font-size: 12px; color: var(--cp-ink-3); margin-top: 4px; letter-spacing: .3px; }
|
||||
.stat-glow { position: absolute; left: 0; top: 0; bottom: 0; width: 3px; border-radius: 0 6px 6px 0; opacity: .9; }
|
||||
|
||||
.tip-card {
|
||||
margin-top: 20px;
|
||||
display: flex; gap: 14px;
|
||||
padding: 20px 22px;
|
||||
background: linear-gradient(135deg, rgba(47, 92, 240, .05), rgba(15, 159, 155, .04)), var(--cp-panel);
|
||||
}
|
||||
.tip-ic {
|
||||
width: 40px; height: 40px; border-radius: 12px; flex-shrink: 0;
|
||||
display: grid; place-items: center;
|
||||
background: linear-gradient(135deg, var(--cp-blue), var(--cp-teal));
|
||||
color: #fff;
|
||||
box-shadow: 0 8px 16px -8px rgba(47, 92, 240, .6);
|
||||
}
|
||||
/* 图表区两列独立高度 */
|
||||
.ov-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 18px; margin: 18px 0 0; align-items: start; }
|
||||
@media (max-width: 1100px) { .ov-grid { grid-template-columns: 1fr; } }
|
||||
.chart-card { padding: 20px; }
|
||||
.card-title { margin-bottom: 10px; }
|
||||
.card-title .sub { font-size: 11px; font-weight: 500; color: var(--cp-ink-3); margin-left: 4px; }
|
||||
.pie-chart { height: 210px; }
|
||||
.gauge-chart { height: 210px; }
|
||||
.pie-legend { display: flex; justify-content: center; gap: 20px; margin-top: 4px; font-size: 12.5px; color: var(--cp-ink-2); }
|
||||
.pie-legend i { width: 10px; height: 10px; border-radius: 3px; display: inline-block; margin-right: 6px; }
|
||||
.pie-legend b { margin-left: 3px; color: var(--cp-ink-1); }
|
||||
.gauge-num { text-align: center; margin-top: 2px; font-size: 13px; color: var(--cp-ink-2); }
|
||||
.gauge-num b { font-size: 20px; color: var(--cp-blue); }
|
||||
|
||||
.page-head.sub h4 { margin: 0; font-size: 15px; font-weight: 800; color: var(--cp-ink-1); }
|
||||
.feed-card { padding: 8px 18px; }
|
||||
.feed-item { display: flex; align-items: center; gap: 10px; padding: 9px 0; border-bottom: 1px dashed var(--cp-line); }
|
||||
.feed-item:last-child { border-bottom: none; }
|
||||
.feed-dot { width: 8px; height: 8px; border-radius: 50%; background: linear-gradient(135deg, var(--cp-blue), var(--cp-teal)); flex: none; }
|
||||
.feed-text { font-size: 13px; color: var(--cp-ink-1); min-width: 120px; }
|
||||
.feed-time { margin-left: auto; }
|
||||
.empty { color: var(--cp-ink-3); font-size: 12px; padding: 14px 0; text-align: center; }
|
||||
|
||||
.tip-card { margin-top: 20px; display: flex; gap: 14px; padding: 20px 22px; background: linear-gradient(135deg, rgba(47, 92, 240, .05), rgba(15, 159, 155, .04)), var(--cp-panel); }
|
||||
.tip-ic { width: 40px; height: 40px; border-radius: 12px; flex-shrink: 0; display: grid; place-items: center; background: linear-gradient(135deg, var(--cp-blue), var(--cp-teal)); color: #fff; box-shadow: 0 8px 16px -8px rgba(47, 92, 240, .6); }
|
||||
.tip-body b { display: block; font-size: 14px; color: var(--cp-ink-1); margin-bottom: 5px; }
|
||||
.tip-body p { margin: 0; font-size: 12.5px; line-height: 1.8; color: var(--cp-ink-2); }
|
||||
.dim-sm { color: var(--cp-ink-3); font-size: 12px; }
|
||||
</style>
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
<h3>插件管理 <span class="badge">Plugins</span></h3>
|
||||
<p>上传发布插件包 · 每插件保留最近 3 个版本,超出自动清理</p>
|
||||
</div>
|
||||
<el-button :loading="overviewBusy" :icon="Refresh" @click="refresh">刷新</el-button>
|
||||
<el-button :loading="listBusy" :icon="Refresh" @click="refresh">刷新</el-button>
|
||||
</div>
|
||||
|
||||
<div class="cp-card block cp-rise up-card">
|
||||
@@ -38,8 +38,11 @@
|
||||
</div>
|
||||
|
||||
<div class="cp-card block cp-rise list-card">
|
||||
<div class="card-title">插件列表</div>
|
||||
<el-table :data="plugins" size="small" :loading="overviewBusy" :row-key="r => r.id">
|
||||
<div class="list-head">
|
||||
<div class="card-title">插件列表</div>
|
||||
<el-input v-model="kw" placeholder="搜索插件 ID / 名称" clearable :prefix-icon="Search" size="small" style="width: 230px" @keyup.enter="onSearch" @clear="onSearch" />
|
||||
</div>
|
||||
<el-table :data="plugins" size="small" :loading="listBusy" :row-key="r => r.id">
|
||||
<el-table-column label="插件 ID" min-width="160">
|
||||
<template #default="{ row }"><b class="cell-strong mono">{{ row.id }}</b></template>
|
||||
</el-table-column>
|
||||
@@ -70,6 +73,7 @@
|
||||
</template>
|
||||
</el-table-column>
|
||||
</el-table>
|
||||
<PagerBar :total="total" :page="page" :page-size="pageSize" @change="onPageChange" />
|
||||
</div>
|
||||
|
||||
<!-- 编辑插件 -->
|
||||
@@ -199,7 +203,7 @@
|
||||
<div class="dt-sec">
|
||||
<div class="ed-sec-title">授权账号</div>
|
||||
<div class="tags" v-if="detail.accounts?.length">
|
||||
<el-tag v-for="a in detail.accounts" :key="a" size="small" effect="plain" type="success" round class="mono">{{ a }}</el-tag>
|
||||
<el-tag v-for="a in detail.accounts" :key="a.account" size="small" effect="plain" type="success" round class="mono">{{ a.nickname ? `${a.nickname} · ${a.account}` : a.account }}</el-tag>
|
||||
</div>
|
||||
<span v-else class="dim">未授权任何账号,执行端不可见</span>
|
||||
</div>
|
||||
@@ -213,15 +217,19 @@
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { computed, onMounted, reactive, ref } from 'vue'
|
||||
import { onMounted, reactive, ref } from 'vue'
|
||||
import { ElMessage as message, ElMessageBox as dialog } from 'element-plus'
|
||||
import { Refresh, UploadFilled, FolderOpened, Edit, Delete, View, Box, Files, User, Clock } from '@element-plus/icons-vue'
|
||||
import { overview, overviewBusy, loadOverview } from '../store'
|
||||
import { adminUpload, adminPluginDelete, adminPluginPatch } from '../api'
|
||||
import { Refresh, UploadFilled, FolderOpened, Edit, Delete, View, Box, Files, User, Clock, Search } from '@element-plus/icons-vue'
|
||||
import { adminPlugins, adminUpload, adminPluginDelete, adminPluginPatch } from '../api'
|
||||
import { fmtTime } from '../format'
|
||||
import PagerBar from '../components/PagerBar.vue'
|
||||
import { usePagedList } from '../composables/usePagedList'
|
||||
|
||||
const plugins = computed(() => overview.value?.plugins || [])
|
||||
const kw = ref('')
|
||||
const list = usePagedList((p, s) => adminPlugins(p, s, kw.value), { onError: e => message.error('读取失败:' + (e.message || e)) })
|
||||
const { items: plugins, total, page, size: pageSize, busy: listBusy, load: refresh, onPageChange, reset } = list
|
||||
const pid = ref(''); const pname = ref(''); const pver = ref(''); const pfile = ref(null)
|
||||
function onSearch() { reset() }
|
||||
const uploading = ref(false)
|
||||
const upRef = ref()
|
||||
|
||||
@@ -286,9 +294,6 @@ async function saveEdit() {
|
||||
finally { saving.value = false }
|
||||
}
|
||||
|
||||
async function refresh() {
|
||||
try { await loadOverview(true) } catch (e) { message.error('读取失败:' + (e.message || e)) }
|
||||
}
|
||||
async function upload() {
|
||||
if (!pid.value || !pver.value || !pfile.value) { message.warning('请填写插件 ID / 版本并选择 ZIP 包'); return }
|
||||
uploading.value = true
|
||||
@@ -317,6 +322,8 @@ onMounted(refresh)
|
||||
<style scoped>
|
||||
.up-card, .list-card { padding: 20px 22px; }
|
||||
.up-card .card-title { margin-bottom: 16px; }
|
||||
.list-head { display: flex; justify-content: space-between; align-items: center; margin-bottom: 14px; }
|
||||
.list-head .card-title { margin-bottom: 0; }
|
||||
.up-form :deep(.el-form-item) { margin-bottom: 16px; }
|
||||
.file-row { display: flex; align-items: center; gap: 10px; }
|
||||
.hint { font-size: 12px; color: var(--cp-ink-3); margin-top: 2px; line-height: 1.7; }
|
||||
|
||||
@@ -2,19 +2,17 @@
|
||||
<div class="page">
|
||||
<div class="page-head cp-rise">
|
||||
<div>
|
||||
<h3>运行统计 <span class="badge">Stats</span></h3>
|
||||
<p>账号 · 插件规模 · 执行次数/时长/成败 · 近 14 天趋势</p>
|
||||
<h3>数据看板 <span class="badge">Stats</span></h3>
|
||||
<p>运行统计 · 近 14 天趋势曲线 · 插件/用户排行 · 最近运行记录(分页)</p>
|
||||
</div>
|
||||
<el-button :loading="busy" :icon="Refresh" @click="refresh">刷新</el-button>
|
||||
</div>
|
||||
|
||||
<template v-if="st">
|
||||
<!-- 指标卡 -->
|
||||
<!-- KPI -->
|
||||
<div class="kpis cp-rise">
|
||||
<div class="kpi cp-card" v-for="(k, i) in kpis" :key="k.label" :style="{ animationDelay: i * 50 + 'ms' }">
|
||||
<div class="kpi-ic" :style="{ background: k.bg, color: k.color }">
|
||||
<el-icon :size="18"><component :is="k.icon" /></el-icon>
|
||||
</div>
|
||||
<div class="kpi-ic" :style="{ background: k.bg, color: k.color }"><el-icon :size="17"><component :is="k.icon" /></el-icon></div>
|
||||
<div class="kpi-meta">
|
||||
<div class="kpi-num mono" :style="{ color: k.color }">{{ k.value }}</div>
|
||||
<div class="kpi-lab">{{ k.label }}</div>
|
||||
@@ -22,68 +20,55 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="grid">
|
||||
<!-- 近 14 天趋势 -->
|
||||
<div class="cp-card trend-card cp-rise">
|
||||
<div class="card-title">近 14 天运行趋势</div>
|
||||
<div class="trend">
|
||||
<div class="tcol" v-for="d in st.trend" :key="d.day" :title="`${d.day} · ${d.runs} 次(成功 ${d.success} / 失败 ${d.failed})`">
|
||||
<div class="tstack">
|
||||
<div class="tbar failed" :style="{ height: pct(d.failed, maxRuns) + '%' }"></div>
|
||||
<div class="tbar success" :style="{ height: pct(d.success, maxRuns) + '%' }"></div>
|
||||
<!-- 趋势曲线(全宽置顶) -->
|
||||
<div class="cp-card cp-rise chart-card">
|
||||
<div class="card-title">近 14 天运行趋势 <span class="sub">成功 / 失败 · 平滑曲线</span></div>
|
||||
<div ref="trendEl" class="chart"></div>
|
||||
</div>
|
||||
|
||||
<!-- 排行(两列左右分布) -->
|
||||
<div class="rank-grid">
|
||||
<div class="cp-card cp-rise rank-card">
|
||||
<div class="card-title">插件排行 <span class="sub">按触发次数</span></div>
|
||||
<ul class="rank" v-if="st.topPlugins.length">
|
||||
<li v-for="(p, i) in st.topPlugins" :key="p.pluginId">
|
||||
<span class="rk" :class="{ top: i < 3 }">{{ i + 1 }}</span>
|
||||
<div class="rbody">
|
||||
<div class="rhead">
|
||||
<span class="rname">{{ p.name }}</span>
|
||||
<em>{{ p.runs }} 次</em>
|
||||
</div>
|
||||
<div class="rbar"><i :style="{ width: Math.round(p.runs / rankMax(st.topPlugins) * 100) + '%' }"></i></div>
|
||||
</div>
|
||||
<span class="tday mono">{{ d.day }}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="trend-legend">
|
||||
<span><i class="dot ok"></i>成功</span>
|
||||
<span><i class="dot fail"></i>失败</span>
|
||||
</div>
|
||||
</li>
|
||||
</ul>
|
||||
<div v-else class="empty">暂无运行数据</div>
|
||||
</div>
|
||||
|
||||
<!-- 插件 / 用户排行 -->
|
||||
<div class="rank-wrap">
|
||||
<div class="cp-card rank-card cp-rise">
|
||||
<div class="card-title">插件排行 <span class="sub">按运行次数</span></div>
|
||||
<ul class="rank">
|
||||
<li v-for="(p, i) in st.topPlugins" :key="p.pluginId">
|
||||
<span class="rk mono" :class="{ top: i < 3 }">{{ i + 1 }}</span>
|
||||
<div class="rbody">
|
||||
<div class="rhead">
|
||||
<span class="rname mono">{{ p.name || p.pluginId }}</span>
|
||||
<em class="mono">{{ p.runs }} 次</em>
|
||||
</div>
|
||||
<div class="rbar"><i :style="{ width: pct(p.runs, rankMax(st.topPlugins)) + '%' }"></i></div>
|
||||
<div class="cp-card cp-rise rank-card">
|
||||
<div class="card-title">活跃用户 <span class="sub">按执行次数</span></div>
|
||||
<ul class="rank" v-if="st.topUsers.length">
|
||||
<li v-for="(u, i) in st.topUsers" :key="u.account">
|
||||
<span class="rk" :class="{ top: i < 3 }">{{ i + 1 }}</span>
|
||||
<div class="rbody">
|
||||
<div class="rhead">
|
||||
<span class="rname mono">{{ u.nickname ? `${u.nickname} · ${u.account}` : u.account }}</span>
|
||||
<em>{{ u.runs }} 次</em>
|
||||
</div>
|
||||
</li>
|
||||
<li v-if="!st.topPlugins.length" class="empty">暂无运行记录</li>
|
||||
</ul>
|
||||
</div>
|
||||
<div class="cp-card rank-card cp-rise">
|
||||
<div class="card-title">活跃用户 <span class="sub">按运行次数</span></div>
|
||||
<ul class="rank">
|
||||
<li v-for="(u, i) in st.topUsers" :key="u.account">
|
||||
<span class="rk mono" :class="{ top: i < 3 }">{{ i + 1 }}</span>
|
||||
<div class="rbody">
|
||||
<div class="rhead">
|
||||
<span class="rname mono">{{ u.account }}</span>
|
||||
<em class="mono">{{ u.runs }} 次</em>
|
||||
</div>
|
||||
<div class="rbar"><i :style="{ width: pct(u.runs, rankMax(st.topUsers)) + '%' }"></i></div>
|
||||
</div>
|
||||
</li>
|
||||
<li v-if="!st.topUsers.length" class="empty">暂无运行记录</li>
|
||||
</ul>
|
||||
</div>
|
||||
<div class="rbar"><i :style="{ width: Math.round(u.runs / rankMax(st.topUsers) * 100) + '%' }"></i></div>
|
||||
</div>
|
||||
</li>
|
||||
</ul>
|
||||
<div v-else class="empty">暂无执行记录</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 最近运行 -->
|
||||
<!-- 最近运行(后端分页) -->
|
||||
<div class="page-head sub cp-rise">
|
||||
<div><h4>最近运行</h4></div>
|
||||
</div>
|
||||
<div class="cp-card cp-rise recent-card">
|
||||
<el-table :data="st.recent" size="small" :row-key="r => r.at + r.pluginId">
|
||||
<el-table :data="recent" size="small" v-loading="recentBusy" :row-key="r => r.id">
|
||||
<el-table-column label="时间" width="170">
|
||||
<template #default="{ row }"><span class="mono dim-sm">{{ fmtTime(row.at) }}</span></template>
|
||||
</el-table-column>
|
||||
@@ -92,13 +77,9 @@
|
||||
<span class="status-dot"><i :style="{ background: statusColor(row.status) }"></i><span :style="{ color: statusColor(row.status) }">{{ statusLabel(row.status) }}</span></span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="账号" width="140">
|
||||
<el-table-column label="账号" width="150">
|
||||
<template #default="{ row }">
|
||||
<div class="acct" v-if="row.nickname">
|
||||
<div class="ann">{{ row.account }}</div>
|
||||
<div class="anick">{{ row.nickname }}</div>
|
||||
</div>
|
||||
<span v-else>{{ row.account || '—' }}</span>
|
||||
<span class="mono">{{ row.nickname ? `${row.nickname} · ${row.account}` : (row.account || '—') }}</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="插件" width="160" show-overflow-tooltip>
|
||||
@@ -110,12 +91,11 @@
|
||||
<el-table-column label="时长" width="100">
|
||||
<template #default="{ row }"><span class="mono">{{ fmtDur(row.durationSec) }}</span></template>
|
||||
</el-table-column>
|
||||
<el-table-column label="信息" min-width="220" show-overflow-tooltip>
|
||||
<template #default="{ row }">
|
||||
<span :class="{ dim: !row.msg }">{{ row.msg || '—' }}</span>
|
||||
</template>
|
||||
<el-table-column label="信息" min-width="200" show-overflow-tooltip>
|
||||
<template #default="{ row }"><span :class="{ dim: !row.msg }">{{ row.msg || '—' }}</span></template>
|
||||
</el-table-column>
|
||||
</el-table>
|
||||
<PagerBar :total="recentTotal" :page="page" :page-size="pageSize" @change="onPageChange" />
|
||||
</div>
|
||||
</template>
|
||||
|
||||
@@ -125,22 +105,37 @@
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { computed, onMounted, ref } from 'vue'
|
||||
import { computed, nextTick, onBeforeUnmount, onMounted, ref, watch } from 'vue'
|
||||
import { Refresh, User, Box, VideoPlay, CircleCheckFilled, CircleCloseFilled, Timer } from '@element-plus/icons-vue'
|
||||
import { ElMessage as message } from 'element-plus'
|
||||
import { adminStats } from '../api'
|
||||
// ECharts 按需引入(折线图),避免全量包
|
||||
import * as echarts from 'echarts/core'
|
||||
import { LineChart } from 'echarts/charts'
|
||||
import { GridComponent, TooltipComponent, LegendComponent } from 'echarts/components'
|
||||
import { CanvasRenderer } from 'echarts/renderers'
|
||||
echarts.use([LineChart, GridComponent, TooltipComponent, LegendComponent, CanvasRenderer])
|
||||
|
||||
import { adminStats, adminReports } from '../api'
|
||||
import { fmtTime } from '../format'
|
||||
import PagerBar from '../components/PagerBar.vue'
|
||||
|
||||
const busy = ref(false)
|
||||
const st = ref(null)
|
||||
|
||||
// 最近运行:独立走 /api/admin/reports 后端分页(数据增长无压力)
|
||||
import { usePagedList } from '../composables/usePagedList'
|
||||
const recentList = usePagedList((p, s) => adminReports(p, s), { onError: e => message.error('读取失败:' + (e.message || e)) })
|
||||
const { items: recent, total: recentTotal, page, size: pageSize, busy: recentBusy, load: loadRecent, onPageChange } = recentList
|
||||
|
||||
const kpis = computed(() => {
|
||||
if (!st.value) return []
|
||||
const r = st.value
|
||||
// 累计执行 = 成功 + 失败(已完成任务数,口径一致);触发数 start(含运行中/中断残留)不作为累计
|
||||
const finished = (r.runs.success || 0) + (r.runs.failed || 0)
|
||||
return [
|
||||
{ label: '用户总数', value: r.users.total, icon: User, color: '#2f5cf0', bg: 'linear-gradient(135deg,#e8edfe,#d7e1fd)' },
|
||||
{ label: '插件总数', value: r.plugins.total, icon: Box, color: '#7c5cf6', bg: 'linear-gradient(135deg,#f0ebfe,#e4dcfd)' },
|
||||
{ label: '累计执行', value: r.runs.total, icon: VideoPlay, color: '#0f9f9b', bg: 'linear-gradient(135deg,#e4f6f5,#d2efee)' },
|
||||
{ label: '累计执行', value: finished, icon: VideoPlay, color: '#0f9f9b', bg: 'linear-gradient(135deg,#e4f6f5,#d2efee)' },
|
||||
{ label: '成功', value: r.runs.success, icon: CircleCheckFilled, color: '#1d9d5c', bg: 'linear-gradient(135deg,#e5f6ed,#d2efe0)' },
|
||||
{ label: '失败', value: r.runs.failed, icon: CircleCloseFilled, color: '#d6453d', bg: 'linear-gradient(135deg,#fbe9e8,#f6d8d6)' },
|
||||
{ label: '总运行时长', value: fmtDur(r.runs.durationSec), icon: Timer, color: '#d97706', bg: 'linear-gradient(135deg,#fbf0df,#f6e4c8)' },
|
||||
@@ -151,7 +146,7 @@ function statusColor(s) {
|
||||
return { done: '#1d9d5c', success: '#1d9d5c', error: '#d6453d', failed: '#d6453d', running: '#2f5cf0', start: '#2f5cf0' }[s] || '#9aa2b4'
|
||||
}
|
||||
function statusLabel(s) {
|
||||
return (s === 'done' || s === 'success') ? '成功' : (s === 'error' || s === 'failed') ? '失败' : s
|
||||
return ({ done: '成功', success: '成功', error: '失败', failed: '失败', running: '运行中', start: '已触发' })[s] || s
|
||||
}
|
||||
function fmtDur(sec) {
|
||||
sec = +sec || 0
|
||||
@@ -161,10 +156,40 @@ function fmtDur(sec) {
|
||||
const hh = Math.floor(m / 60)
|
||||
return `${hh}h${m % 60}m`
|
||||
}
|
||||
const maxRuns = () => Math.max(1, ...(st.value?.trend || []).map(t => t.runs || 0))
|
||||
const pct = (n, max) => Math.max(2, Math.round((n || 0) / (max || 1) * 100))
|
||||
const rankMax = list => Math.max(1, ...(list || []).map(x => x.runs || 1))
|
||||
|
||||
// ---------- ECharts 趋势曲线 ----------
|
||||
const trendEl = ref(null)
|
||||
let chart = null
|
||||
|
||||
function renderTrend() {
|
||||
if (!st.value || !trendEl.value) return
|
||||
if (!chart) chart = echarts.init(trendEl.value)
|
||||
chart.setOption({
|
||||
tooltip: { trigger: 'axis', backgroundColor: 'rgba(35,42,58,.92)', borderWidth: 0, textStyle: { color: '#fff', fontSize: 12 } },
|
||||
legend: { data: ['成功', '失败'], right: 4, top: 0, icon: 'roundRect', itemWidth: 14, itemHeight: 5, textStyle: { color: '#6b7488', fontSize: 12 } },
|
||||
grid: { left: 36, right: 16, top: 36, bottom: 24 },
|
||||
xAxis: { type: 'category', boundaryGap: false, data: st.value.trend.map(t => t.day),
|
||||
axisLine: { lineStyle: { color: 'rgba(35,42,58,.16)' } }, axisTick: { show: false },
|
||||
axisLabel: { fontSize: 10.5, color: '#9aa2b4' } },
|
||||
yAxis: { type: 'value', minInterval: 1, splitLine: { lineStyle: { color: 'rgba(35,42,58,.07)' } },
|
||||
axisLabel: { fontSize: 10.5, color: '#9aa2b4' } },
|
||||
series: [
|
||||
{ name: '成功', type: 'line', smooth: true, symbolSize: 6, data: st.value.trend.map(t => t.success || 0),
|
||||
lineStyle: { width: 2.6, color: '#1d9d5c' }, itemStyle: { color: '#1d9d5c' },
|
||||
areaStyle: { color: { type: 'linear', x: 0, y: 0, x2: 0, y2: 1, colorStops: [
|
||||
{ offset: 0, color: 'rgba(29,157,92,.20)' }, { offset: 1, color: 'rgba(29,157,92,.01)' }] } } },
|
||||
{ name: '失败', type: 'line', smooth: true, symbolSize: 6, data: st.value.trend.map(t => t.failed || 0),
|
||||
lineStyle: { width: 2.6, color: '#d6453d' }, itemStyle: { color: '#d6453d' },
|
||||
areaStyle: { color: { type: 'linear', x: 0, y: 0, x2: 0, y2: 1, colorStops: [
|
||||
{ offset: 0, color: 'rgba(214,69,61,.16)' }, { offset: 1, color: 'rgba(214,69,61,.01)' }] } } },
|
||||
],
|
||||
})
|
||||
}
|
||||
watch(st, () => nextTick(renderTrend))
|
||||
const onResize = () => chart && chart.resize()
|
||||
|
||||
// ---------- 数据 ----------
|
||||
async function refresh() {
|
||||
busy.value = true
|
||||
try {
|
||||
@@ -172,57 +197,39 @@ async function refresh() {
|
||||
st.value = {
|
||||
users: r.users || {}, plugins: r.plugins || {}, runs: r.runs || {},
|
||||
trend: r.trend || [], topPlugins: r.topPlugins || [], topUsers: r.topUsers || [],
|
||||
recent: r.recent || [],
|
||||
}
|
||||
await loadRecent()
|
||||
} catch (e) { message.error('读取失败:' + (e.message || e)) }
|
||||
finally { busy.value = false }
|
||||
}
|
||||
onMounted(refresh)
|
||||
|
||||
onMounted(() => { refresh(); window.addEventListener('resize', onResize) })
|
||||
onBeforeUnmount(() => { window.removeEventListener('resize', onResize); chart && chart.dispose(); chart = null })
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.kpis { display: grid; grid-template-columns: repeat(6, 1fr); gap: 16px; margin-bottom: 18px; }
|
||||
@media (max-width: 1100px) { .kpis { grid-template-columns: repeat(3, 1fr); } }
|
||||
.kpi {
|
||||
display: flex; align-items: center; gap: 14px;
|
||||
padding: 18px;
|
||||
}
|
||||
.kpi-ic {
|
||||
width: 42px; height: 42px; border-radius: 13px; flex-shrink: 0;
|
||||
display: grid; place-items: center;
|
||||
box-shadow: inset 0 0 0 1px rgba(255, 255, 255, .7);
|
||||
}
|
||||
.kpi { display: flex; align-items: center; gap: 14px; padding: 18px; }
|
||||
.kpi-ic { width: 42px; height: 42px; border-radius: 13px; flex-shrink: 0; display: grid; place-items: center; box-shadow: inset 0 0 0 1px rgba(255, 255, 255, .7); }
|
||||
.kpi-meta { min-width: 0; }
|
||||
.kpi-num { font-size: 24px; font-weight: 800; line-height: 1.1; }
|
||||
.kpi-lab { font-size: 12px; color: var(--cp-ink-3); margin-top: 4px; letter-spacing: .3px; }
|
||||
|
||||
.grid { display: grid; grid-template-columns: 1.45fr 1fr; gap: 18px; margin-bottom: 20px; }
|
||||
@media (max-width: 1100px) { .grid { grid-template-columns: 1fr; } }
|
||||
.rank-wrap { display: flex; flex-direction: column; gap: 18px; }
|
||||
.trend-card, .rank-card { padding: 20px; }
|
||||
.card-title { margin-bottom: 16px; }
|
||||
/* 趋势图全宽置顶 */
|
||||
.chart-card { padding: 20px; margin-bottom: 18px; }
|
||||
.chart { height: 320px; }
|
||||
|
||||
/* 排行两列左右分布 */
|
||||
.rank-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 18px; margin-bottom: 20px; }
|
||||
@media (max-width: 900px) { .rank-grid { grid-template-columns: 1fr; } }
|
||||
.rank-card { padding: 20px; }
|
||||
.card-title { margin-bottom: 14px; }
|
||||
.card-title .sub { font-size: 11px; font-weight: 500; color: var(--cp-ink-3); margin-left: 4px; }
|
||||
|
||||
.trend { display: flex; gap: 5px; height: 176px; align-items: stretch; }
|
||||
.tcol { flex: 1; display: flex; flex-direction: column; justify-content: flex-end; align-items: center; gap: 6px; }
|
||||
.tstack { flex: 1; display: flex; align-items: flex-end; gap: 2px; width: 100%; }
|
||||
.tbar { flex: 1; border-radius: 3px 3px 0 0; transition: filter .18s, transform .18s; }
|
||||
.tbar.success { background: linear-gradient(180deg, #34b877, #1d9d5c); }
|
||||
.tbar.failed { background: linear-gradient(180deg, #f07a72, #d6453d); }
|
||||
.tcol:hover .tbar { filter: brightness(1.05); }
|
||||
.tday { font-size: 10px; color: var(--cp-ink-3); }
|
||||
.trend-legend { display: flex; gap: 18px; margin-top: 14px; font-size: 12px; color: var(--cp-ink-2); }
|
||||
.trend-legend .dot { width: 9px; height: 9px; border-radius: 3px; display: inline-block; margin-right: 6px; }
|
||||
.trend-legend .ok { background: #1d9d5c; }
|
||||
.trend-legend .fail { background: #d6453d; }
|
||||
|
||||
.rank { list-style: none; margin: 0; padding: 0; }
|
||||
.rank li { display: flex; align-items: center; gap: 11px; padding: 8px 0; }
|
||||
.rank .rk {
|
||||
width: 24px; height: 24px; flex: none; border-radius: 8px;
|
||||
background: var(--cp-panel-2); color: var(--cp-ink-3);
|
||||
font-size: 12px; font-weight: 700; display: flex; align-items: center; justify-content: center;
|
||||
}
|
||||
.rank li { display: flex; align-items: center; gap: 11px; padding: 7px 0; }
|
||||
.rank .rk { width: 24px; height: 24px; flex: none; border-radius: 8px; background: var(--cp-panel-2); color: var(--cp-ink-3); font-size: 12px; font-weight: 700; display: flex; align-items: center; justify-content: center; }
|
||||
.rank .rk.top { background: linear-gradient(135deg, var(--cp-blue), var(--cp-teal)); color: #fff; box-shadow: 0 4px 10px -4px rgba(47, 92, 240, .5); }
|
||||
.rank .rbody { flex: 1; min-width: 0; }
|
||||
.rhead { display: flex; justify-content: space-between; align-items: center; margin-bottom: 6px; gap: 10px; }
|
||||
@@ -230,10 +237,12 @@ onMounted(refresh)
|
||||
.rhead em { font-style: normal; font-size: 11.5px; color: var(--cp-ink-3); flex: none; }
|
||||
.rbar { height: 6px; border-radius: 4px; background: var(--cp-panel-2); overflow: hidden; }
|
||||
.rbar i { display: block; height: 100%; background: linear-gradient(90deg, var(--cp-blue), var(--cp-teal)); border-radius: 4px; transition: width .6s cubic-bezier(.22, .61, .36, 1); }
|
||||
.empty { color: var(--cp-ink-3); font-size: 12px; justify-content: center; padding: 18px 0 !important; }
|
||||
.empty { color: var(--cp-ink-3); font-size: 12px; justify-content: center; padding: 18px 0 !important; display: flex; }
|
||||
.empty-tip { padding: 40px; text-align: center; color: var(--cp-ink-3); }
|
||||
|
||||
.page-head.sub h4 { margin: 0; font-size: 15px; font-weight: 800; color: var(--cp-ink-1); }
|
||||
.recent-card { padding: 12px 16px; }
|
||||
.dim-sm { color: var(--cp-ink-2); }
|
||||
.dim-sm { color: var(--cp-ink-2); font-size: 12px; }
|
||||
.status-dot { display: inline-flex; align-items: center; gap: 6px; font-size: 12.5px; }
|
||||
.status-dot i { width: 8px; height: 8px; border-radius: 50%; display: inline-block; }
|
||||
</style>
|
||||
|
||||
@@ -15,7 +15,7 @@
|
||||
走 /api/admin/auth 用账号+密码换 1 小时票据,管理主密钥不出服务器。
|
||||
- 本机密钥自签(原方式,中心机本机):直接复用 desktop/controlplane/.env 与 .admin_secret,
|
||||
X-API-Token 取自 CONTROLPLANE_TOKEN(.env);为空则该接口不强制,无需携带。
|
||||
X-Admin-Token 用 CONTROLPLANE_ADMIN_SECRET > CONTROLPLANE_TOKEN > .admin_secret 本地自签。
|
||||
X-Admin-Token 用 CONTROLPLANE_ADMIN_SECRET > .admin_secret 本地自签(不再回退 CONTROLPLANE_TOKEN)。
|
||||
中心机地址默认本机 8800;远程发版用 --base 或环境变量 CONTROLPLANE_AGENT_BASE 指向中心机公网地址。
|
||||
|
||||
管理员账号:需用 --admin 显式指定(或设环境变量 AGENT_ADMIN_ACCOUNT),该账号须 is_admin=1。
|
||||
@@ -68,8 +68,9 @@ FILESERVER_TOKEN = os.getenv("FILESERVER_TOKEN", "")
|
||||
|
||||
|
||||
def _admin_secret() -> str:
|
||||
"""与 app.py 完全一致:CONTROLPLANE_ADMIN_SECRET > CONTROLPLANE_TOKEN > .admin_secret。"""
|
||||
cand = os.getenv("CONTROLPLANE_ADMIN_SECRET") or os.getenv("CONTROLPLANE_TOKEN") or ""
|
||||
"""与 app.py 完全一致:CONTROLPLANE_ADMIN_SECRET > .admin_secret(不再回退 CONTROLPLANE_TOKEN,
|
||||
传输凭证与管理密钥分离,避免持 X-API-Token 者自签管理员票据)。"""
|
||||
cand = os.getenv("CONTROLPLANE_ADMIN_SECRET") or ""
|
||||
if cand:
|
||||
return cand
|
||||
_f = APP_DIR / ".admin_secret"
|
||||
|
||||
@@ -69,6 +69,10 @@ def submit_run(account: str, plugin, fields: dict) -> str:
|
||||
"msg": "设备正有其他插件执行中,排队等待其完成后自动启动…"})
|
||||
|
||||
def _start():
|
||||
if _is_user_stopped(run_id):
|
||||
# 排队期间用户已点停止:不真正拉起插件,抛异常让 request_start 回滚单活槽位,
|
||||
# 由下方 !ok 分支把 run 落为"用户手动强制停止",避免"看似取消实际还在跑"。
|
||||
raise RuntimeError("用户已取消该排队任务")
|
||||
threading.Thread(target=_run_target,
|
||||
args=(plugin, fields, run_id),
|
||||
daemon=True, name=f"exec-{plugin.id}").start()
|
||||
@@ -78,10 +82,14 @@ def submit_run(account: str, plugin, fields: dict) -> str:
|
||||
getattr(plugin, "version", "0"), _start)
|
||||
if not r.get("ok"):
|
||||
# 启动失败(回滚已发生):落地错误结果并广播,避免前端永久等待
|
||||
_st._set_run(run_id, status="error", result=None,
|
||||
error=r.get("error") or "启动失败")
|
||||
err = r.get("error") or "启动失败"
|
||||
if _is_user_stopped(run_id):
|
||||
err = "用户手动强制停止"
|
||||
with _STOP_LOCK:
|
||||
_USER_STOPPED.discard(run_id)
|
||||
_st._set_run(run_id, status="error", result=None, error=err)
|
||||
HUB.publish({"t": "run_done", "run_id": run_id, "ok": False,
|
||||
"error": r.get("error") or "启动失败"})
|
||||
"error": err})
|
||||
|
||||
threading.Thread(target=_queued, daemon=True,
|
||||
name=f"run-{plugin.id}").start()
|
||||
|
||||
@@ -26,11 +26,14 @@ _APP_DATA = Path(os.getenv("LOCALAPPDATA") or os.getenv("APPDATA")
|
||||
_SCHED_FILE = _APP_DATA / "schedules.json"
|
||||
|
||||
_TICK_SECS = 30 # 后台检查周期(秒)
|
||||
_DENY_LOG_CD = 300 # 同一任务触发被拒后,拒绝日志的最小间隔(秒),避免离线时刷屏
|
||||
_STARTED = False
|
||||
|
||||
_LOCK = threading.RLock()
|
||||
# 内存中的任务列表(dict 列表),持久化到 _SCHED_FILE
|
||||
_SCHEDULES: list = []
|
||||
# 任务 id → 上次打印"触发被拒"日志的时间戳(节流用)
|
||||
_deny_log_ts: dict = {}
|
||||
|
||||
|
||||
# ==================== 标准 5 段 cron 解析 ====================
|
||||
@@ -256,7 +259,8 @@ def _public(s: dict) -> dict:
|
||||
out = dict(s)
|
||||
out["enabled"] = bool(out.get("enabled"))
|
||||
out["last_run_at"] = out.get("last_run_at") or ""
|
||||
nxt = next_run_at(s)
|
||||
# 已停用任务不再推算/展示下次执行,避免误导
|
||||
nxt = next_run_at(s) if out["enabled"] else None
|
||||
out["next_run_at"] = nxt.strftime("%Y-%m-%d %H:%M:%S") if nxt else ""
|
||||
return out
|
||||
|
||||
@@ -331,8 +335,14 @@ def _fire(s: dict) -> bool:
|
||||
account = s.get("account", "")
|
||||
deny = licensing.run_check_allowed(plugin.id, account, licensing.is_online())
|
||||
if deny:
|
||||
_LOGGER.warning("定时任务「%s」触发被拒(账号 %s):%s",
|
||||
s.get("name"), account, deny)
|
||||
# 拒绝日志节流:同一任务至少间隔 _DENY_LOG_CD 秒才再记一条,避免授权失效时每 tick 刷屏
|
||||
_ts = time.time()
|
||||
with _LOCK:
|
||||
_last = _deny_log_ts.get(s.get("id"))
|
||||
_deny_log_ts[s.get("id")] = _ts
|
||||
if _last is None or _ts - _last >= _DENY_LOG_CD:
|
||||
_LOGGER.warning("定时任务「%s」触发被拒(账号 %s):%s",
|
||||
s.get("name"), account, deny)
|
||||
return False
|
||||
try:
|
||||
submit_run(account, plugin, s.get("fields") or {})
|
||||
|
||||
@@ -29,7 +29,7 @@
|
||||
|
||||
<!-- 专属界面插件:插件 UI 直接内嵌在页面主体(同源共享会话 cookie,不再弹窗/外跳),日志保持在其下方可见 -->
|
||||
<div v-if="plugin.ui" class="ui-inline">
|
||||
<div class="ui-tip">账号密码、仓库编码、日期选项等个性化配置在界面内填写并自动保存在本机,下次打开自动回填;执行日志实时显示在下方日志区。</div>
|
||||
<div class="ui-tip">个性化配置项在界面内填写并自动保存在本机,下次打开自动回填;执行日志实时显示在下方日志区。</div>
|
||||
<iframe :key="plugin.id" :src="uiSrc" class="pui-frame" title="插件界面"></iframe>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -46,7 +46,8 @@
|
||||
</el-table-column>
|
||||
</el-table>
|
||||
|
||||
<el-dialog v-model="dlg" :title="editing ? '编辑定时任务' : '新建定时任务'" width="560px" align-center>
|
||||
<el-dialog v-model="dlg" :title="editing ? '编辑定时任务' : '新建定时任务'" width="min(780px, 94vw)" align-center
|
||||
class="sched-dlg">
|
||||
<el-form label-width="86px" class="dlg-form">
|
||||
<el-form-item label="任务名称">
|
||||
<el-input v-model="form.name" placeholder="如:每日考勤封存检查" maxlength="32" />
|
||||
@@ -58,15 +59,68 @@
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
<el-form-item label="触发时间">
|
||||
<div class="cron-row">
|
||||
<el-input v-model="form.cron" placeholder="标准 5 段 cron,如 0 8 * * *" class="cron-input">
|
||||
<template #prepend>cron</template>
|
||||
</el-input>
|
||||
<el-select v-model="preset" placeholder="快捷项" class="preset-sel" @change="onPreset">
|
||||
<el-option v-for="p in presets" :key="p.cron" :value="p.cron" :label="p.label" />
|
||||
</el-select>
|
||||
<div class="freq-zone">
|
||||
<el-radio-group v-model="freq" class="freq-tabs" size="small">
|
||||
<el-radio-button value="daily">每天</el-radio-button>
|
||||
<el-radio-button value="weekdays">工作日</el-radio-button>
|
||||
<el-radio-button value="weekly">每周</el-radio-button>
|
||||
<el-radio-button value="monthly">每月</el-radio-button>
|
||||
<el-radio-button value="hourly">每隔 N 小时</el-radio-button>
|
||||
<el-radio-button value="advanced">高级</el-radio-button>
|
||||
</el-radio-group>
|
||||
|
||||
<!-- 每天 / 工作日 -->
|
||||
<div v-if="freq === 'daily' || freq === 'weekdays'" class="freq-row">
|
||||
<span class="freq-desc">{{ freq === 'daily' ? '每天' : '周一至周五' }}</span>
|
||||
<el-time-select v-model="timeStr" start="00:00" step="00:05" end="23:55"
|
||||
placeholder="选择时间" class="time-sel" />
|
||||
</div>
|
||||
|
||||
<!-- 每周:选周几 + 时间 -->
|
||||
<div v-else-if="freq === 'weekly'" class="freq-row">
|
||||
<span class="freq-desc">每周</span>
|
||||
<el-checkbox-group v-model="weekdays" class="week-days">
|
||||
<el-checkbox-button v-for="d in weekDayOpts" :key="d.v" :value="d.v">{{ d.label }}</el-checkbox-button>
|
||||
</el-checkbox-group>
|
||||
<el-time-select v-model="timeStr" start="00:00" step="00:05" end="23:55"
|
||||
placeholder="选择时间" class="time-sel" />
|
||||
</div>
|
||||
|
||||
<!-- 每月:选几号 + 时间 -->
|
||||
<div v-else-if="freq === 'monthly'" class="freq-row">
|
||||
<span class="freq-desc">每月</span>
|
||||
<el-select v-model="monthDay" class="day-sel">
|
||||
<el-option v-for="d in 31" :key="d" :value="d" :label="`${d} 日`" />
|
||||
</el-select>
|
||||
<el-time-select v-model="timeStr" start="00:00" step="00:05" end="23:55"
|
||||
placeholder="选择时间" class="time-sel" />
|
||||
</div>
|
||||
|
||||
<!-- 每隔 N 小时 -->
|
||||
<div v-else-if="freq === 'hourly'" class="freq-row">
|
||||
<span class="freq-desc">每隔</span>
|
||||
<el-input-number v-model="hourlyStep" :min="1" :max="24" :controls="false" class="step-num" />
|
||||
<span class="freq-desc">小时执行一次(整点)</span>
|
||||
</div>
|
||||
|
||||
<!-- 高级:直接写 cron -->
|
||||
<div v-else class="freq-row col">
|
||||
<div class="cron-row">
|
||||
<el-input v-model="advancedCron" placeholder="标准 5 段 cron,如 0 8 * * *" class="cron-input">
|
||||
<template #prepend>cron</template>
|
||||
</el-input>
|
||||
<el-select v-model="preset" placeholder="快捷项" class="preset-sel" @change="onPreset">
|
||||
<el-option v-for="p in presets" :key="p.cron" :value="p.cron" :label="p.label" />
|
||||
</el-select>
|
||||
</div>
|
||||
<div class="cron-tip">5 段格式:分 时 日 月 周(0-59 0-23 1-31 1-12 0-6,0/7 均为周日)</div>
|
||||
</div>
|
||||
|
||||
<!-- 非高级模式下实时预览生成的 cron -->
|
||||
<div v-if="freq !== 'advanced'" class="cron-preview">
|
||||
表达式 <code>{{ form.cron }}</code>
|
||||
</div>
|
||||
</div>
|
||||
<div class="cron-tip">5 段格式:分 时 日 月 周(0-59 0-23 1-31 1-12 0-6,0/7 均为周日)</div>
|
||||
</el-form-item>
|
||||
<el-form-item v-if="pluginFields.length" label="执行参数">
|
||||
<div class="fields">
|
||||
@@ -101,7 +155,7 @@
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { computed, ref } from 'vue'
|
||||
import { computed, ref, watch } from 'vue'
|
||||
import { ElMessage, ElMessageBox } from 'element-plus'
|
||||
import { Clock, Plus } from '@element-plus/icons-vue'
|
||||
import { store } from '../store'
|
||||
@@ -113,6 +167,80 @@ const editing = ref(null)
|
||||
const saving = ref(false)
|
||||
const preset = ref('')
|
||||
|
||||
// ---- 闹钟式触发时间选择状态 ----
|
||||
// freq: daily=每天 weekdays=工作日 weekly=每周 monthly=每月 hourly=每隔N小时 advanced=高级cron
|
||||
const freq = ref('daily')
|
||||
const timeStr = ref('08:00')
|
||||
const weekdays = ref([1])
|
||||
const monthDay = ref(1)
|
||||
const hourlyStep = ref(1)
|
||||
const advancedCron = ref('')
|
||||
const weekDayOpts = [
|
||||
{ v: 1, label: '周一' }, { v: 2, label: '周二' }, { v: 3, label: '周三' },
|
||||
{ v: 4, label: '周四' }, { v: 5, label: '周五' }, { v: 6, label: '周六' }, { v: 7, label: '周日' },
|
||||
]
|
||||
|
||||
function pad2(n) { return String(n).padStart(2, '0') }
|
||||
|
||||
// 由可视化选择状态生成 cron 表达式(分钟/小时补齐 2 位,兼容解析)
|
||||
function buildCron() {
|
||||
const [h, m] = timeStr.value.split(':').map(Number)
|
||||
switch (freq.value) {
|
||||
case 'daily': return `${pad2(m)} ${pad2(h)} * * *`
|
||||
case 'weekdays': return `${pad2(m)} ${pad2(h)} * * 1-5`
|
||||
case 'weekly': {
|
||||
const ds = (weekdays.value.length ? weekdays.value : [1]).slice().sort((a, b) => a - b)
|
||||
return `${pad2(m)} ${pad2(h)} * * ${ds.join(',')}`
|
||||
}
|
||||
case 'monthly': return `${pad2(m)} ${pad2(h)} ${monthDay.value} * *`
|
||||
case 'hourly': return `0 */${hourlyStep.value || 1} * * *`
|
||||
default: return advancedCron.value.trim()
|
||||
}
|
||||
}
|
||||
|
||||
// 把已有 cron 反向解析为可视化选择状态;无法识别的回退到高级模式原样展示
|
||||
function cronToState(cron) {
|
||||
const s = String(cron || '').trim()
|
||||
const parts = s.split(/\s+/)
|
||||
const st = { freq: 'advanced', timeStr: '08:00', weekdays: [1], monthDay: 1, hourlyStep: 1, advancedCron: s }
|
||||
if (parts.length !== 5) return st
|
||||
const [m, h, dom, mon, dow] = parts
|
||||
// 每隔 N 小时:0 */N * * *
|
||||
if (m === '0' && /^\*\/\d+$/.test(h) && dom === '*' && mon === '*' && dow === '*') {
|
||||
const step = parseInt(h.split('/')[1], 10)
|
||||
if (step >= 1 && step <= 24) return { ...st, freq: 'hourly', hourlyStep: step }
|
||||
}
|
||||
const num = (x) => (/^\d+$/.test(x) ? parseInt(x, 10) : null)
|
||||
const mn = num(m), hr = num(h)
|
||||
if (mn == null || hr == null || mn < 0 || mn > 59 || hr < 0 || hr > 23) return st
|
||||
const hhmm = pad2(hr) + ':' + pad2(mn)
|
||||
if (dom === '*' && mon === '*') {
|
||||
if (dow === '*') return { ...st, freq: 'daily', timeStr: hhmm }
|
||||
if (dow === '1-5') return { ...st, freq: 'weekdays', timeStr: hhmm }
|
||||
if (/^[0-7](,[0-7])*$/.test(dow)) {
|
||||
const ds = [...new Set(dow.split(',').map(Number).map((x) => (x === 0 ? 7 : x)))].sort((a, b) => a - b)
|
||||
return { ...st, freq: 'weekly', timeStr: hhmm, weekdays: ds }
|
||||
}
|
||||
return st
|
||||
}
|
||||
if (dow === '*' && mon === '*') {
|
||||
const dd = num(dom)
|
||||
if (dd != null && dd >= 1 && dd <= 31) return { ...st, freq: 'monthly', timeStr: hhmm, monthDay: dd }
|
||||
}
|
||||
return st
|
||||
}
|
||||
|
||||
// 同步状态 → form.cron(打开弹窗时立即生成一次)
|
||||
function syncCron() {
|
||||
if (freq.value !== 'advanced') form.value.cron = buildCron()
|
||||
}
|
||||
|
||||
// 选择状态变化时自动重写 form.cron
|
||||
watch([freq, timeStr, weekdays, monthDay, hourlyStep], syncCron)
|
||||
watch(advancedCron, (v) => {
|
||||
if (freq.value === 'advanced') form.value.cron = v.trim()
|
||||
})
|
||||
|
||||
const presets = [
|
||||
{ label: '每天 08:00', cron: '0 8 * * *' },
|
||||
{ label: '每天 12:00', cron: '0 12 * * *' },
|
||||
@@ -144,7 +272,7 @@ function onPluginChange(id) {
|
||||
}
|
||||
|
||||
function onPreset(cron) {
|
||||
form.value.cron = cron
|
||||
advancedCron.value = cron
|
||||
preset.value = ''
|
||||
}
|
||||
|
||||
@@ -160,6 +288,14 @@ async function load() {
|
||||
function openCreate() {
|
||||
editing.value = null
|
||||
form.value = { name: '', plugin_id: '', cron: '', enabled: true, fields: {} }
|
||||
// 默认:每天 08:00
|
||||
freq.value = 'daily'
|
||||
timeStr.value = '08:00'
|
||||
weekdays.value = [1]
|
||||
monthDay.value = 1
|
||||
hourlyStep.value = 1
|
||||
advancedCron.value = ''
|
||||
syncCron()
|
||||
dlg.value = true
|
||||
}
|
||||
|
||||
@@ -173,6 +309,15 @@ function openEdit(row) {
|
||||
fields: buildFields(store.plugins.find((x) => x.id === row.plugin_id)),
|
||||
}
|
||||
Object.assign(form.value.fields, row.fields || {})
|
||||
// 把已有 cron 解析回可视化选择状态
|
||||
const st = cronToState(row.cron || '')
|
||||
freq.value = st.freq
|
||||
timeStr.value = st.timeStr
|
||||
weekdays.value = st.weekdays
|
||||
monthDay.value = st.monthDay
|
||||
hourlyStep.value = st.hourlyStep
|
||||
advancedCron.value = st.advancedCron
|
||||
syncCron()
|
||||
dlg.value = true
|
||||
}
|
||||
|
||||
@@ -331,13 +476,80 @@ load()
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.fields {
|
||||
/* ---- 闹钟式触发时间选择 ---- */
|
||||
.freq-zone {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 10px;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.freq-tabs {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.freq-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
flex-wrap: wrap;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.freq-row.col {
|
||||
flex-direction: column;
|
||||
align-items: stretch;
|
||||
}
|
||||
|
||||
.freq-desc {
|
||||
font-size: 13px;
|
||||
color: var(--text-sub);
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.time-sel {
|
||||
width: 130px;
|
||||
}
|
||||
|
||||
.day-sel {
|
||||
width: 110px;
|
||||
}
|
||||
|
||||
.step-num {
|
||||
width: 90px;
|
||||
}
|
||||
|
||||
.week-days {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.cron-preview {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
font-size: 12px;
|
||||
color: var(--text-faint);
|
||||
}
|
||||
|
||||
.cron-preview code {
|
||||
padding: 1px 8px;
|
||||
border-radius: 6px;
|
||||
background: var(--surface-2, #f7f8fa);
|
||||
border: 1px solid var(--border);
|
||||
font-size: 12px;
|
||||
color: var(--text);
|
||||
}
|
||||
|
||||
.fields {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
|
||||
gap: 10px 14px;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.field {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
@@ -358,4 +570,14 @@ load()
|
||||
.w-full {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
/* 定时任务弹窗:内容超高时弹窗内滚动,避免配置多的插件把弹窗顶出屏幕 */
|
||||
:deep(.sched-dlg .el-dialog) {
|
||||
max-height: 90vh;
|
||||
}
|
||||
|
||||
:deep(.sched-dlg .el-dialog__body) {
|
||||
max-height: 62vh;
|
||||
overflow-y: auto;
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
; 37du 自动化工作台 - Inno Setup 安装脚本 (Inno Setup 7)
|
||||
; 37du 自动化工作台 - Inno Setup 安装脚本 (Inno Setup 7)
|
||||
; 编译: "C:\Program Files\Inno Setup 7\ISCC.exe" webhost\tools\install.iss
|
||||
; 打包内容: 主程序 37du-host.exe + 插件执行壳 37du-host-runner.exe + .env 默认配置
|
||||
; .env 与 webhost/.env 同源(控制面/平台共享配置):仅首次安装写入(onlyifdoesntexist),
|
||||
; 升级不覆盖机器已有 .env;不含 37du-host-console.exe(调试版)、plugins/(登录后自下载)
|
||||
|
||||
#define MyAppName "37du 自动化工作台"
|
||||
#define MyAppVersion "1.1.8"
|
||||
#define MyAppVersion "1.2.0"
|
||||
#define MyAppExeName "37du-host.exe"
|
||||
|
||||
[Setup]
|
||||
|
||||
@@ -1 +1 @@
|
||||
1.1.8
|
||||
1.2.0
|
||||
Reference in New Issue
Block a user