feat(账号池): 对外只读 API(独立令牌)+ 资产管理入口

- GET /api/account_pool/accounts:X-Account-Token / Bearer,支持 device/q/status/online 过滤
- 令牌存 app_meta.account_pool_token,页面可查看/复制/重置
- 管理端 GET /api/account_pool/token、POST /token/reset
- CORS;API/ACCOUNT_FOLDER 文档同步
This commit is contained in:
2026-10-20 16:14:31 +08:00
parent 0a3920d97d
commit 6bdf45808b
5 changed files with 240 additions and 1 deletions
+120 -1
View File
@@ -17,21 +17,62 @@
抓元素 / 测一下:**复用现有的**(前端 openPicker / `POST /api/steps/test`),这里不重复造
"""
import os
import hmac
import secrets
import threading
import time
import uuid
from flask import Blueprint, jsonify, request, send_file
from flask_login import current_user
from core import account_folder as af
from core.db_config import meta_get, meta_set
from core.logger import get_logger
from web.auth import perm_required, PERM_DEVICES
from web.auth import perm_required, admin_required, PERM_DEVICES
_log = get_logger("web")
bp = Blueprint("account_folder", __name__)
PROFILE_ID = "default"
# ==================== 账号池对外 API(给其他应用只读访问)====================
# 与「设备端令牌」分开:这里只读账号库,不暴露设备 Agent 的 bootstrap/上报能力。
_K_POOL_TOKEN = "account_pool_token"
_K_POOL_TOKEN_AT = "account_pool_token_at"
def _pool_token():
"""取(没有就生成)账号池 API 令牌,存 app_meta(随备份走)。"""
tok = meta_get(_K_POOL_TOKEN) or ""
if not tok:
tok = secrets.token_urlsafe(24)
meta_set(_K_POOL_TOKEN, tok)
meta_set(_K_POOL_TOKEN_AT, time.strftime("%Y-%m-%d %H:%M:%S"))
_log.info("账号池 API 令牌已生成")
return tok
def _pool_req_token():
"""请求里的令牌:`X-Account-Token` 或 `Authorization: Bearer <token>`。"""
tok = (request.headers.get("X-Account-Token") or "").strip()
if tok:
return tok
auth = (request.headers.get("Authorization") or "").strip()
if auth.lower().startswith("bearer "):
return auth[7:].strip()
return ""
def _pool_json(data, code=200):
"""账号池 JSON 响应:带 CORS(其他应用/网页可直接读)。"""
resp = jsonify(data)
resp.status_code = code
resp.headers["Access-Control-Allow-Origin"] = "*"
resp.headers["Access-Control-Allow-Headers"] = "X-Account-Token, Authorization, Content-Type"
resp.headers["Access-Control-Allow-Methods"] = "GET, OPTIONS"
return resp
def _profile_row(create=True):
"""取(或建)那唯一一条配置。"""
@@ -364,6 +405,84 @@ def api_af_roster():
return jsonify({"ok": True, "rows": rows, "groups": groups, "total": len(rows)})
# ==================== 账号池对外只读 API ====================
# 其他应用用 `X-Account-Token`(或 Bearer)访问,不需要登录会话。
@bp.route("/api/account_pool/accounts", methods=["GET", "OPTIONS"])
def api_account_pool_accounts():
"""**账号池**(账号库)只读列表:给其他应用看"池子里有哪些号、在哪台手机"。
鉴权:`X-Account-Token: <token>` 或 `Authorization: Bearer <token>`
(令牌在「资产管理 → 🔑 账号池 API」里查看/重置)。
可选过滤:`?device=A11`、`?q=锋哥`、`?status=正常`、`?online=1`。
"""
if request.method == "OPTIONS":
return _pool_json({"ok": True})
real = _pool_token()
got = _pool_req_token()
if not got or not hmac.compare_digest(got, real):
_log.warning("账号池 API 鉴权失败(来源 %s)", request.remote_addr)
return _pool_json({"ok": False, "error": "unauthorized"}, 401)
device = (request.args.get("device") or "").strip()
q = (request.args.get("q") or "").strip().lower()
status = (request.args.get("status") or "").strip()
only_online = (request.args.get("online") or "").strip().lower() in ("1", "true", "yes")
rows = af.roster_rows()
out = []
for r in rows:
if device and (r.get("device_name") or "") != device:
continue
if status and (r.get("account_status") or "") != status:
continue
if only_online and not r.get("online"):
continue
if q and q not in (r.get("nickname") or "").lower() \
and q not in (r.get("douyin_id") or "").lower():
continue
out.append({
"id": r.get("id") or "",
"nickname": r.get("nickname") or "",
"douyin_id": r.get("douyin_id") or "",
"device_name": r.get("device_name") or "",
"serial": r.get("serial") or "",
"phone": r.get("phone") or "",
"online": bool(r.get("online")),
"pooled": bool(r.get("pooled")),
"account_status": r.get("account_status") or "",
"can_post_video": bool(r.get("can_post_video")),
"note": r.get("note") or "",
"updated_at": r.get("updated_at") or "",
})
return _pool_json({"ok": True, "total": len(out), "total_all": len(rows),
"server_time": time.strftime("%Y-%m-%d %H:%M:%S"),
"accounts": out})
@bp.route("/api/account_pool/token")
@admin_required
def api_account_pool_token():
"""管理端:查看账号池 API 令牌(仅管理员;页面「资产 → 🔑 账号池 API」)。"""
tok = _pool_token()
return jsonify({"ok": True, "token": tok,
"token_created_at": meta_get(_K_POOL_TOKEN_AT) or "",
"url": request.host_url.rstrip("/") + "/api/account_pool/accounts"})
@bp.route("/api/account_pool/token/reset", methods=["POST"])
@admin_required
def api_account_pool_token_reset():
"""管理端:重置账号池 API 令牌(旧令牌立即失效)。"""
tok = secrets.token_urlsafe(24)
meta_set(_K_POOL_TOKEN, tok)
meta_set(_K_POOL_TOKEN_AT, time.strftime("%Y-%m-%d %H:%M:%S"))
_log.info("账号池 API 令牌已重置 by %s", getattr(current_user, "username", ""))
return jsonify({"ok": True, "token": tok,
"token_created_at": meta_get(_K_POOL_TOKEN_AT) or "",
"url": request.host_url.rstrip("/") + "/api/account_pool/accounts",
"msg": "令牌已重置(旧令牌立即失效)"})
@bp.route("/api/af/roster/import", methods=["POST"])
@perm_required(PERM_DEVICES)
def api_af_roster_import():