feat: 授权关联用户账号 — 登录记录设备, 激活时卡密存账号, 换设备登录自动授权(最多10台), 用户中心显示授权状态

This commit is contained in:
personal82555 committed 2026-10-12 12:32:13 +08:00
1 parent 3cd73d7f62
commit 70e03feca6
4 files changed
+133 -4

No files matched your search

+78 -1
View File
@@ -480,9 +480,33 @@ def check(machine: str, tool: str) -> int:
return 200 if trial_allowed(machine, tool) else 403
if query_authorized(machine):
return 200
# account-level license: this device belongs to a logged-in user whose card is active
if _account_license_ok(machine):
return 200
return 200 if trial_allowed(machine, tool) else 403
def _account_license_ok(machine: str) -> bool:
"""True when this device logged into an account holding an active card."""
try:
conn = _db()
rows = conn.execute("SELECT card_key, origin_machine, bound_machines FROM users").fetchall()
conn.close()
except Exception:
return False
for card_key, origin, bm_json in rows:
if not card_key or not origin:
continue
try:
machines = json.loads(bm_json or "[]")
except Exception:
machines = []
if machine in machines:
if origin == machine or query_authorized(origin):
return True
return False
# ---- card activation (server-side key) ----
_auth_state: dict = {"token": None}
@@ -604,10 +628,47 @@ def _db():
conn = sqlite3.connect(USER_DB)
conn.execute("CREATE TABLE IF NOT EXISTS users (username TEXT PRIMARY KEY, salt TEXT, pw_hash TEXT, created REAL)")
conn.execute("CREATE TABLE IF NOT EXISTS files (id TEXT PRIMARY KEY, username TEXT, name TEXT, size INTEGER, mime TEXT, created REAL)")
for stmt in (
"ALTER TABLE users ADD COLUMN card_key TEXT DEFAULT ''",
"ALTER TABLE users ADD COLUMN origin_machine TEXT DEFAULT ''",
"ALTER TABLE users ADD COLUMN bound_machines TEXT DEFAULT '[]'",
):
try:
conn.execute(stmt)
except sqlite3.OperationalError:
pass
conn.commit()
return conn
def _bind_machine(username: str, machine: str):
"""remember devices that logged into this account (max 10)"""
if not machine or not MACHINE_RE.match(machine):
return
conn = _db()
row = conn.execute("SELECT bound_machines FROM users WHERE username=?", (username,)).fetchone()
try:
machines = json.loads(row[0] or "[]") if row else []
except Exception:
machines = []
if machine in machines:
machines.remove(machine)
machines.insert(0, machine)
conn.execute("UPDATE users SET bound_machines=? WHERE username=?", (json.dumps(machines[:10]), username))
conn.commit()
conn.close()
def _save_user_license(username: str, card_key: str, machine: str):
"""store the card bound to this account after a successful activation"""
conn = _db()
conn.execute("UPDATE users SET card_key=?, origin_machine=? WHERE username=?",
(card_key, machine, username))
conn.commit()
conn.close()
_bind_machine(username, machine)
def _hash_pw(pw, salt):
return hashlib.pbkdf2_hmac("sha256", pw.encode(), salt.encode(), 120000).hex()
@@ -666,6 +727,10 @@ def verify_turnstile(token: str) -> bool:
USER_NAME_RE = re.compile(r"^[A-Za-z0-9_\u4e00-\u9fa5-]{3,32}$")
def _req_machine(handler):
return handler.headers.get("X-Machine-Id", "") if handler else ""
def user_api(method, sub, payload, handler):
"""returns (status, body_dict)"""
if method == "POST" and sub == "/register":
@@ -687,6 +752,7 @@ def user_api(method, sub, payload, handler):
finally:
conn.close()
_user_dir(username)
_bind_machine(username, _req_machine(handler))
return 200, {"code": 200, "message": "ok", "data": {"token": _make_token(username), "username": username}}
if method == "POST" and sub == "/login":
@@ -700,6 +766,7 @@ def user_api(method, sub, payload, handler):
if not row or _hash_pw(password, row[0]) != row[1]:
return 401, {"code": 401, "message": "用户名或密码错误"}
_user_dir(username)
_bind_machine(username, _req_machine(handler))
return 200, {"code": 200, "message": "ok", "data": {"token": _make_token(username), "username": username}}
# ---- below requires auth ----
@@ -872,7 +939,7 @@ class Handler(BaseHTTPRequestHandler):
return
authorized = False
if machine not in _load_revoked():
authorized = query_authorized(machine)
authorized = query_authorized(machine) or _account_license_ok(machine)
body = {"code": 200, "message": "ok", "data": {"authorized": authorized}}
self._reply(200, json.dumps(body, ensure_ascii=False).encode("utf-8"), "application/json")
return
@@ -1128,6 +1195,16 @@ class Handler(BaseHTTPRequestHandler):
return
status, body = activate_card(card_key, machine_id, contact_qq, replace=replace)
if status == 200:
# bind card to the logged-in account so it follows the user across devices
tok = self.headers.get("Authorization", "")
if tok.lower().startswith("bearer "):
acc = _parse_token(tok[7:])
if acc:
try:
_save_user_license(acc, card_key, machine_id)
except Exception:
pass
self._reply(status, json.dumps(body, ensure_ascii=False).encode("utf-8"), "application/json")
return