refactor: 整体迁移控制面至MySQL + 替换UI框架为Element Plus

1. 移除naive-ui依赖,迁移前端至Element Plus
2. 重构后端数据库层,切换为MySQL替代SQLite
3. 调整项目部署架构,停止exe打包改为源码部署
4. 新增设备上报接口与相关数据库模型
5. 优化配置路径与SQL语法,替换为MySQL占位符格式
6. 调整站点名称与文案,统一为「37du 插件管理平台」
7. 新增SQLite到MySQL迁移脚本
This commit is contained in:
2026-09-16 15:58:45 +08:00
parent 4363116e31
commit 84d3e103ec
54 changed files with 5542 additions and 1890 deletions
+86 -70
View File
@@ -38,12 +38,12 @@ def admin_accounts(x_admin_token: str = Header(default="", alias="X-Admin-Token"
"FROM accounts ORDER BY id")]
for a in rows:
a["plugins"] = [dict(r)["plugin_id"] for r in conn.execute(
"SELECT plugin_id FROM account_plugins WHERE account = ?", (a["account"],))]
"SELECT plugin_id FROM account_plugins WHERE account = %s", (a["account"],))]
a["grants"] = [dict(r) for r in conn.execute(
"SELECT plugin_id, can_download, can_run FROM plugin_grants WHERE account = ?",
"SELECT plugin_id, can_download, can_run FROM account_plugins WHERE account = %s",
(a["account"],))]
a["platforms"] = [dict(r)["platform_id"] for r in conn.execute(
"SELECT platform_id FROM account_platforms WHERE account = ?", (a["account"],))]
"SELECT platform_id FROM account_platforms WHERE account = %s", (a["account"],))]
return {"accounts": rows}
@@ -57,13 +57,13 @@ def admin_account_create(a: schemas.AccountCreateIn,
if not account or not a.password:
raise HTTPException(400, "account 与 password 必填")
with _db() as conn:
exists = conn.execute("SELECT 1 FROM accounts WHERE account = ?", (account,)).fetchone()
exists = conn.execute("SELECT 1 FROM accounts WHERE account = %s", (account,)).fetchone()
if exists:
raise HTTPException(400, f"账号 {account} 已存在")
_hex, _salt = _hash_password(a.password)
with _db() as conn:
conn.execute("INSERT INTO accounts(account, password_hash, salt, is_admin, dept, nickname, "
"created_at) VALUES (?, ?, ?, ?, ?, ?, ?)",
"created_at) VALUES (%s, %s, %s, %s, %s, %s, %s)",
(account, _hex, _salt, int(a.is_admin), (a.dept or "").strip(),
(a.nickname or "").strip(), _now()))
conn.commit()
@@ -81,26 +81,26 @@ def admin_account_update(a: schemas.AccountUpdateIn,
if not account:
raise HTTPException(400, "account 必填")
with _db() as conn:
if not conn.execute("SELECT 1 FROM accounts WHERE account = ?", (account,)).fetchone():
if not conn.execute("SELECT 1 FROM accounts WHERE account = %s", (account,)).fetchone():
raise HTTPException(400, f"账号 {account} 不存在")
if a.dept is not None:
conn.execute("UPDATE accounts SET dept = ? WHERE account = ?",
conn.execute("UPDATE accounts SET dept = %s WHERE account = %s",
((a.dept or "").strip(), account))
if a.nickname is not None:
conn.execute("UPDATE accounts SET nickname = ? WHERE account = ?",
conn.execute("UPDATE accounts SET nickname = %s WHERE account = %s",
((a.nickname or "").strip(), account))
if a.is_admin is not None:
# 禁止撤销自己的管理员身份,避免把自己锁在门外
if a.is_admin:
conn.execute("UPDATE accounts SET is_admin = 1 WHERE account = ?", (account,))
conn.execute("UPDATE accounts SET is_admin = 1 WHERE account = %s", (account,))
else:
conn.execute("UPDATE accounts SET is_admin = 0 WHERE account = ? AND account <> ?",
conn.execute("UPDATE accounts SET is_admin = 0 WHERE account = %s AND account <> %s",
(account, login))
if a.status is not None:
# 禁止停用自己,避免把自己锁在门外
if not a.status and account == login:
raise HTTPException(400, "不能停用当前登录的账号")
conn.execute("UPDATE accounts SET status = ? WHERE account = ?",
conn.execute("UPDATE accounts SET status = %s WHERE account = %s",
(int(bool(a.status)), account))
conn.commit()
return {"ok": True, "account": account}
@@ -116,10 +116,10 @@ def admin_account_reset(r: schemas.AccountResetIn,
if not account or not r.new_password:
raise HTTPException(400, "account 与新密码必填")
with _db() as conn:
if not conn.execute("SELECT 1 FROM accounts WHERE account = ?", (account,)).fetchone():
if not conn.execute("SELECT 1 FROM accounts WHERE account = %s", (account,)).fetchone():
raise HTTPException(400, f"账号 {account} 不存在")
_hex, _salt = _hash_password(r.new_password)
conn.execute("UPDATE accounts SET password_hash = ?, salt = ? WHERE account = ?",
conn.execute("UPDATE accounts SET password_hash = %s, salt = %s WHERE account = %s",
(_hex, _salt, account))
conn.commit()
return {"ok": True, "account": account}
@@ -137,10 +137,10 @@ def admin_account_delete(d: schemas.AccountDelIn,
if account == login:
raise HTTPException(400, "不能删除当前登录的账号")
with _db() as conn:
if not conn.execute("SELECT 1 FROM accounts WHERE account = ?", (account,)).fetchone():
if not conn.execute("SELECT 1 FROM accounts WHERE account = %s", (account,)).fetchone():
raise HTTPException(400, f"账号 {account} 不存在")
conn.execute("DELETE FROM accounts WHERE account = ?", (account,))
conn.execute("DELETE FROM account_plugins WHERE account = ?", (account,))
# account_plugins / account_platforms 由外键 ON DELETE CASCADE 级联清理
conn.execute("DELETE FROM accounts WHERE account = %s", (account,))
conn.commit()
return {"ok": True, "account": account}
@@ -172,9 +172,9 @@ def admin_avatar_upload(file: UploadFile = File(...),
if not content or len(content) > 2 * 1024 * 1024:
raise HTTPException(400, "头像文件为空或超过 2MB")
with _db() as conn:
if not conn.execute("SELECT 1 FROM accounts WHERE account = ?", (account,)).fetchone():
if not conn.execute("SELECT 1 FROM accounts WHERE account = %s", (account,)).fetchone():
raise HTTPException(400, f"账号 {account} 不存在")
old = conn.execute("SELECT avatar FROM accounts WHERE account = ?", (account,)).fetchone()
old = conn.execute("SELECT avatar FROM accounts WHERE account = %s", (account,)).fetchone()
old_name = (old["avatar"] if old else "") or ""
config.AVATAR_DIR.mkdir(parents=True, exist_ok=True)
fname = f"{account}{ext}"
@@ -185,7 +185,7 @@ def admin_avatar_upload(file: UploadFile = File(...),
except OSError:
pass
with _db() as conn:
conn.execute("UPDATE accounts SET avatar = ? WHERE account = ?", (fname, account))
conn.execute("UPDATE accounts SET avatar = %s WHERE account = %s", (fname, account))
conn.commit()
return {"ok": True, "account": account, "avatar": fname}
@@ -194,7 +194,7 @@ def admin_avatar_upload(file: UploadFile = File(...),
def admin_avatar_get(account: str) -> FileResponse:
"""读取账号头像(前端 img 直接引用;未设置返回 404)。"""
with _db() as conn:
row = conn.execute("SELECT avatar FROM accounts WHERE account = ?", (account,)).fetchone()
row = conn.execute("SELECT avatar FROM accounts WHERE account = %s", (account,)).fetchone()
if not row or not row["avatar"]:
raise HTTPException(404, "未设置头像")
path = config.AVATAR_DIR / row["avatar"]
@@ -208,7 +208,11 @@ def admin_avatar_get(account: str) -> FileResponse:
def admin_grant(g: schemas.GrantIn,
x_admin_token: str = Header(default="", alias="X-Admin-Token"),
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
"""授予/撤销某账号对某插件的权限。granted=True 授,False 撤;同时维护插件级授权表。"""
"""授予/撤销某账号对某插件的权限。granted=True 授,False 撤。
MySQL 版合并表:权限位(can_download/can_run)即存在 account_plugins 本身,
不再有独立 plugin_grants 表;撤销即删除 account_plugins 行。
"""
_require_admin(x_admin_token, x_api_token)
account = g.account.strip()
plugin_id = g.plugin_id.strip()
@@ -216,21 +220,18 @@ def admin_grant(g: schemas.GrantIn,
raise HTTPException(400, "account 与 plugin_id 不能为空")
with _db() as conn:
if g.granted:
if not conn.execute("SELECT 1 FROM accounts WHERE account = ?", (account,)).fetchone():
if not conn.execute("SELECT 1 FROM accounts WHERE account = %s", (account,)).fetchone():
raise HTTPException(400, f"账号 {account} 不存在,请先建号")
if not conn.execute("SELECT 1 FROM plugins WHERE id = %s", (plugin_id,)).fetchone():
raise HTTPException(400, f"插件 {plugin_id} 不存在,请先上传发布")
conn.execute(
"INSERT OR IGNORE INTO account_plugins(account, plugin_id) VALUES (?, ?)",
(account, plugin_id))
conn.execute(
"INSERT INTO plugin_grants(account, plugin_id, can_download, can_run) "
"VALUES (?, ?, ?, ?) "
"ON CONFLICT(account, plugin_id) DO UPDATE SET "
"can_download = excluded.can_download, can_run = excluded.can_run",
"INSERT INTO account_plugins(account, plugin_id, can_download, can_run) "
"VALUES (%s, %s, %s, %s) "
"ON DUPLICATE KEY UPDATE can_download = VALUES(can_download), "
"can_run = VALUES(can_run)",
(account, plugin_id, int(g.can_download), int(g.can_run)))
else:
conn.execute("DELETE FROM account_plugins WHERE account = ? AND plugin_id = ?",
(account, plugin_id))
conn.execute("DELETE FROM plugin_grants WHERE account = ? AND plugin_id = ?",
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,
@@ -250,13 +251,13 @@ def admin_platform_grant(g: schemas.PlatformGrantIn,
raise HTTPException(400, "account 与 platform_id 不能为空")
with _db() as conn:
if g.granted:
if not conn.execute("SELECT 1 FROM accounts WHERE account = ?", (account,)).fetchone():
if not conn.execute("SELECT 1 FROM accounts WHERE account = %s", (account,)).fetchone():
raise HTTPException(400, f"账号 {account} 不存在,请先建号")
conn.execute(
"INSERT OR IGNORE INTO account_platforms(account, platform_id) VALUES (?, ?)",
"INSERT IGNORE INTO account_platforms(account, platform_id) VALUES (%s, %s)",
(account, platform_id))
else:
conn.execute("DELETE FROM account_platforms WHERE account = ? AND platform_id = ?",
conn.execute("DELETE FROM account_platforms WHERE account = %s AND platform_id = %s",
(account, platform_id))
conn.commit()
return {"ok": True, "account": account, "platform_id": platform_id, "granted": g.granted}
@@ -301,11 +302,11 @@ async def admin_upload_plugin(upload: UploadFile = File(...),
with _db() as conn:
conn.execute(
"INSERT INTO plugins(id, name, latest_version, description, category, icon, manifest) "
"VALUES (?, ?, ?, ?, ?, ?, ?) ON CONFLICT(id) DO UPDATE SET "
"name = excluded.name, manifest = excluded.manifest"
+ (", description = excluded.description" if manifest else "")
+ (", category = excluded.category" if manifest else "")
+ (", icon = excluded.icon" if manifest else ""),
"VALUES (%s, %s, %s, %s, %s, %s, %s) ON DUPLICATE KEY UPDATE "
"name = VALUES(name), manifest = VALUES(manifest)"
+ (", description = VALUES(description)" if manifest else "")
+ (", category = VALUES(category)" if manifest else "")
+ (", icon = VALUES(icon)" if manifest else ""),
(plugin_id, name, version,
(manifest or {}).get("description", ""),
(manifest or {}).get("category", ""),
@@ -313,12 +314,12 @@ async def admin_upload_plugin(upload: UploadFile = File(...),
manifest_json))
conn.execute(
"INSERT INTO plugin_versions(plugin_id, version, filename, uploaded_at, sha256) "
"VALUES (?, ?, ?, ?, ?) ON CONFLICT(plugin_id, version) DO UPDATE SET "
"filename = excluded.filename, uploaded_at = excluded.uploaded_at, sha256 = excluded.sha256",
"VALUES (%s, %s, %s, %s, %s) ON DUPLICATE KEY UPDATE "
"filename = VALUES(filename), uploaded_at = VALUES(uploaded_at), sha256 = VALUES(sha256)",
(plugin_id, version, filename, _now(), pkg_sha256))
cur = conn.execute("SELECT latest_version FROM plugins WHERE id = ?", (plugin_id,))
cur = conn.execute("SELECT latest_version FROM plugins WHERE id = %s", (plugin_id,))
if _version_key(cur.fetchone()["latest_version"]) < _version_key(version):
conn.execute("UPDATE plugins SET latest_version = ? WHERE id = ?", (version, plugin_id))
conn.execute("UPDATE plugins SET latest_version = %s WHERE id = %s", (version, plugin_id))
stale_files = _prune_versions(conn, plugin_id)
conn.commit()
for fn in stale_files: # 超出保留数的旧版本:清 DB 记录 + 清磁盘包
@@ -339,13 +340,14 @@ def admin_plugin_delete(d: schemas.PluginDelIn,
if not plugin_id:
raise HTTPException(400, "plugin_id 必填")
with _db() as conn:
if not conn.execute("SELECT 1 FROM plugins WHERE id = ?", (plugin_id,)).fetchone():
if not conn.execute("SELECT 1 FROM plugins WHERE id = %s", (plugin_id,)).fetchone():
raise HTTPException(400, f"插件 {plugin_id} 不存在")
files = [dict(r)["filename"] for r in conn.execute(
"SELECT filename FROM plugin_versions WHERE plugin_id = ?", (plugin_id,))]
conn.execute("DELETE FROM plugin_versions WHERE plugin_id = ?", (plugin_id,))
conn.execute("DELETE FROM plugins WHERE id = ?", (plugin_id,))
conn.execute("DELETE FROM account_plugins WHERE plugin_id = ?", (plugin_id,))
"SELECT filename FROM plugin_versions WHERE plugin_id = %s", (plugin_id,))]
# 外键 CASCADE 会连带清理 plugin_versions / account_plugins,显式删除仅作兜底保序
conn.execute("DELETE FROM account_plugins WHERE plugin_id = %s", (plugin_id,))
conn.execute("DELETE FROM plugin_versions WHERE plugin_id = %s", (plugin_id,))
conn.execute("DELETE FROM plugins WHERE id = %s", (plugin_id,))
conn.commit()
for fn in files:
try:
@@ -373,19 +375,19 @@ def admin_plugin_patch(d: schemas.PluginPatchIn,
fields = []
vals = []
if d.name is not None and d.name.strip():
fields.append("name = ?"); vals.append(d.name.strip())
fields.append("name = %s"); vals.append(d.name.strip())
if d.description:
fields.append("description = ?"); vals.append(d.description.strip())
fields.append("description = %s"); vals.append(d.description.strip())
if d.category:
fields.append("category = ?"); vals.append(d.category.strip())
fields.append("category = %s"); vals.append(d.category.strip())
if d.icon:
fields.append("icon = ?"); vals.append(d.icon.strip())
fields.append("icon = %s"); vals.append(d.icon.strip())
if d.status in ("published", "disabled", "revoked"):
fields.append("status = ?"); vals.append(d.status)
fields.append("status = %s"); vals.append(d.status)
# 强制更新三态:成对开启 / clear_force 清除 / 仅给其一报错
if d.force_min_version and d.force_deadline:
fields.append("force_min_version = ?"); vals.append(d.force_min_version.strip())
fields.append("force_deadline = ?"); vals.append(d.force_deadline.strip())
fields.append("force_min_version = %s"); vals.append(d.force_min_version.strip())
fields.append("force_deadline = %s"); vals.append(d.force_deadline.strip())
elif (d.force_min_version or d.force_deadline) and not d.clear_force:
raise HTTPException(400, "强制更新需同时提供 force_min_version 与 force_deadline")
elif d.clear_force:
@@ -395,9 +397,9 @@ def admin_plugin_patch(d: schemas.PluginPatchIn,
return {"ok": True} # 无更新项
vals.append(pid)
with _db() as conn:
if not conn.execute("SELECT 1 FROM plugins WHERE id = ?", (pid,)).fetchone():
if not conn.execute("SELECT 1 FROM plugins WHERE id = %s", (pid,)).fetchone():
raise HTTPException(400, f"插件 {pid} 不存在")
conn.execute(f"UPDATE plugins SET {', '.join(fields)} WHERE id = ?", vals)
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])))
@@ -424,27 +426,27 @@ def admin_overview(x_admin_token: str = Header(default="", alias="X-Admin-Token"
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 = ? ORDER BY version", (p["id"],))]
"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 = ?", (p["id"],))]
"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 plugin_grants "
"WHERE plugin_id = ?", (p["id"],))}
"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 = ?", (a["account"],))]
"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 = ?", (a["account"],))]
"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 plugin_grants "
"WHERE account = ?", (a["account"],))}
"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}
@@ -475,11 +477,11 @@ def admin_stats(x_admin_token: str = Header(default="", alias="X-Admin-Token"),
# 近 14 天运行趋势(按日:触发次数 / 成功 / 失败)
trend_rows = conn.execute(
"SELECT substr(at,1,10) AS day, "
"SELECT LEFT(at,10) AS day, "
" SUM(CASE WHEN status = 'start' THEN 1 ELSE 0 END) AS runs, "
" SUM(CASE WHEN status IN ('done','success') THEN 1 ELSE 0 END) AS success, "
" SUM(CASE WHEN status IN ('error','failed') THEN 1 ELSE 0 END) AS failed "
"FROM runtime_reports WHERE at >= date('now','-13 days') GROUP BY day ORDER BY day"
"FROM runtime_reports WHERE at >= CURDATE() - INTERVAL 13 DAY GROUP BY day ORDER BY day"
).fetchall()
trend_map = {r["day"]: r for r in trend_rows}
trend = []
@@ -553,7 +555,7 @@ def admin_audit(limit: int = Query(default=200, ge=1, le=1000),
"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 ?", (limit,))]
"ORDER BY id DESC LIMIT %s", (limit,))]
for r in rows:
r["nickname"] = nick.get(r["account"], "")
return {"auditlogs": rows}
@@ -570,12 +572,26 @@ def admin_reports(limit: int = Query(default=200, ge=1, le=1000),
"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 ?", (limit,))]
"FROM runtime_reports ORDER BY id DESC LIMIT %s", (limit,))]
for r in rows:
r["nickname"] = nick.get(r["account"], "")
return {"reports": rows}
@router.get("/api/admin/devices")
def admin_devices(limit: int = Query(default=200, ge=1, le=1000),
x_admin_token: str = Header(default="", alias="X-Admin-Token"),
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
"""执行机设备列表(按最近心跳倒序):环境信息 + Chrome 检测结果。"""
_require_admin(x_admin_token, x_api_token)
with _db() as conn:
rows = [dict(r) for r in conn.execute(
"SELECT device_id, account, hostname, os, ip, chrome_installed, chrome_version, "
" chrome_ok, last_seen, status, created_at, updated_at "
"FROM devices ORDER BY last_seen DESC LIMIT %s", (limit,))]
return {"devices": rows}
@router.post("/api/admin/shell-release")
async def admin_shell_release(upload: UploadFile = File(...),
version: str = Query(...),
+5 -5
View File
@@ -42,7 +42,7 @@ def admin_me(x_admin_token: str = Header(default="", alias="X-Admin-Token"),
return {"account": "", "is_admin": False, "dept": "", "nickname": "", "avatar": ""}
with _db() as conn:
row = conn.execute(
"SELECT is_admin, dept, nickname, status, avatar FROM accounts WHERE account = ?",
"SELECT is_admin, dept, nickname, status, avatar FROM accounts WHERE account = %s",
(account,)).fetchone()
# 账号停用:视为未登录(执行机/控制面前端据此自动登出)
if not row or not row["status"]:
@@ -74,7 +74,7 @@ def admin_auth(a: schemas.AuthIn,
with _db() as conn:
row = conn.execute(
"SELECT password_hash, salt, is_admin, dept, nickname, must_change_pwd, status, avatar "
"FROM accounts WHERE account = ?",
"FROM accounts WHERE account = %s",
(account,)).fetchone()
if not row or not _verify_password(a.password, row["salt"], row["password_hash"]):
_auth_fail(account)
@@ -105,7 +105,7 @@ def admin_password(p: schemas.PwdIn,
raise HTTPException(403, "只能修改自己的密码")
with _db() as conn:
row = conn.execute(
"SELECT password_hash, salt, must_change_pwd FROM accounts WHERE account = ?",
"SELECT password_hash, salt, must_change_pwd FROM accounts WHERE account = %s",
(login,)).fetchone()
if not row:
raise HTTPException(401, "账号不存在")
@@ -115,8 +115,8 @@ def admin_password(p: schemas.PwdIn,
raise HTTPException(401, "原密码错误")
_hex, _salt = _hash_password(p.new_password)
with _db() as conn:
conn.execute("UPDATE accounts SET password_hash = ?, salt = ?, must_change_pwd = 0 "
"WHERE account = ?", (_hex, _salt, login))
conn.execute("UPDATE accounts SET password_hash = %s, salt = %s, must_change_pwd = 0 "
"WHERE account = %s", (_hex, _salt, login))
conn.commit()
return {"ok": True, "account": login}
+3 -3
View File
@@ -38,14 +38,14 @@ def admin_dingtalk_auth(d: schemas.DingTalkIn,
ding_uid = (d.dingtalk_uid or "").strip()
with _db() as conn:
row = conn.execute(
"SELECT account, is_admin, must_change_pwd, nickname, status FROM accounts WHERE account = ?",
"SELECT account, is_admin, must_change_pwd, nickname, status FROM accounts WHERE account = %s",
(account,)).fetchone()
if row:
# 已存在:顺带同步昵称(钉钉名),但不改密码/权限;原有 must_change_pwd 保留
if not row["status"]:
raise HTTPException(403, "账号已停用,请联系管理员")
if nickname and nickname != (row["nickname"] or ""):
conn.execute("UPDATE accounts SET nickname = ? WHERE account = ?",
conn.execute("UPDATE accounts SET nickname = %s WHERE account = %s",
(nickname, account))
conn.commit()
return {"ok": True, "account": account,
@@ -60,7 +60,7 @@ def admin_dingtalk_auth(d: schemas.DingTalkIn,
_hex, _salt = _hash_password(pwd)
conn.execute(
"INSERT INTO accounts(account, password_hash, salt, is_admin, dept, nickname, "
"dingtalk_uid, must_change_pwd) VALUES (?, ?, ?, 0, '', ?, ?, 1)",
"dingtalk_uid, must_change_pwd) VALUES (%s, %s, %s, 0, '', %s, %s, 1)",
(account, _hex, _salt, nickname, ding_uid))
conn.commit()
return {"ok": True, "account": account, "nickname": nickname,
+1 -1
View File
@@ -11,4 +11,4 @@ router = APIRouter()
@router.get("/health")
def health() -> dict:
return {"ok": True, "db": config.DB_PATH.name}
return {"ok": True, "db": "mysql", "host": config.MYSQL_HOST, "database": config.MYSQL_DB}
+39 -9
View File
@@ -22,7 +22,7 @@ router = APIRouter()
def _account_disabled(acct: str) -> bool:
"""账号是否已停用(停用后机器侧一律不给插件/授权)。"""
with _db() as conn:
row = conn.execute("SELECT status FROM accounts WHERE account = ?", (acct,)).fetchone()
row = conn.execute("SELECT status FROM accounts WHERE account = %s", (acct,)).fetchone()
return bool(row) and not bool(row["status"])
@@ -49,7 +49,7 @@ def plugins(account: str = Query(default="", description="账号(旧底座按此
SELECT p.id, p.name, p.latest_version AS version
FROM plugins p
JOIN account_plugins ap ON ap.plugin_id = p.id
WHERE ap.account = ?
WHERE ap.account = %s
ORDER BY p.id
""",
(acct,),
@@ -72,7 +72,7 @@ def platforms_allowed(account: str = Query(default="", description="账号(旧
return {"account": acct, "allowed": []}
with _db() as conn:
rows = conn.execute(
"SELECT platform_id FROM account_platforms WHERE account = ? ORDER BY platform_id",
"SELECT platform_id FROM account_platforms WHERE account = %s ORDER BY platform_id",
(acct,),
).fetchall()
return {"account": acct, "allowed": [dict(r)["platform_id"] for r in rows]}
@@ -112,7 +112,7 @@ def pkg(plugin_id: str, version: str,
_check_token(x_api_token)
with _db() as conn:
row = conn.execute(
"SELECT filename FROM plugin_versions WHERE plugin_id = ? AND version = ?",
"SELECT filename FROM plugin_versions WHERE plugin_id = %s AND version = %s",
(plugin_id, version),
).fetchone()
if not row:
@@ -147,9 +147,9 @@ def me_license(account: str = Query(...), device: str = Query(default=""),
rows = conn.execute(
"""
SELECT g.plugin_id, g.can_download, g.can_run, p.name, p.status, p.latest_version
FROM plugin_grants g
FROM account_plugins g
JOIN plugins p ON p.id = g.plugin_id
WHERE g.account = ?
WHERE g.account = %s
""",
(account.strip(),),
).fetchall()
@@ -199,10 +199,10 @@ def download_ticket(plugin_id: str, version: str,
raise HTTPException(400, "account 不能为空")
with _db() as conn:
row = conn.execute(
"SELECT can_download FROM plugin_grants WHERE account = ? AND plugin_id = ?",
"SELECT can_download FROM account_plugins WHERE account = %s AND plugin_id = %s",
(account.strip(), plugin_id)).fetchone()
ver = conn.execute(
"SELECT filename, sha256 FROM plugin_versions WHERE plugin_id = ? AND version = ?",
"SELECT filename, sha256 FROM plugin_versions WHERE plugin_id = %s AND version = %s",
(plugin_id, version)).fetchone()
if not ver:
raise HTTPException(404, f"未找到插件包 {plugin_id}@{version}")
@@ -243,12 +243,42 @@ def runtime_report(b: schemas.RuntimeReportIn,
with _db() as conn:
conn.execute(
"INSERT INTO runtime_reports(account, device_id, plugin_id, version, status, msg, duration_sec, at) "
"VALUES (?,?,?,?,?,?,?,?)",
"VALUES (%s,%s,%s,%s,%s,%s,%s,%s)",
(b.account, b.device_id, b.plugin_id, b.version, b.status, b.msg, b.duration_sec, _now()))
conn.commit()
return {"ok": True}
@router.post("/api/device/report")
def device_report(b: schemas.DeviceReportIn,
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
"""执行机心跳/环境上报(含 Chrome 检测结果):按 device_id 幂等 upsert 设备记录。
供壳(执行机底座)启动/定时上报本机环境;last_seen 与 status 由中心机统一维护
在线态(status 由调用方按心跳状态传,离线清理逻辑在管理端查询侧)。
"""
_check_token(x_api_token)
device_id = (b.device_id or "").strip()
if not device_id:
raise HTTPException(400, "device_id 不能为空")
with _db() as conn:
conn.execute(
"INSERT INTO devices(device_id, account, hostname, os, ip, "
"chrome_installed, chrome_version, chrome_ok, last_seen, status) "
"VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s) "
"ON DUPLICATE KEY UPDATE "
"account = VALUES(account), hostname = VALUES(hostname), os = VALUES(os), "
"ip = VALUES(ip), chrome_installed = VALUES(chrome_installed), "
"chrome_version = VALUES(chrome_version), chrome_ok = VALUES(chrome_ok), "
"last_seen = VALUES(last_seen), status = VALUES(status)",
(device_id, (b.account or "").strip(), (b.hostname or "").strip(),
(b.os or "").strip(), (b.ip or "").strip(),
int(bool(b.chrome_installed)), (b.chrome_version or "").strip(),
int(bool(b.chrome_ok)), _now(), int(bool(b.status))))
conn.commit()
return {"ok": True, "device_id": device_id}
# ==================== 壳子(执行机主程序)自动更新 ====================
# shell/version.json 约定:{"version": "1.0.0", "filename": "setup-37du-host-1.0.0.exe",
# "sha256": "<可选,安装包校验值>", "notes": "<可选,更新说明>"}