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
+3 -2
View File
@@ -1,4 +1,5 @@
import { computed, ref } from 'vue';
import { licenseHeaders } from '@/tools/license/license';
const TOKEN_KEY = 'it-tools-auth';
@@ -52,7 +53,7 @@ export function useUserAuth() {
async function login(u: string, p: string, cfToken = '') {
const { status, body } = await apiFetch('/user/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
headers: { 'Content-Type': 'application/json', ...licenseHeaders() },
body: JSON.stringify({ username: u, password: p, cf_token: cfToken }),
});
if (status !== 200) {
@@ -66,7 +67,7 @@ export function useUserAuth() {
async function register(u: string, p: string, cfToken = '') {
const { status, body } = await apiFetch('/user/register', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
headers: { 'Content-Type': 'application/json', ...licenseHeaders() },
body: JSON.stringify({ username: u, password: p, cf_token: cfToken }),
});
if (status !== 200) {
+38
View File
@@ -9,6 +9,23 @@ useHead({ title: '用户中心 - IT-TOOLS-PRO' });
const { isLoggedIn, username } = useUserAuth();
// ---- 授权状态 ----
const licensed = ref<boolean | null>(null);
async function loadLicense() {
try {
const { getMachineId } = await import('@/tools/license/license');
const res = await fetch(`/relay/auth-status?machine_id=${getMachineId()}`);
const b = await res.json();
licensed.value = !!b?.data?.authorized;
}
catch {
licensed.value = null;
}
}
if (isLoggedIn.value) {
loadLicense();
}
// ============ 数据(优先云端,回退本地) ============
const favTools = ref<string[]>([]);
const recentTools = ref<{ path: string; name: string; at: number }[]>([]);
@@ -144,6 +161,9 @@ function removeBookmark(i: number) {
<div class="uc-sync" v-if="syncAt">
云端已同步 {{ fmtTime(syncAt) }}
</div>
<div class="uc-license" :class="licensed ? 'ok' : 'none'">
{{ licensed ? '✓ 授权已关联账号' : '未授权(试用中)' }}
</div>
</div>
<div
v-for="m in MENUS"
@@ -295,6 +315,24 @@ function removeBookmark(i: number) {
opacity: 0.5;
margin-top: 3px;
}
.uc-license {
display: inline-block;
margin-top: 7px;
font-size: 11.5px;
border-radius: 999px;
padding: 2px 12px;
&.ok {
color: #18a058;
background: rgba(24, 160, 88, 0.12);
}
&.none {
opacity: 0.55;
background: rgba(128, 128, 128, 0.12);
}
}
}
.uc-menu-item {
+14 -1
View File
@@ -162,9 +162,22 @@ export async function activateCard(cardKey: string, contactQq: string, replace =
licenseState.activateSuccess = false;
try {
// 走本站 relay:API Key 只存在服务端,且 relay 先用 /verify 预检卡密
// attach the logged-in account token so the card is bound to the account (follows across devices)
let authHeader = '';
try {
const auth = JSON.parse(localStorage.getItem('it-tools-auth') ?? 'null');
if (auth?.token) {
authHeader = `Bearer ${auth.token}`;
}
}
catch { /* ignore */ }
const actHeaders: Record<string, string> = { 'Content-Type': 'application/json' };
if (authHeader) {
actHeaders['Authorization'] = authHeader;
}
const res = await fetch('/relay/activate', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
headers: actHeaders,
body: JSON.stringify({
card_key: key,
machine_id: getMachineId(),