feat(HEL-560): 数据中枢接管数据源/模型池/会员,注册改一次性邀请码
主站 - 新增 m0006 invite_codes 迁移;注册强制邀请码(首个管理员除外),消码与建号 同一事务,并发提交只有一个能成功 - 新增 /api/hub-admin/* 服务端点(共享 HUB_ADMIN_TOKEN,先于鉴权校验),供数据 中枢桥接读写会话/密码/模型池/会员/邀请码,并提供供应商模型列表拉取 - 前端:注册表单加邀请码(桌面 login、index.html、移动端);「系统管理」改为 「数据中枢」入口指向 8766,原模型池与会员管理分区移除,仅留「行情管理」; 随之清理陈旧 CSS 数据中枢 - 取消独立账号:删除 hub_admin/hub_sessions 与登录、改密、锁定逻辑,改为校验 主站 xiaobai_session,仅管理员可进,CSRF 由会话派生,危险操作二次确认走主站 - 控制台新增数据源凭证可编辑区(原有内容一项不删)、供应商制模型池(自动拉取 /models,失败退回卡内手动录入)、会员管理与邀请码页 - 日夜双主题:颜色收敛为同名 token 换值,SVG 改用 inline style 以吃到变量 自测 - 主站 verify_baseline 通过(498 项);数据中枢 235 项通过 - tools/verify_datahub_console.py 端到端跑通两服务真实对话; tools/verify_datahub_console_ui.py 浏览器跑通门禁/凭证/模型池/会员/主题/1030 窄屏 Co-authored-by: multica-agent <github@multica.ai>
This commit is contained in:
@@ -28,8 +28,14 @@ class AccountApplicationMixin:
|
||||
def update_membership(self, payload: dict[str, Any]) -> None:
|
||||
self.accounts.update_membership(payload)
|
||||
|
||||
def register_account(self, username: str, password: str, device_hash: str = "") -> dict[str, Any]:
|
||||
return self.accounts.register(username, password, device_hash)
|
||||
def register_account(
|
||||
self,
|
||||
username: str,
|
||||
password: str,
|
||||
device_hash: str = "",
|
||||
invite_code: str = "",
|
||||
) -> dict[str, Any]:
|
||||
return self.accounts.register(username, password, device_hash, invite_code)
|
||||
|
||||
def login_account(self, username: str, password: str, device_hash: str = "") -> dict[str, Any]:
|
||||
return self.accounts.login(username, password, device_hash)
|
||||
|
||||
@@ -41,6 +41,7 @@ class AccountHttpMixin:
|
||||
str(body.get("username") or ""),
|
||||
str(body.get("password") or ""),
|
||||
token_hash(device_raw),
|
||||
str(body.get("invite_code") or ""),
|
||||
)
|
||||
self._send_authenticated_session(result, HTTPStatus.CREATED, device_raw)
|
||||
except (ValueError, json.JSONDecodeError) as exc:
|
||||
|
||||
@@ -5,6 +5,9 @@ from datetime import datetime, timezone
|
||||
from typing import Any
|
||||
|
||||
|
||||
INVITE_CONSUMED_MESSAGE = "邀请码无效或已被使用,请联系管理员重新获取。"
|
||||
|
||||
|
||||
class AccountRepositoryMixin:
|
||||
"""Original SQLite account persistence methods, moved without query changes."""
|
||||
|
||||
@@ -23,11 +26,14 @@ class AccountRepositoryMixin:
|
||||
username: str,
|
||||
password_salt: str,
|
||||
password_hash: str,
|
||||
invite_code: str = "",
|
||||
) -> dict[str, Any]:
|
||||
now = datetime.now(timezone.utc).isoformat(timespec="seconds")
|
||||
try:
|
||||
with self.connect() as connection:
|
||||
role = "admin" if int(connection.execute("SELECT COUNT(*) FROM users").fetchone()[0]) == 0 else "user"
|
||||
if invite_code and not self._consume_invite_code(connection, invite_code, now):
|
||||
raise ValueError(INVITE_CONSUMED_MESSAGE)
|
||||
cursor = connection.execute(
|
||||
"""
|
||||
INSERT INTO users
|
||||
@@ -37,10 +43,91 @@ class AccountRepositoryMixin:
|
||||
(username, password_salt, password_hash, role, now, now),
|
||||
)
|
||||
user_id = int(cursor.lastrowid)
|
||||
if invite_code:
|
||||
connection.execute(
|
||||
"UPDATE invite_codes SET used_by = ? WHERE code = ?",
|
||||
(user_id, invite_code),
|
||||
)
|
||||
except sqlite3.IntegrityError as exc:
|
||||
raise ValueError("该账号名已被使用。") from exc
|
||||
return {"id": user_id, "username": username, "role": role, "created_at": now}
|
||||
|
||||
@staticmethod
|
||||
def _consume_invite_code(
|
||||
connection: sqlite3.Connection, code: str, used_at: str
|
||||
) -> bool:
|
||||
cursor = connection.execute(
|
||||
"""
|
||||
UPDATE invite_codes SET status = 'used', used_at = ?
|
||||
WHERE code = ? AND status = 'unused'
|
||||
""",
|
||||
(used_at, code),
|
||||
)
|
||||
return cursor.rowcount > 0
|
||||
|
||||
def invite_code(self, code: str) -> dict[str, Any] | None:
|
||||
with self.connect() as connection:
|
||||
row = connection.execute(
|
||||
"""
|
||||
SELECT code, status, note, created_at, used_at, revoked_at, used_by
|
||||
FROM invite_codes WHERE code = ?
|
||||
""",
|
||||
(code,),
|
||||
).fetchone()
|
||||
return dict(row) if row else None
|
||||
|
||||
def create_invite_codes(
|
||||
self, codes: list[str], note: str, created_by: int
|
||||
) -> list[str]:
|
||||
now = datetime.now(timezone.utc).isoformat(timespec="seconds")
|
||||
with self.connect() as connection:
|
||||
for code in codes:
|
||||
connection.execute(
|
||||
"""
|
||||
INSERT INTO invite_codes (code, status, note, created_by, created_at)
|
||||
VALUES (?, 'unused', ?, ?, ?)
|
||||
""",
|
||||
(code, note, created_by or None, now),
|
||||
)
|
||||
return list(codes)
|
||||
|
||||
def revoke_invite_code(self, code: str) -> bool:
|
||||
now = datetime.now(timezone.utc).isoformat(timespec="seconds")
|
||||
with self.connect() as connection:
|
||||
cursor = connection.execute(
|
||||
"""
|
||||
UPDATE invite_codes SET status = 'revoked', revoked_at = ?
|
||||
WHERE code = ? AND status = 'unused'
|
||||
""",
|
||||
(now, code),
|
||||
)
|
||||
return cursor.rowcount > 0
|
||||
|
||||
def list_invite_codes(self, limit: int = 100) -> list[dict[str, Any]]:
|
||||
with self.connect() as connection:
|
||||
rows = connection.execute(
|
||||
"""
|
||||
SELECT c.code, c.status, c.note, c.created_at, c.used_at, c.revoked_at,
|
||||
u.username AS used_by_username
|
||||
FROM invite_codes AS c
|
||||
LEFT JOIN users AS u ON u.id = c.used_by
|
||||
ORDER BY c.created_at DESC, c.code
|
||||
LIMIT ?
|
||||
""",
|
||||
(max(1, min(500, int(limit))),),
|
||||
).fetchall()
|
||||
return [dict(row) for row in rows]
|
||||
|
||||
def count_invite_codes(self) -> dict[str, int]:
|
||||
with self.connect() as connection:
|
||||
rows = connection.execute(
|
||||
"SELECT status, COUNT(*) AS total FROM invite_codes GROUP BY status"
|
||||
).fetchall()
|
||||
counts = {"unused": 0, "used": 0, "revoked": 0}
|
||||
for row in rows:
|
||||
counts[str(row["status"])] = int(row["total"])
|
||||
return counts
|
||||
|
||||
def user_by_username(self, username: str) -> dict[str, Any] | None:
|
||||
with self.connect() as connection:
|
||||
row = connection.execute(
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import secrets
|
||||
import threading
|
||||
from collections.abc import Callable
|
||||
@@ -82,16 +83,123 @@ class AccountService:
|
||||
MAX_GRANTS_PER_DEVICE = 5
|
||||
SWITCH_REAUTH_MESSAGE = "该账号需重新验证"
|
||||
|
||||
def register(self, username: str, password: str, device_hash: str = "") -> dict[str, Any]:
|
||||
INVITE_ALPHABET = "ACDEFGHJKLMNPQRTUVWXY34679"
|
||||
INVITE_MAX_BATCH = 20
|
||||
INVITE_LIST_LIMIT = 500
|
||||
|
||||
def register(
|
||||
self,
|
||||
username: str,
|
||||
password: str,
|
||||
device_hash: str = "",
|
||||
invite_code: str = "",
|
||||
) -> dict[str, Any]:
|
||||
username = username.strip()
|
||||
self.validate_input(username, password)
|
||||
with self.auth_lock:
|
||||
code = self.checked_invite_code(invite_code)
|
||||
salt, password_digest = hash_password(password)
|
||||
user = self.database.create_user(username, salt, password_digest)
|
||||
user = self.database.create_user(username, salt, password_digest, code)
|
||||
result = self.create_session(user)
|
||||
self.remember_account(device_hash, int(user["id"]), fresh=True)
|
||||
return result
|
||||
|
||||
@classmethod
|
||||
def normalize_invite_code(cls, value: str) -> str:
|
||||
raw = "".join(
|
||||
character
|
||||
for character in str(value or "").upper()
|
||||
if character.isalnum()
|
||||
)
|
||||
if raw.startswith("XB") and len(raw) == 14:
|
||||
body = raw[2:]
|
||||
return f"XB-{body[0:4]}-{body[4:8]}-{body[8:12]}"
|
||||
return raw[:64]
|
||||
|
||||
@staticmethod
|
||||
def mask_invite_code(code: str) -> str:
|
||||
groups = str(code or "").split("-")
|
||||
if len(groups) < 3:
|
||||
return str(code or "")
|
||||
return f"{groups[0]}-{groups[1]}-••••"
|
||||
|
||||
@staticmethod
|
||||
def invite_handle(code: str) -> str:
|
||||
return hashlib.sha256(str(code or "").encode("utf-8")).hexdigest()[:16]
|
||||
|
||||
def checked_invite_code(self, invite_code: str) -> str:
|
||||
if self.database.count_users() == 0:
|
||||
return ""
|
||||
code = self.normalize_invite_code(invite_code)
|
||||
if not code:
|
||||
raise ValueError("请填写邀请码,注册需要管理员发放的一次性邀请码。")
|
||||
record = self.database.invite_code(code)
|
||||
status = str((record or {}).get("status") or "")
|
||||
if not record:
|
||||
raise ValueError("邀请码不存在,请向管理员确认。")
|
||||
if status == "used":
|
||||
raise ValueError("该邀请码已被使用。")
|
||||
if status != "unused":
|
||||
raise ValueError("该邀请码已作废。")
|
||||
return code
|
||||
|
||||
def generate_invite_codes(
|
||||
self, count: int, note: str = "", created_by: int = 0
|
||||
) -> list[dict[str, str]]:
|
||||
try:
|
||||
total = int(count or 1)
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValueError("生成数量不正确。") from exc
|
||||
if total < 1 or total > self.INVITE_MAX_BATCH:
|
||||
raise ValueError(f"每次最多生成 {self.INVITE_MAX_BATCH} 个邀请码。")
|
||||
codes: list[str] = []
|
||||
while len(codes) < total:
|
||||
body = "".join(secrets.choice(self.INVITE_ALPHABET) for _ in range(12))
|
||||
code = f"XB-{body[0:4]}-{body[4:8]}-{body[8:12]}"
|
||||
if code in codes or self.database.invite_code(code):
|
||||
continue
|
||||
codes.append(code)
|
||||
self.database.create_invite_codes(codes, str(note or "").strip()[:60], created_by)
|
||||
return [{"code": code, "code_id": self.invite_handle(code)} for code in codes]
|
||||
|
||||
def _stored_invite_code(self, reference: str) -> str:
|
||||
normalized = self.normalize_invite_code(reference)
|
||||
if normalized and self.database.invite_code(normalized):
|
||||
return normalized
|
||||
handle = str(reference or "").strip().lower()
|
||||
for row in self.database.list_invite_codes(self.INVITE_LIST_LIMIT):
|
||||
if self.invite_handle(str(row["code"])) == handle:
|
||||
return str(row["code"])
|
||||
return ""
|
||||
|
||||
def revoke_invite_code(self, reference: str) -> None:
|
||||
code = self._stored_invite_code(reference)
|
||||
record = self.database.invite_code(code) if code else None
|
||||
if not record:
|
||||
raise ValueError("邀请码不存在。")
|
||||
if str(record.get("status")) == "used":
|
||||
raise ValueError("该邀请码已被使用,无法作废。")
|
||||
if not self.database.revoke_invite_code(code):
|
||||
raise ValueError("该邀请码已作废。")
|
||||
|
||||
def invite_overview(self, limit: int = 100) -> dict[str, Any]:
|
||||
codes = []
|
||||
for row in self.database.list_invite_codes(limit):
|
||||
code = str(row["code"])
|
||||
codes.append(
|
||||
{
|
||||
"code_id": self.invite_handle(code),
|
||||
"code_masked": self.mask_invite_code(code),
|
||||
"status": str(row["status"]),
|
||||
"note": str(row.get("note") or ""),
|
||||
"created_at": str(row.get("created_at") or ""),
|
||||
"used_at": str(row.get("used_at") or ""),
|
||||
"revoked_at": str(row.get("revoked_at") or ""),
|
||||
"used_by_username": str(row.get("used_by_username") or ""),
|
||||
}
|
||||
)
|
||||
return {"summary": self.database.count_invite_codes(), "codes": codes}
|
||||
|
||||
def login(self, username: str, password: str, device_hash: str = "") -> dict[str, Any]:
|
||||
username = username.strip()
|
||||
if not username or not password:
|
||||
|
||||
Reference in New Issue
Block a user