feat: 新增账号状态管理、头像功能与报表工具,完善账号系统
新增账号状态字段与停用校验,支持账号头像上传管理,新增物料收发汇总表合并工具,优化银行卡检查脚本,新增ERP登录复用模块,重构账号数据库迁移与管理接口
This commit is contained in:
@@ -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"],))]
|
||||
|
||||
@@ -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)}
|
||||
|
||||
|
||||
@@ -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))
|
||||
|
||||
@@ -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(
|
||||
"""
|
||||
|
||||
Reference in New Issue
Block a user