feat: 新增账号状态管理、头像功能与报表工具,完善账号系统

新增账号状态字段与停用校验,支持账号头像上传管理,新增物料收发汇总表合并工具,优化银行卡检查脚本,新增ERP登录复用模块,重构账号数据库迁移与管理接口
This commit is contained in:
2026-09-16 00:25:13 +08:00
parent 1e533dd1b3
commit 4363116e31
27 changed files with 2533 additions and 268 deletions
+75 -7
View File
@@ -8,11 +8,13 @@ from __future__ import annotations
import hashlib
import json
from datetime import datetime, timedelta
from pathlib import Path
from fastapi import APIRouter, File, Header, HTTPException, Query, UploadFile
from fastapi.responses import FileResponse
from controlplane import config, schemas
from controlplane.core.auth import _require_admin
from controlplane.core.auth import _require_admin, _resolve_login
from controlplane.core.crypto import _hash_password
from controlplane.core.db import _audit, _db, _now
from controlplane.core.pkgutil import (
@@ -31,8 +33,9 @@ def admin_accounts(x_admin_token: str = Header(default="", alias="X-Admin-Token"
_require_admin(x_admin_token, x_api_token)
with _db() as conn:
rows = [dict(r) for r in conn.execute(
"SELECT account, is_admin, dept, nickname, dingtalk_uid, must_change_pwd "
"FROM accounts ORDER BY account")]
"SELECT id, account, is_admin, dept, nickname, dingtalk_uid, must_change_pwd, "
" avatar, status, created_at "
"FROM accounts ORDER BY id")]
for a in rows:
a["plugins"] = [dict(r)["plugin_id"] for r in conn.execute(
"SELECT plugin_id FROM account_plugins WHERE account = ?", (a["account"],))]
@@ -59,10 +62,10 @@ def admin_account_create(a: schemas.AccountCreateIn,
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) "
"VALUES (?, ?, ?, ?, ?, ?)",
conn.execute("INSERT INTO accounts(account, password_hash, salt, is_admin, dept, nickname, "
"created_at) VALUES (?, ?, ?, ?, ?, ?, ?)",
(account, _hex, _salt, int(a.is_admin), (a.dept or "").strip(),
(a.nickname or "").strip()))
(a.nickname or "").strip(), _now()))
conn.commit()
return {"ok": True, "account": account, "dept": (a.dept or "").strip(),
"nickname": (a.nickname or "").strip(), "is_admin": a.is_admin}
@@ -93,6 +96,12 @@ def admin_account_update(a: schemas.AccountUpdateIn,
else:
conn.execute("UPDATE accounts SET is_admin = 0 WHERE account = ? AND account <> ?",
(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 = ?",
(int(bool(a.status)), account))
conn.commit()
return {"ok": True, "account": account}
@@ -136,6 +145,64 @@ def admin_account_delete(d: schemas.AccountDelIn,
return {"ok": True, "account": account}
# ==================== 头像(自服务可传自己;管理员可传任意账号) ====================
_AVATAR_EXT = {".jpg", ".jpeg", ".png", ".gif", ".webp"}
@router.post("/api/admin/avatar")
def admin_avatar_upload(file: UploadFile = File(...),
account: str = Query(...),
x_admin_token: str = Header(default="", alias="X-Admin-Token"),
x_api_token: str = Header(default="", alias="X-API-Token"),
x_admin_user: str = Header(default="", alias="X-Admin-User")) -> dict:
"""上传账号头像:自服务传自己;管理员可传任意账号。覆盖旧头像。"""
try:
login = _resolve_login(x_admin_token, x_api_token, x_admin_user)
except Exception:
raise HTTPException(401, "登录态无效或已过期,请重新登录")
account = account.strip()
if not account:
raise HTTPException(400, "account 不能为空")
if account != login:
_require_admin(x_admin_token, x_api_token)
ext = Path(file.filename or "").suffix.lower()
if ext not in _AVATAR_EXT:
raise HTTPException(400, "仅支持图片格式(jpg/png/gif/webp)")
content = file.file.read()
if not content or len(content) > 2 * 1024 * 1024:
raise HTTPException(400, "头像文件为空或超过 2MB")
with _db() as conn:
if not conn.execute("SELECT 1 FROM accounts WHERE account = ?", (account,)).fetchone():
raise HTTPException(400, f"账号 {account} 不存在")
old = conn.execute("SELECT avatar FROM accounts WHERE account = ?", (account,)).fetchone()
old_name = (old["avatar"] if old else "") or ""
config.AVATAR_DIR.mkdir(parents=True, exist_ok=True)
fname = f"{account}{ext}"
(config.AVATAR_DIR / fname).write_bytes(content)
if old_name and old_name != fname: # 换扩展名时清掉旧文件,防残留
try:
(config.AVATAR_DIR / old_name).unlink(missing_ok=True)
except OSError:
pass
with _db() as conn:
conn.execute("UPDATE accounts SET avatar = ? WHERE account = ?", (fname, account))
conn.commit()
return {"ok": True, "account": account, "avatar": fname}
@router.get("/api/avatar/{account}")
def admin_avatar_get(account: str) -> FileResponse:
"""读取账号头像(前端 img 直接引用;未设置返回 404)。"""
with _db() as conn:
row = conn.execute("SELECT avatar FROM accounts WHERE account = ?", (account,)).fetchone()
if not row or not row["avatar"]:
raise HTTPException(404, "未设置头像")
path = config.AVATAR_DIR / row["avatar"]
if not path.is_file():
raise HTTPException(404, "头像文件缺失")
return FileResponse(path)
# ==================== 授权 / 插件维护 ====================
@router.post("/api/admin/account_plugins")
def admin_grant(g: schemas.GrantIn,
@@ -366,7 +433,8 @@ def admin_overview(x_admin_token: str = Header(default="", alias="X-Admin-Token"
"SELECT account, can_download, can_run FROM plugin_grants "
"WHERE plugin_id = ?", (p["id"],))}
accounts = [dict(r) for r in conn.execute(
"SELECT account, is_admin, dept, nickname FROM accounts ORDER BY account")]
"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"],))]
+15 -5
View File
@@ -39,14 +39,19 @@ def admin_me(x_admin_token: str = Header(default="", alias="X-Admin-Token"),
except Exception:
account = ""
if not account:
return {"account": "", "is_admin": False, "dept": "", "nickname": ""}
return {"account": "", "is_admin": False, "dept": "", "nickname": "", "avatar": ""}
with _db() as conn:
row = conn.execute(
"SELECT is_admin, dept, nickname FROM accounts WHERE account = ?", (account,)).fetchone()
"SELECT is_admin, dept, nickname, status, avatar FROM accounts WHERE account = ?",
(account,)).fetchone()
# 账号停用:视为未登录(执行机/控制面前端据此自动登出)
if not row or not row["status"]:
return {"account": "", "is_admin": False, "dept": "", "nickname": "", "avatar": ""}
return {"account": account,
"is_admin": bool(row and row["is_admin"]),
"is_admin": bool(row["is_admin"]),
"dept": (row["dept"] if row else "") or "",
"nickname": (row["nickname"] if row else "") or ""}
"nickname": (row["nickname"] if row else "") or "",
"avatar": (row["avatar"] if row else "") or ""}
@router.get("/api/admin/platforms")
@@ -68,13 +73,18 @@ def admin_auth(a: schemas.AuthIn,
_auth_gate(account)
with _db() as conn:
row = conn.execute(
"SELECT password_hash, salt, is_admin, dept, must_change_pwd FROM accounts WHERE account = ?",
"SELECT password_hash, salt, is_admin, dept, nickname, must_change_pwd, status, avatar "
"FROM accounts WHERE account = ?",
(account,)).fetchone()
if not row or not _verify_password(a.password, row["salt"], row["password_hash"]):
_auth_fail(account)
raise HTTPException(401, "账号或密码错误")
if not row["status"]:
raise HTTPException(403, "账号已停用,请联系管理员")
_AUTH_FAILS.pop(account, None)
return {"ok": True, "account": account, "is_admin": bool(row["is_admin"]),
"dept": (row["dept"] or ""), "nickname": (row["nickname"] or ""),
"avatar": (row["avatar"] or ""),
"must_change_pwd": bool(row["must_change_pwd"]),
"token": _sign_admin_token(account)}
+3 -1
View File
@@ -38,10 +38,12 @@ 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 FROM accounts WHERE account = ?",
"SELECT account, is_admin, must_change_pwd, nickname, status FROM accounts WHERE account = ?",
(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 = ?",
(nickname, account))
+13
View File
@@ -19,6 +19,13 @@ from controlplane.core.pkgutil import _load_manifest
router = APIRouter()
def _account_disabled(acct: str) -> bool:
"""账号是否已停用(停用后机器侧一律不给插件/授权)。"""
with _db() as conn:
row = conn.execute("SELECT status FROM accounts WHERE account = ?", (acct,)).fetchone()
return bool(row) and not bool(row["status"])
@router.get("/api/plugins", response_model=dict)
def plugins(account: str = Query(default="", description="账号(旧底座按此传)"),
x_api_token: str = Header(default="", alias="X-API-Token"),
@@ -34,6 +41,8 @@ def plugins(account: str = Query(default="", description="账号(旧底座按此
acct = (account or "").strip()
if not acct:
raise HTTPException(400, "缺少有效会话或 account")
if _account_disabled(acct):
return {"account": acct, "plugins": []}
with _db() as conn:
rows = conn.execute(
"""
@@ -59,6 +68,8 @@ def platforms_allowed(account: str = Query(default="", description="账号(旧
acct = (account or "").strip()
if not acct:
raise HTTPException(400, "缺少有效会话或 account")
if _account_disabled(acct):
return {"account": acct, "allowed": []}
with _db() as conn:
rows = conn.execute(
"SELECT platform_id FROM account_platforms WHERE account = ? ORDER BY platform_id",
@@ -130,6 +141,8 @@ def me_license(account: str = Query(...), device: str = Query(default=""),
_check_token(x_api_token)
if not account.strip():
raise HTTPException(400, "account 不能为空")
if _account_disabled(account.strip()):
raise HTTPException(403, "账号已停用,无法获取授权")
with _db() as conn:
rows = conn.execute(
"""
Binary file not shown.

After

Width:  |  Height:  |  Size: 70 B

+1
View File
@@ -24,6 +24,7 @@ def _app_base() -> Path:
APP_DIR = _app_base()
DB_PATH = APP_DIR / "controlplane.db"
PKG_DIR = APP_DIR / "packages"
AVATAR_DIR = APP_DIR / "avatars"
# 壳子(执行机主程序)更新源:version.json + setup 安装包,供执行端自动下载升级
SHELL_DIR = APP_DIR / "shell"
+46 -2
View File
@@ -40,6 +40,40 @@ def _ensure_col(conn: sqlite3.Connection, table: str, col: str, ddl: str) -> Non
conn.execute(f"ALTER TABLE {table} ADD COLUMN {col} {ddl}")
def _migrate_accounts(conn: sqlite3.Connection) -> None:
"""老库 accounts 迁移:account 主键 → 自增 id 主键(account 改唯一键),并补新列。
仅当表缺 id 列时执行;新库/已迁移库直接跳过。old 表在此前已 _ensure_col 补齐
must_change_pwd,故 SELECT 可直接引用。
"""
cols = {r["name"] for r in conn.execute("PRAGMA table_info(accounts)").fetchall()}
if "id" in cols:
return
conn.executescript("""
CREATE TABLE accounts_new (
id INTEGER PRIMARY KEY AUTOINCREMENT,
account TEXT NOT NULL UNIQUE,
password_hash TEXT NOT NULL,
salt TEXT NOT NULL,
is_admin INTEGER DEFAULT 0,
dept TEXT DEFAULT '',
nickname TEXT DEFAULT '',
dingtalk_uid TEXT DEFAULT '',
must_change_pwd INTEGER DEFAULT 0,
avatar TEXT DEFAULT '',
status INTEGER DEFAULT 1,
created_at TEXT DEFAULT ''
);
INSERT INTO accounts_new(account, password_hash, salt, is_admin, dept,
nickname, dingtalk_uid, must_change_pwd)
SELECT account, password_hash, salt, is_admin, dept,
nickname, dingtalk_uid, COALESCE(must_change_pwd, 0)
FROM accounts;
DROP TABLE accounts;
ALTER TABLE accounts_new RENAME TO accounts;
""")
def _init_db() -> None:
"""建表(幂等)。基础表 + 产品化扩展表(插件授权/审计/运行上报),并兼容旧库补列。"""
with _db() as conn:
@@ -68,13 +102,18 @@ def _init_db() -> None:
PRIMARY KEY (account, platform_id)
);
CREATE TABLE IF NOT EXISTS accounts (
account TEXT PRIMARY KEY,
id INTEGER PRIMARY KEY AUTOINCREMENT,
account TEXT NOT NULL UNIQUE,
password_hash TEXT NOT NULL,
salt TEXT NOT NULL,
is_admin INTEGER DEFAULT 0,
dept TEXT DEFAULT '',
nickname TEXT DEFAULT '',
dingtalk_uid TEXT DEFAULT ''
dingtalk_uid TEXT DEFAULT '',
must_change_pwd INTEGER DEFAULT 0,
avatar TEXT DEFAULT '',
status INTEGER DEFAULT 1,
created_at TEXT DEFAULT ''
);
CREATE TABLE IF NOT EXISTS plugin_grants (
account TEXT NOT NULL,
@@ -117,6 +156,11 @@ def _init_db() -> None:
_ensure_col(conn, "accounts", "nickname", "TEXT DEFAULT ''")
_ensure_col(conn, "accounts", "dingtalk_uid", "TEXT DEFAULT ''")
_ensure_col(conn, "accounts", "must_change_pwd", "INTEGER DEFAULT 0")
# 老库迁移:account 主键 → 自增 id 主键 + 补 avatar/status/created_at(幂等)
_migrate_accounts(conn)
_ensure_col(conn, "accounts", "avatar", "TEXT DEFAULT ''")
_ensure_col(conn, "accounts", "status", "INTEGER DEFAULT 1")
_ensure_col(conn, "accounts", "created_at", "TEXT DEFAULT ''")
# 回填:老库 account_plugins 已有授权但 plugin_grants 为空,则按"全权限"补录,
# 保证离线票据 license 不会漏掉存量授权(can_download=1, can_run=1)。
conn.execute(
+1
View File
@@ -60,6 +60,7 @@ class AccountUpdateIn(BaseModel):
dept: str | None = None
nickname: str | None = None
is_admin: bool | None = None
status: bool | None = None # 是否启用(True=启用,False=停用)
class AccountResetIn(BaseModel):
+3 -3
View File
@@ -14,7 +14,7 @@
<n-dropdown trigger="click" :options="acctOptions" @select="onCommand">
<div class="acct">
<span class="avatar">{{ initial }}</span>
<span class="acct-name">{{ store.current }}</span>
<span class="acct-name">{{ store.nickname || store.current }}</span>
<n-tag v-if="store.isAdmin" size="small" round :bordered="false" type="primary" class="admin-tag">管理员</n-tag>
<n-icon class="caret" :size="13"><ArrowDown /></n-icon>
</div>
@@ -99,7 +99,7 @@ function onMenu(key) {
route.value = h
}
const initial = computed(() => (store.current || '')[0]?.toUpperCase() || '?')
const initial = computed(() => (store.nickname || store.current || '')[0]?.toUpperCase() || '?')
const pwdOpen = ref(false)
function onCommand(cmd) {
@@ -121,7 +121,7 @@ onMounted(async () => {
try {
const me = await adminMe()
if (!me.account || !me.is_admin) clearSession()
else store.isAdmin = true
else { store.isAdmin = true; store.nickname = me.nickname || '' }
} catch (_) { /* 后端 down:保持本地态 */ }
})
</script>
+6
View File
@@ -84,6 +84,12 @@ export async function adminAccountDelete(body) {
body: JSON.stringify(body)
})
}
export async function adminAvatarUpload(account, file) {
const fd = new FormData()
fd.append('file', file)
const qs = new URLSearchParams({ account })
return req('/api/admin/avatar?' + qs.toString(), { method: 'POST', headers: adminHeaders(), body: fd })
}
export async function adminPluginDelete(body) {
return req('/api/admin/plugin/delete', {
method: 'POST',
@@ -70,8 +70,9 @@ async function doLogin() {
store.current = acct
store.token = r.token || ''
store.isAdmin = true
store.nickname = r.nickname || ''
try { localStorage.setItem('cp_account', acct); localStorage.setItem('cp_token', store.token) } catch (_) {}
message.success(`欢迎,${acct}`)
message.success(`欢迎,${store.nickname || acct}`)
emit('ok', r)
} catch (e) {
message.error(e.message || String(e))
@@ -6,6 +6,7 @@ export const store = reactive({
isAdmin: false,
current: _get('cp_account'),
token: _get('cp_token'),
nickname: '',
})
// 概览数据缓存:各管理页共用一份 adminOverview 结果,避免切页重复拉取
@@ -35,6 +36,7 @@ export function clearSession() {
store.current = ''
store.token = ''
store.isAdmin = false
store.nickname = ''
resetOverview()
try { localStorage.removeItem('cp_account'); localStorage.removeItem('cp_token') } catch (_) {}
}
@@ -73,7 +73,7 @@ import { computed, h, onMounted, reactive, ref } from 'vue'
import { NButton, NInput, NSwitch, NTag } from 'naive-ui'
import { Refresh, Plus } from '@element-plus/icons-vue'
import { store, overview, overviewBusy, loadOverview } from '../store'
import { adminAccountCreate, adminAccountUpdate, adminAccountReset, adminAccountDelete } from '../api'
import { adminAccountCreate, adminAccountUpdate, adminAccountReset, adminAccountDelete, adminAvatarUpload } from '../api'
import { message, dialog } from '../naive'
const current = computed(() => store.current || '')
@@ -118,6 +118,45 @@ async function toggleAdmin(row) {
try { await adminAccountUpdate({ account: row.account, is_admin: !row.is_admin }); await refresh() }
catch (e) { message.error(e.message || e) }
}
async function toggleStatus(row, v) {
if (row.account === current.value && !v) { message.warning('不能停用当前登录的账号'); return }
try { await adminAccountUpdate({ account: row.account, status: v }); await refresh() }
catch (e) { message.error(e.message || e) }
}
// ---------- 头像(显示 + 上传) ----------
const _fileInput = (() => {
const el = document.createElement('input')
el.type = 'file'
el.accept = 'image/*'
return el
})()
function pickAvatar(row) {
_fileInput.onchange = async () => {
const f = _fileInput.files && _fileInput.files[0]
_fileInput.value = ''
if (!f) return
try {
await adminAvatarUpload(row.account, f)
message.success(`已更新 ${row.account} 的头像`)
await refresh()
} catch (e) { message.error(e.message || e) }
}
_fileInput.click()
}
function avatarCell(row) {
const img = row.avatar
? h('img', {
src: `/api/avatar/${row.account}?v=${encodeURIComponent(row.avatar)}`,
class: 'cell-avatar',
onError: (e) => { e.target.style.display = 'none' },
})
: h('span', { class: 'dim' }, '—')
return h('div', { class: 'cell-avatar-wrap' }, [
img,
h(NButton, { text: true, size: 'tiny', type: 'primary', onClick: () => pickAvatar(row) }, { default: () => '上传' }),
])
}
function renderTags(list, kind) {
if (!list || !list.length) return h('span', { class: 'dim' }, '—')
@@ -128,22 +167,30 @@ function renderTags(list, kind) {
}
const columns = computed(() => [
{ title: '账号', key: 'account', width: 140, render: r => h('b', { class: 'cell-strong' }, r.account) },
{ title: '昵称', key: 'nickname', width: 150, render: r => inlineInput(r, 'nickname') },
{ title: 'ID', key: 'id', width: 64, render: r => h('span', { class: 'dim' }, r.id ?? '—') },
{ title: '用户名(工号)', key: 'account', width: 130, render: r => h('b', { class: 'cell-strong' }, r.account) },
{ title: '昵称(姓名)', key: 'nickname', width: 130, render: r => inlineInput(r, 'nickname') },
{ title: '部门', key: 'dept', width: 130, render: (row) => inlineInput(row, 'dept') },
{ title: '头像', key: 'avatar', width: 120, render: r => avatarCell(r) },
{
title: '部门', key: 'dept', width: 160,
render: (row) => inlineInput(row, 'dept'),
title: '状态', key: 'status', width: 90,
render: (row) => h(NSwitch, {
value: !!row.status,
disabled: row.account === current.value,
onUpdateValue: (v) => toggleStatus(row, v),
}),
},
{ title: '创建时间', key: 'created_at', width: 150, render: r => h('span', { class: 'dim' }, r.created_at || '—') },
{
title: '管理员', key: 'is_admin', width: 100,
title: '管理员', key: 'is_admin', width: 90,
render: (row) => h(NSwitch, {
value: !!row.is_admin,
disabled: row.account === current.value,
onUpdateValue: () => toggleAdmin(row),
}),
},
{ title: '已授权插件', key: 'plugins', minWidth: 180, render: r => renderTags(r.plugins, 'plugin') },
{ title: '已授权平台', key: 'platforms', minWidth: 140, render: r => renderTags(r.platforms, 'platform') },
{ title: '已授权插件', key: 'plugins', minWidth: 160, render: r => renderTags(r.plugins, 'plugin') },
{ title: '已授权平台', key: 'platforms', minWidth: 130, render: r => renderTags(r.platforms, 'platform') },
{
title: '操作', key: 'actions', width: 170,
render: (row) => h('div', { class: 'ops' }, [
@@ -237,4 +284,6 @@ onMounted(refresh)
<style>
.ops { display: flex; align-items: center; gap: 16px; }
.ops .n-button { padding: 0 4px; }
.cell-avatar-wrap { display: flex; align-items: center; gap: 8px; }
.cell-avatar { width: 32px; height: 32px; border-radius: 50%; object-fit: cover; background: #f2f3f7; flex: none; }
</style>
@@ -3,7 +3,7 @@
<div class="page-head cp-rise">
<div>
<h3>概览 <span class="badge">Dashboard</span></h3>
<p>中心机 · 插件分发与账号权限 · 当前账号 <b class="who">{{ store.current }}</b></p>
<p>中心机 · 插件分发与账号权限 · 当前账号 <b class="who">{{ store.nickname || store.current }}</b></p>
</div>
<n-button :loading="overviewBusy" @click="refresh">
<template #icon><n-icon><Refresh /></n-icon></template>刷新