From 2d3ff21222fb8d59dad211225c9dd77766f3e1f0 Mon Sep 17 00:00:00 2001 From: TTlaji Date: Fri, 5 Jun 2026 16:56:30 +0800 Subject: [PATCH] feat: add activation-code auth --- admin.html | 42 +-- admin.js | 191 ++++++++++++-- app.js | 50 +--- auth.js | 127 ++++++++++ backend/auth.py | 99 ++++++++ backend/db.py | 232 +++++++++++++++++ backend/main.py | 239 ++++++++++++++++-- ...2026-06-05-speaking-lab-activation-auth.md | 95 +++++++ home.js | 46 +--- index.html | 14 +- login.html | 54 ++++ login.js | 101 ++++++++ study.html | 20 +- styles.css | 169 +++++++++++++ tests/auth-ui-helpers.test.mjs | 9 + tests/auth_helpers_test.py | 73 ++++++ tests/auth_routes_test.py | 141 +++++++++++ 17 files changed, 1566 insertions(+), 136 deletions(-) create mode 100644 auth.js create mode 100644 backend/auth.py create mode 100644 docs/superpowers/plans/2026-06-05-speaking-lab-activation-auth.md create mode 100644 login.html create mode 100644 login.js create mode 100644 tests/auth-ui-helpers.test.mjs create mode 100644 tests/auth_helpers_test.py create mode 100644 tests/auth_routes_test.py diff --git a/admin.html b/admin.html index d612109..cbbb26f 100644 --- a/admin.html +++ b/admin.html @@ -4,30 +4,22 @@ Speaking Lab 后台管理 - +

后台管理

-

请先使用管理员账号登录。

+

正在验证管理员账号...

- 返回学习页 +
+ 返回首页 + +
-
-

需要管理员账号

-

请输入 .env 中配置的管理员账号密码。

- - -
-
@@ -81,8 +73,28 @@
+ +
+
+

账号管理

+ +
+
+
+ +
+
+

激活卡密

+
+
+ + +
+
+
- + + diff --git a/admin.js b/admin.js index b7f30f9..6f4affa 100644 --- a/admin.js +++ b/admin.js @@ -4,12 +4,8 @@ const IS_BROWSER = typeof document !== "undefined"; const els = { identity: IS_BROWSER ? document.querySelector("#adminIdentity") : null, - locked: IS_BROWSER ? document.querySelector("#adminLocked") : null, content: IS_BROWSER ? document.querySelector("#adminContent") : null, - adminLoginForm: IS_BROWSER ? document.querySelector("#adminLoginForm") : null, - adminUsername: IS_BROWSER ? document.querySelector("#adminUsername") : null, - adminPassword: IS_BROWSER ? document.querySelector("#adminPassword") : null, - adminLoginMessage: IS_BROWSER ? document.querySelector("#adminLoginMessage") : null, + logoutBtn: IS_BROWSER ? document.querySelector("#adminLogoutBtn") : null, formTitle: IS_BROWSER ? document.querySelector("#adminFormTitle") : null, form: IS_BROWSER ? document.querySelector("#adminCreateForm") : null, submitBtn: IS_BROWSER ? document.querySelector("#adminSubmitBtn") : null, @@ -30,11 +26,18 @@ const els = { processAiSubtitlesBtn: IS_BROWSER ? document.querySelector("#processAiSubtitlesBtn") : null, generateLocalWhisperSubtitlesBtn: IS_BROWSER ? document.querySelector("#generateLocalWhisperSubtitlesBtn") : null, refreshBtn: IS_BROWSER ? document.querySelector("#refreshVideosBtn") : null, + refreshUsersBtn: IS_BROWSER ? document.querySelector("#refreshUsersBtn") : null, message: IS_BROWSER ? document.querySelector("#adminMessage") : null, videoList: IS_BROWSER ? document.querySelector("#adminVideoList") : null, + userList: IS_BROWSER ? document.querySelector("#adminUserList") : null, + activationCodeForm: IS_BROWSER ? document.querySelector("#activationCodeForm") : null, + activationCodeQuantity: IS_BROWSER ? document.querySelector("#activationCodeQuantity") : null, + activationCodeList: IS_BROWSER ? document.querySelector("#activationCodeList") : null, }; let videos = []; +let users = []; +let activationCodes = []; let editingVideo = null; let editableSubtitles = createEmptySubtitleEditState(); let adminCredentials = IS_BROWSER ? getStoredAdminCredentials(window.sessionStorage) : null; @@ -54,6 +57,9 @@ function loadState() { } async function apiRequest(path, options = {}) { + if (IS_BROWSER && window.SpeakingAuth) { + return window.SpeakingAuth.apiRequest(path, options); + } const response = await fetch(path, withAdminAuth(options)); if (!response.ok) { let message = "请求失败,请重试。"; @@ -68,26 +74,27 @@ async function apiRequest(path, options = {}) { return response.json(); } -function initializeAdmin() { - els.adminLoginForm?.addEventListener("submit", loginAdmin); +async function initializeAdmin() { els.form.addEventListener("submit", addVideo); els.refreshBtn.addEventListener("click", loadVideos); + els.refreshUsersBtn?.addEventListener("click", loadUsers); + els.activationCodeForm?.addEventListener("submit", generateActivationCodes); + els.logoutBtn?.addEventListener("click", () => window.SpeakingAuth.logout()); els.cancelEditBtn.addEventListener("click", resetFormMode); els.testAiBtn?.addEventListener("click", testAiConnection); els.processAiSubtitlesBtn?.addEventListener("click", processAiSubtitles); els.generateLocalWhisperSubtitlesBtn?.addEventListener("click", generateLocalWhisperSubtitles); bindFileInputs(); - if (adminCredentials) { - unlockAdmin(adminCredentials.username); - verifyStoredAdminCredentials(); - } else { - lockAdmin("请输入管理员账号密码。"); - } + + const user = await window.SpeakingAuth.requireSession({ adminOnly: true }); + if (!user) return; + unlockAdmin(user.username); } function lockAdmin(message = "") { + if (!els.content) return; els.identity.textContent = "未登录管理员账号"; - els.locked.hidden = false; + if (els.locked) els.locked.hidden = false; els.content.hidden = true; if (els.adminLoginMessage) { els.adminLoginMessage.hidden = !message; @@ -98,10 +105,11 @@ function lockAdmin(message = "") { function unlockAdmin(username) { els.identity.textContent = `${username} · 管理员`; - els.locked.hidden = true; els.content.hidden = false; loadAiStatus(); loadVideos(); + loadUsers(); + loadActivationCodes(); } async function loginAdmin(event) { @@ -452,6 +460,159 @@ function renderVideos() { els.videoList.appendChild(fragment); } +async function loadUsers() { + if (!els.userList) return; + els.userList.innerHTML = `
正在加载账号...
`; + try { + users = await apiRequest("/api/admin/users"); + renderUsers(); + } catch (error) { + els.userList.innerHTML = `
${error.message || "账号加载失败。"}
`; + } +} + +function renderUsers() { + if (!els.userList) return; + els.userList.innerHTML = ""; + if (!users.length) { + els.userList.innerHTML = `
还没有注册用户。
`; + return; + } + + const fragment = document.createDocumentFragment(); + users.forEach((user) => { + const item = document.createElement("article"); + const details = document.createElement("div"); + const action = document.createElement("button"); + item.className = "admin-user-item"; + details.innerHTML = ` +

+

+ `; + details.querySelector("h3").textContent = user.username; + details.querySelector("p").textContent = [ + user.role === "admin" ? "管理员" : "普通用户", + user.isActive ? "启用中" : "已停用", + user.lastLoginAt ? `最近登录 ${user.lastLoginAt}` : `创建于 ${user.createdAt || "-"}`, + ].join(" · "); + action.type = "button"; + action.className = user.isActive ? "danger-action" : "secondary-action"; + action.textContent = user.isActive ? "停用" : "启用"; + action.disabled = user.role === "admin"; + action.addEventListener("click", () => updateUserStatus(user, !user.isActive)); + item.append(details, action); + fragment.appendChild(item); + }); + els.userList.appendChild(fragment); +} + +async function updateUserStatus(user, isActive) { + try { + await apiRequest(`/api/admin/users/${user.id}`, { + method: "PATCH", + body: JSON.stringify({ isActive }), + }); + await loadUsers(); + } catch (error) { + showMessage(error.message || "账号状态更新失败。", true); + } +} + +async function loadActivationCodes() { + if (!els.activationCodeList) return; + els.activationCodeList.innerHTML = `
正在加载卡密...
`; + try { + activationCodes = await apiRequest("/api/admin/activation-codes"); + renderActivationCodes(); + } catch (error) { + els.activationCodeList.innerHTML = `
${error.message || "卡密加载失败。"}
`; + } +} + +async function generateActivationCodes(event) { + event.preventDefault(); + const quantity = Number(els.activationCodeQuantity.value) || 1; + try { + await apiRequest("/api/admin/activation-codes", { + method: "POST", + body: JSON.stringify({ quantity }), + }); + els.activationCodeQuantity.value = "1"; + await loadActivationCodes(); + } catch (error) { + showMessage(error.message || "卡密生成失败。", true); + } +} + +function renderActivationCodes() { + if (!els.activationCodeList) return; + els.activationCodeList.innerHTML = ""; + if (!activationCodes.length) { + els.activationCodeList.innerHTML = `
还没有激活卡密。
`; + return; + } + + const fragment = document.createDocumentFragment(); + activationCodes.forEach((code) => { + const item = document.createElement("article"); + const details = document.createElement("div"); + const actions = document.createElement("div"); + const copyButton = document.createElement("button"); + const deleteButton = document.createElement("button"); + const isUsed = code.status === "used"; + + item.className = "activation-code-item"; + details.innerHTML = ` +

+

+ `; + details.querySelector("h3").textContent = code.code; + details.querySelector("p").textContent = isUsed + ? `已使用 · ${code.usedByUsername || "-"} · ${code.usedAt || "-"}` + : `未使用 · 创建于 ${code.createdAt || "-"}`; + + actions.className = "admin-video-actions"; + copyButton.type = "button"; + copyButton.className = "secondary-action"; + copyButton.textContent = "复制"; + copyButton.addEventListener("click", () => copyActivationCode(code.code, copyButton)); + + deleteButton.type = "button"; + deleteButton.className = "danger-action"; + deleteButton.textContent = "删除"; + deleteButton.disabled = isUsed; + deleteButton.addEventListener("click", () => deleteActivationCode(code)); + + actions.append(copyButton, deleteButton); + item.append(details, actions); + fragment.appendChild(item); + }); + els.activationCodeList.appendChild(fragment); +} + +async function copyActivationCode(code, button) { + try { + await navigator.clipboard.writeText(code); + button.textContent = "已复制"; + window.setTimeout(() => { + button.textContent = "复制"; + }, 1200); + } catch { + showMessage(`卡密:${code}`, false); + } +} + +async function deleteActivationCode(code) { + const confirmed = window.confirm(`确定删除卡密 ${code.code} 吗?`); + if (!confirmed) return; + try { + await apiRequest(`/api/admin/activation-codes/${code.id}`, { method: "DELETE" }); + await loadActivationCodes(); + } catch (error) { + showMessage(error.message || "卡密删除失败。", true); + } +} + function formatTags(tags) { return Array.isArray(tags) && tags.length ? tags.join(" / ") : "未分类"; } diff --git a/app.js b/app.js index 449c3dd..285f4ae 100644 --- a/app.js +++ b/app.js @@ -5,9 +5,6 @@ const IS_BROWSER = typeof document !== "undefined"; const els = { video: IS_BROWSER ? document.querySelector("#video") : null, emptyVideo: IS_BROWSER ? document.querySelector("#emptyVideo") : null, - loginForm: IS_BROWSER ? document.querySelector("#loginForm") : null, - emailInput: IS_BROWSER ? document.querySelector("#emailInput") : null, - passwordInput: IS_BROWSER ? document.querySelector("#passwordInput") : null, userMenu: IS_BROWSER ? document.querySelector("#userMenu") : null, userLabel: IS_BROWSER ? document.querySelector("#userLabel") : null, logoutBtn: IS_BROWSER ? document.querySelector("#logoutBtn") : null, @@ -140,6 +137,7 @@ let hlsInstance = null; let libraryLoadMessage = ""; let lastProgressSaveAt = 0; let pendingRestoreProgress = null; +let currentSessionUser = null; async function apiRequest(path, options = {}) { const response = await fetch(path, options); @@ -187,6 +185,10 @@ if (IS_BROWSER) { } async function initializeApp() { + currentSessionUser = await window.SpeakingAuth.requireSession(); + if (!currentSessionUser) return; + ensureLocalUserForSession(currentSessionUser); + try { libraryLoadMessage = ""; const videos = await apiRequest("/api/videos"); @@ -214,17 +216,7 @@ async function initializeApp() { } function bindEvents() { - els.loginForm.addEventListener("submit", (event) => { - event.preventDefault(); - loginOrRegister(); - }); - els.logoutBtn.addEventListener("click", () => { - state.currentUserId = null; - saveState(); - renderAccount(); - renderSavedLists(); - renderVideoMeta(); - }); + els.logoutBtn.addEventListener("click", () => window.SpeakingAuth.logout()); els.searchInput?.addEventListener("input", renderLibrary); els.modeTabs.forEach((tab) => { tab.addEventListener("click", () => { @@ -268,18 +260,14 @@ function renderAll() { } function renderAccount() { - const user = getCurrentUser(); - els.loginForm.hidden = Boolean(user); - els.userMenu.hidden = !user; - if (user) { - els.userLabel.textContent = user.email; - } + els.userMenu.hidden = false; + els.userLabel.textContent = currentSessionUser?.username || ""; renderAdminAccess(); } function renderAdminAccess() { if (!els.adminEntryBtn) return; - els.adminEntryBtn.hidden = false; + els.adminEntryBtn.hidden = currentSessionUser?.role !== "admin"; } function renderLibrary() { @@ -650,34 +638,22 @@ function renderSavedNames(ids) { return ids.map((id) => getVideo(id)?.title).filter(Boolean).join("、"); } -function loginOrRegister() { - const email = els.emailInput.value.trim().toLowerCase(); - const password = els.passwordInput.value; - if (!email || !password) return; - +function ensureLocalUserForSession(sessionUser) { + const email = sessionUser.username; let user = state.users.find((item) => item.email === email); if (!user) { user = { - id: `user-${Date.now()}`, + id: `server-${sessionUser.id || email}`, email, - password, - role: "user", + role: sessionUser.role || "user", favorites: [], watchLater: [], progress: {}, }; state.users.push(user); - } else if (user.password !== password) { - alert("密码不匹配。"); - return; } - state.currentUserId = user.id; saveState(); - els.loginForm.reset(); - renderAccount(); - renderVideoMeta(); - renderSavedLists(); } async function startRecording() { diff --git a/auth.js b/auth.js new file mode 100644 index 0000000..31f3781 --- /dev/null +++ b/auth.js @@ -0,0 +1,127 @@ +(function () { + const IS_BROWSER = typeof window !== "undefined"; + const TOKEN_KEY = "speaking-lab-auth-token-v1"; + const USER_KEY = "speaking-lab-auth-user-v1"; + + function getToken() { + return window.sessionStorage.getItem(TOKEN_KEY) || ""; + } + + function getStoredUser() { + try { + return JSON.parse(window.sessionStorage.getItem(USER_KEY) || "null"); + } catch { + return null; + } + } + + function setSession(payload) { + if (!payload?.token || !payload?.user) return null; + window.sessionStorage.setItem(TOKEN_KEY, payload.token); + window.sessionStorage.setItem(USER_KEY, JSON.stringify(payload.user)); + return payload.user; + } + + function clearSession() { + window.sessionStorage.removeItem(TOKEN_KEY); + window.sessionStorage.removeItem(USER_KEY); + } + + function getLoginUrl() { + const current = `${window.location.pathname}${window.location.search}`; + return `./login.html?next=${encodeURIComponent(current)}`; + } + + async function apiRequest(path, options = {}) { + const headers = new Headers(options.headers || {}); + if (options.body && !(options.body instanceof FormData) && !headers.has("Content-Type")) { + headers.set("Content-Type", "application/json"); + } + const token = getToken(); + if (token) headers.set("Authorization", `Bearer ${token}`); + + const response = await fetch(path, { ...options, headers }); + if (!response.ok) { + let message = "请求失败,请重试。"; + try { + const payload = await response.json(); + message = payload.detail || message; + } catch { + message = response.statusText || message; + } + throw new Error(message); + } + return response.json(); + } + + async function login(username, password) { + const payload = await apiRequest("/api/auth/login", { + method: "POST", + body: JSON.stringify({ username, password }), + }); + setSession(payload); + return payload.user; + } + + async function register(activationCode, username, password) { + const payload = await apiRequest("/api/auth/register", { + method: "POST", + body: JSON.stringify({ activationCode, username, password }), + }); + setSession(payload); + return payload.user; + } + + async function requireSession(options = {}) { + const token = getToken(); + if (!token) { + if (options.redirect !== false) window.location.href = getLoginUrl(); + return null; + } + + try { + const payload = await apiRequest("/api/auth/session"); + setSession({ token, user: payload.user }); + if (options.adminOnly && payload.user.role !== "admin") { + if (options.redirect !== false) window.location.href = "./index.html"; + return null; + } + return payload.user; + } catch { + clearSession(); + if (options.redirect !== false) window.location.href = getLoginUrl(); + return null; + } + } + + function logout() { + clearSession(); + window.location.href = "./login.html"; + } + + if (IS_BROWSER) { + window.SpeakingAuth = { + apiRequest, + clearSession, + getLoginUrl, + getStoredUser, + getToken, + login, + logout, + register, + requireSession, + setSession, + }; + } + + if (typeof module !== "undefined" && module.exports) { + module.exports = { + getLoginUrlForPath(path) { + return `./login.html?next=${encodeURIComponent(path)}`; + }, + shouldShowAdminEntry(user) { + return user?.role === "admin"; + }, + }; + } +})(); diff --git a/backend/auth.py b/backend/auth.py new file mode 100644 index 0000000..6c7a8cd --- /dev/null +++ b/backend/auth.py @@ -0,0 +1,99 @@ +import base64 +import hashlib +import hmac +import json +import secrets +import time + + +PASSWORD_ALGORITHM = "pbkdf2_sha256" +PASSWORD_ITERATIONS = 120_000 +TOKEN_TTL_SECONDS = 60 * 60 * 24 * 7 + + +def _b64url_encode(value: bytes) -> str: + return base64.urlsafe_b64encode(value).decode("ascii").rstrip("=") + + +def _b64url_decode(value: str) -> bytes: + padding = "=" * (-len(value) % 4) + return base64.urlsafe_b64decode(value + padding) + + +def hash_password(password: str) -> str: + salt = secrets.token_hex(16) + digest = hashlib.pbkdf2_hmac( + "sha256", + password.encode("utf-8"), + salt.encode("ascii"), + PASSWORD_ITERATIONS, + ).hex() + return f"{PASSWORD_ALGORITHM}${PASSWORD_ITERATIONS}${salt}${digest}" + + +def verify_password(password: str, stored_hash: str) -> bool: + try: + algorithm, iterations_raw, salt, expected = stored_hash.split("$", 3) + iterations = int(iterations_raw) + except (ValueError, AttributeError): + return False + + if algorithm != PASSWORD_ALGORITHM: + return False + + actual = hashlib.pbkdf2_hmac( + "sha256", + password.encode("utf-8"), + salt.encode("ascii"), + iterations, + ).hex() + return hmac.compare_digest(actual, expected) + + +def create_auth_token(payload: dict[str, object], secret: str, ttl_seconds: int = TOKEN_TTL_SECONDS) -> str: + token_payload = { + **payload, + "exp": int(time.time()) + ttl_seconds, + } + payload_json = json.dumps(token_payload, separators=(",", ":"), sort_keys=True).encode("utf-8") + payload_part = _b64url_encode(payload_json) + signature = hmac.new(secret.encode("utf-8"), payload_part.encode("ascii"), hashlib.sha256).digest() + return f"{payload_part}.{_b64url_encode(signature)}" + + +def verify_auth_token(token: str, secret: str) -> dict[str, object] | None: + try: + payload_part, signature_part = token.split(".", 1) + except ValueError: + return None + + expected_signature = hmac.new( + secret.encode("utf-8"), + payload_part.encode("ascii"), + hashlib.sha256, + ).digest() + try: + actual_signature = _b64url_decode(signature_part) + except (ValueError, base64.binascii.Error): + return None + + if not hmac.compare_digest(actual_signature, expected_signature): + return None + + try: + payload = json.loads(_b64url_decode(payload_part).decode("utf-8")) + except (ValueError, UnicodeDecodeError): + return None + + if int(payload.get("exp") or 0) < int(time.time()): + return None + return payload if isinstance(payload, dict) else None + + +def normalize_username(username: str) -> str: + return username.strip().lower() + + +def generate_activation_code() -> str: + groups = [secrets.token_urlsafe(4).replace("-", "X").replace("_", "Y").upper()[:6] for _ in range(3)] + return "SL-" + "-".join(groups) diff --git a/backend/db.py b/backend/db.py index fb5b721..492536e 100644 --- a/backend/db.py +++ b/backend/db.py @@ -83,6 +83,31 @@ def initialize_database() -> None: } if "cover_url" not in video_columns: connection.execute("ALTER TABLE videos ADD COLUMN cover_url TEXT") + user_columns = { + row["name"] + for row in connection.execute("PRAGMA table_info(users)").fetchall() + } + if "is_active" not in user_columns: + connection.execute("ALTER TABLE users ADD COLUMN is_active INTEGER NOT NULL DEFAULT 1") + if "last_login_at" not in user_columns: + connection.execute("ALTER TABLE users ADD COLUMN last_login_at TEXT") + connection.executescript( + """ + CREATE TABLE IF NOT EXISTS activation_codes ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + code TEXT NOT NULL UNIQUE, + created_by TEXT NOT NULL, + used_by_user_id INTEGER, + created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP, + used_at TEXT, + status TEXT NOT NULL DEFAULT 'unused', + FOREIGN KEY (used_by_user_id) REFERENCES users (id) ON DELETE SET NULL + ); + + CREATE INDEX IF NOT EXISTS idx_activation_codes_status + ON activation_codes (status); + """ + ) connection.execute( """ DELETE FROM subtitles @@ -101,6 +126,213 @@ def initialize_database() -> None: ) +def row_to_user(row: sqlite3.Row) -> dict[str, object]: + return { + "id": row["id"], + "username": repair_mojibake_text(row["email"]), + "displayName": repair_mojibake_text(row["display_name"] or row["email"]), + "role": row["role"], + "isActive": bool(row["is_active"]), + "createdAt": row["created_at"], + "updatedAt": row["updated_at"], + "lastLoginAt": row["last_login_at"] or "", + } + + +def row_to_activation_code(row: sqlite3.Row) -> dict[str, object]: + return { + "id": row["id"], + "code": row["code"], + "createdBy": row["created_by"], + "status": row["status"], + "createdAt": row["created_at"], + "usedAt": row["used_at"] or "", + "usedByUserId": row["used_by_user_id"], + "usedByUsername": repair_mojibake_text(row["used_by_username"] or ""), + } + + +def get_user_by_username(username: str) -> dict[str, object] | None: + with get_connection() as connection: + row = connection.execute( + """ + SELECT * + FROM users + WHERE email = ? + """, + (repair_mojibake_text(username),), + ).fetchone() + return row_to_user(row) if row else None + + +def get_user_auth_record(username: str) -> sqlite3.Row | None: + with get_connection() as connection: + return connection.execute( + """ + SELECT * + FROM users + WHERE email = ? + """, + (repair_mojibake_text(username),), + ).fetchone() + + +def get_user_by_id(user_id: int) -> dict[str, object] | None: + with get_connection() as connection: + row = connection.execute( + """ + SELECT * + FROM users + WHERE id = ? + """, + (user_id,), + ).fetchone() + return row_to_user(row) if row else None + + +def list_users() -> list[dict[str, object]]: + with get_connection() as connection: + rows = connection.execute( + """ + SELECT * + FROM users + ORDER BY created_at DESC, id DESC + """ + ).fetchall() + return [row_to_user(row) for row in rows] + + +def update_user_active(user_id: int, is_active: bool) -> dict[str, object] | None: + with get_connection() as connection: + cursor = connection.execute( + """ + UPDATE users + SET is_active = ?, + updated_at = CURRENT_TIMESTAMP + WHERE id = ? + AND role != 'admin' + """, + (1 if is_active else 0, user_id), + ) + if cursor.rowcount == 0: + return None + return get_user_by_id(user_id) + + +def mark_user_login(user_id: int) -> None: + with get_connection() as connection: + connection.execute( + """ + UPDATE users + SET last_login_at = CURRENT_TIMESTAMP, + updated_at = CURRENT_TIMESTAMP + WHERE id = ? + """, + (user_id,), + ) + + +def register_user_with_activation(*, username: str, password_hash: str, activation_code: str) -> dict[str, object]: + clean_username = repair_mojibake_text(username) + clean_code = activation_code.strip().upper() + with get_connection() as connection: + code_row = connection.execute( + """ + SELECT * + FROM activation_codes + WHERE code = ? + AND status = 'unused' + """, + (clean_code,), + ).fetchone() + if code_row is None: + raise ValueError("activation_code_unavailable") + + try: + cursor = connection.execute( + """ + INSERT INTO users ( + email, password_hash, display_name, role, is_active + ) + VALUES (?, ?, ?, 'user', 1) + """, + (clean_username, password_hash, clean_username), + ) + except sqlite3.IntegrityError as exc: + raise ValueError("username_exists") from exc + + user_id = int(cursor.lastrowid) + connection.execute( + """ + UPDATE activation_codes + SET status = 'used', + used_by_user_id = ?, + used_at = CURRENT_TIMESTAMP + WHERE id = ? + """, + (user_id, code_row["id"]), + ) + + user = get_user_by_id(user_id) + if user is None: + raise RuntimeError("Registered user could not be loaded") + return user + + +def create_activation_codes(codes: list[str], created_by: str) -> list[dict[str, object]]: + created_ids: list[int] = [] + with get_connection() as connection: + for code in codes: + cursor = connection.execute( + """ + INSERT INTO activation_codes (code, created_by) + VALUES (?, ?) + """, + (code, created_by), + ) + created_ids.append(int(cursor.lastrowid)) + + with get_connection() as connection: + placeholders = ",".join("?" for _ in created_ids) + rows = connection.execute( + f""" + SELECT activation_codes.*, users.email AS used_by_username + FROM activation_codes + LEFT JOIN users ON users.id = activation_codes.used_by_user_id + WHERE activation_codes.id IN ({placeholders}) + ORDER BY activation_codes.id DESC + """, + created_ids, + ).fetchall() + return [row_to_activation_code(row) for row in rows] + + +def list_activation_codes() -> list[dict[str, object]]: + with get_connection() as connection: + rows = connection.execute( + """ + SELECT activation_codes.*, users.email AS used_by_username + FROM activation_codes + LEFT JOIN users ON users.id = activation_codes.used_by_user_id + ORDER BY activation_codes.created_at DESC, activation_codes.id DESC + """ + ).fetchall() + return [row_to_activation_code(row) for row in rows] + + +def delete_unused_activation_code(code_id: int) -> bool: + with get_connection() as connection: + cursor = connection.execute( + """ + DELETE FROM activation_codes + WHERE id = ? + AND status = 'unused' + """, + (code_id,), + ) + return cursor.rowcount > 0 + + def repair_mojibake_text(value: str | None) -> str: if not value: return "" diff --git a/backend/main.py b/backend/main.py index ca54987..1aeaced 100644 --- a/backend/main.py +++ b/backend/main.py @@ -4,20 +4,38 @@ from urllib.parse import urlparse from uuid import uuid4 from fastapi import Depends, FastAPI, File, Form, HTTPException, UploadFile +from pydantic import BaseModel from fastapi.responses import FileResponse -from fastapi.security import HTTPBasic, HTTPBasicCredentials +from fastapi.security import HTTPAuthorizationCredentials, HTTPBasic, HTTPBasicCredentials, HTTPBearer from fastapi.staticfiles import StaticFiles from .ai_config import get_ai_status, get_config_value, load_local_whisper_config, load_text_ai_config +from .auth import ( + create_auth_token, + generate_activation_code, + hash_password, + normalize_username, + verify_auth_token, + verify_password, +) from .db import ( DATABASE_PATH, + create_activation_codes, create_video, delete_video, + delete_unused_activation_code, + get_user_auth_record, + get_user_by_id, initialize_database, + list_activation_codes, + list_users, list_videos, + mark_user_login, parse_tags, + register_user_with_activation, table_names, get_video, + update_user_active, update_video, upsert_video_subtitle, ) @@ -134,6 +152,26 @@ ensure_upload_directories() app = FastAPI(title="Speaking Lab API") admin_security = HTTPBasic(auto_error=False) +bearer_security = HTTPBearer(auto_error=False) + + +class LoginRequest(BaseModel): + username: str + password: str + + +class RegisterRequest(BaseModel): + activationCode: str + username: str + password: str + + +class GenerateActivationCodesRequest(BaseModel): + quantity: int = 1 + + +class UpdateUserStatusRequest(BaseModel): + isActive: bool @app.on_event("startup") @@ -167,7 +205,126 @@ def api_get_video(video_id: int) -> dict[str, object]: return video -def require_admin(credentials: HTTPBasicCredentials | None = Depends(admin_security)) -> dict[str, str]: +def get_token_secret() -> str: + configured = get_config_value("AUTH_SECRET") + if configured: + return configured + admin_password = get_config_value("ADMIN_PASSWORD") + return admin_password or "speaking-lab-development-secret" + + +def build_user_response(username: str, role: str, user_id: int | None = None) -> dict[str, object]: + return { + "id": user_id, + "username": username, + "role": role, + } + + +def create_session_payload(username: str, role: str, user_id: int | None = None) -> dict[str, object]: + token = create_auth_token( + { + "username": username, + "role": role, + "userId": user_id, + }, + get_token_secret(), + ) + return { + "token": token, + "user": build_user_response(username, role, user_id), + } + + +def validate_bearer_session(token: str) -> dict[str, object] | None: + payload = verify_auth_token(token, get_token_secret()) + if not payload: + return None + + role = str(payload.get("role") or "") + username = str(payload.get("username") or "") + if role == "admin" and username: + return build_user_response(username, "admin", None) + + user_id = int(payload.get("userId") or 0) + user = get_user_by_id(user_id) if user_id else None + if not user or not user["isActive"]: + return None + if user["username"] != username: + return None + return build_user_response(str(user["username"]), str(user["role"]), int(user["id"])) + + +def require_session(credentials: HTTPAuthorizationCredentials | None = Depends(bearer_security)) -> dict[str, object]: + if credentials is None: + raise HTTPException(status_code=401, detail="请先登录。") + + session = validate_bearer_session(credentials.credentials) + if session is None: + raise HTTPException(status_code=401, detail="登录已失效,请重新登录。") + return session + + +@app.post("/api/auth/login") +def api_auth_login(request: LoginRequest) -> dict[str, object]: + username = normalize_username(request.username) + password = request.password + if not username or not password: + raise HTTPException(status_code=400, detail="请输入账号和密码。") + + admin_username = normalize_username(get_config_value("ADMIN_USERNAME")) + admin_password = get_config_value("ADMIN_PASSWORD") + if admin_username and admin_password and username == admin_username: + if not secrets.compare_digest(password, admin_password): + raise HTTPException(status_code=401, detail="账号或密码错误。") + return create_session_payload(admin_username, "admin") + + user = get_user_auth_record(username) + if user is None or not verify_password(password, user["password_hash"]): + raise HTTPException(status_code=401, detail="账号或密码错误。") + if not bool(user["is_active"]): + raise HTTPException(status_code=403, detail="账号已停用,请联系管理员。") + + mark_user_login(int(user["id"])) + return create_session_payload(str(user["email"]), str(user["role"]), int(user["id"])) + + +@app.post("/api/auth/register") +def api_auth_register(request: RegisterRequest) -> dict[str, object]: + username = normalize_username(request.username) + password = request.password + activation_code = request.activationCode.strip().upper() + if not activation_code: + raise HTTPException(status_code=400, detail="请输入激活卡密。") + if not username or not password: + raise HTTPException(status_code=400, detail="请输入账号和密码。") + if len(password) < 6: + raise HTTPException(status_code=400, detail="密码至少需要 6 位。") + + try: + user = register_user_with_activation( + username=username, + password_hash=hash_password(password), + activation_code=activation_code, + ) + except ValueError as error: + if str(error) == "username_exists": + raise HTTPException(status_code=409, detail="账号已存在。") from error + raise HTTPException(status_code=400, detail="激活卡密无效或已被使用。") from error + + mark_user_login(int(user["id"])) + return create_session_payload(str(user["username"]), str(user["role"]), int(user["id"])) + + +@app.get("/api/auth/session") +def api_auth_session(session: dict[str, object] = Depends(require_session)) -> dict[str, object]: + return {"ok": True, "user": session} + + +def require_admin( + credentials: HTTPBasicCredentials | None = Depends(admin_security), + bearer: HTTPAuthorizationCredentials | None = Depends(bearer_security), +) -> dict[str, str]: admin_username = get_config_value("ADMIN_USERNAME") admin_password = get_config_value("ADMIN_PASSWORD") @@ -177,26 +334,76 @@ def require_admin(credentials: HTTPBasicCredentials | None = Depends(admin_secur detail="未配置 ADMIN_USERNAME / ADMIN_PASSWORD,请先在 .env 中填写管理员账号密码。", ) - if credentials is None: - raise HTTPException( - status_code=401, - detail="需要管理员账号密码。", - ) + if credentials is not None: + username_ok = secrets.compare_digest(credentials.username, admin_username) + password_ok = secrets.compare_digest(credentials.password, admin_password) + if username_ok and password_ok: + return {"username": admin_username, "role": "admin"} - username_ok = secrets.compare_digest(credentials.username, admin_username) - password_ok = secrets.compare_digest(credentials.password, admin_password) - if not username_ok or not password_ok: - raise HTTPException( - status_code=401, - detail="管理员账号或密码错误。", - ) + if bearer is not None and hasattr(bearer, "credentials"): + session = validate_bearer_session(bearer.credentials) + if session and session["role"] == "admin": + return {"username": str(session["username"]), "role": "admin"} - return {"username": admin_username} + raise HTTPException( + status_code=401, + detail="需要管理员账号。", + ) @app.get("/api/admin/session") def api_admin_session(admin: dict[str, str] = Depends(require_admin)) -> dict[str, object]: - return {"ok": True, "username": admin["username"]} + return {"ok": True, "username": admin["username"], "role": "admin"} + + +@app.get("/api/admin/users") +def api_admin_users(admin: dict[str, str] = Depends(require_admin)) -> list[dict[str, object]]: + return list_users() + + +@app.patch("/api/admin/users/{user_id}") +def api_admin_update_user( + user_id: int, + request: UpdateUserStatusRequest, + admin: dict[str, str] = Depends(require_admin), +) -> dict[str, object]: + user = update_user_active(user_id, request.isActive) + if user is None: + raise HTTPException(status_code=404, detail="用户不存在,或不能修改管理员账号。") + return {"ok": True, "user": user} + + +@app.get("/api/admin/activation-codes") +def api_admin_activation_codes(admin: dict[str, str] = Depends(require_admin)) -> list[dict[str, object]]: + return list_activation_codes() + + +@app.post("/api/admin/activation-codes") +def api_admin_create_activation_codes( + request: GenerateActivationCodesRequest, + admin: dict[str, str] = Depends(require_admin), +) -> dict[str, object]: + if request.quantity < 1 or request.quantity > 100: + raise HTTPException(status_code=400, detail="一次只能生成 1 到 100 个卡密。") + + codes: list[str] = [] + while len(codes) < request.quantity: + code = generate_activation_code() + if code not in codes: + codes.append(code) + + created = create_activation_codes(codes, admin["username"]) + return {"ok": True, "codes": created} + + +@app.delete("/api/admin/activation-codes/{code_id}") +def api_admin_delete_activation_code( + code_id: int, + admin: dict[str, str] = Depends(require_admin), +) -> dict[str, object]: + if not delete_unused_activation_code(code_id): + raise HTTPException(status_code=400, detail="已使用的卡密不能删除。") + return {"ok": True, "deletedCodeId": code_id} @app.post("/api/videos") diff --git a/docs/superpowers/plans/2026-06-05-speaking-lab-activation-auth.md b/docs/superpowers/plans/2026-06-05-speaking-lab-activation-auth.md new file mode 100644 index 0000000..b3f3b72 --- /dev/null +++ b/docs/superpowers/plans/2026-06-05-speaking-lab-activation-auth.md @@ -0,0 +1,95 @@ +# Speaking Lab Activation Auth Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** Add activation-code registration, server-backed login, admin-only account/code management, and gated access to the learning pages. + +**Architecture:** Reuse FastAPI and SQLite. Add focused auth helpers in `backend/auth.py`, extend `backend/db.py` for users and activation codes, expose auth/admin APIs in `backend/main.py`, then replace local fake login in frontend with a shared `auth.js` module and a new `login.html/login.js`. + +**Tech Stack:** FastAPI, SQLite, plain HTML/CSS/JavaScript, Node syntax checks, Python compile checks. + +--- + +### Task 1: Backend Auth Storage And Helpers + +**Files:** +- Create: `backend/auth.py` +- Modify: `backend/db.py` +- Test: `tests/auth_helpers_test.py` + +- [ ] Add SQLite columns `users.is_active` and `users.last_login_at` in `initialize_database`. +- [ ] Add `activation_codes` table and indexes in `initialize_database`. +- [ ] Add user CRUD helpers, activation code helpers, and password hashing helpers. +- [ ] Add signed token helpers in `backend/auth.py`. +- [ ] Add focused Python tests for password hashing, token roundtrip, user creation, activation code use, and disabled user behavior. + +### Task 2: Backend Auth And Admin APIs + +**Files:** +- Modify: `backend/main.py` +- Test: `tests/auth_routes_test.py` + +- [ ] Add Pydantic request models for login, register, code generation, and user status changes. +- [ ] Add `POST /api/auth/login`, `POST /api/auth/register`, and `GET /api/auth/session`. +- [ ] Extend admin dependency to accept either current HTTP Basic admin credentials or `Authorization: Bearer ` with admin role. +- [ ] Add `GET /api/admin/users`, `PATCH /api/admin/users/{user_id}`, `GET /api/admin/activation-codes`, `POST /api/admin/activation-codes`, and `DELETE /api/admin/activation-codes/{code_id}`. +- [ ] Add route tests for normal login, admin login, registration with activation code, reused code rejection, normal-user admin rejection, and admin code generation. + +### Task 3: Shared Frontend Auth And Login Page + +**Files:** +- Create: `auth.js` +- Create: `login.html` +- Create: `login.js` +- Modify: `styles.css` +- Test: `tests/auth-ui-helpers.test.mjs` + +- [ ] Add browser auth helpers for token storage, session check, logout, and authenticated fetch. +- [ ] Build the centered login/register page inspired by the reference HTML. +- [ ] Add login/register UI logic and frontend password confirmation checks. +- [ ] Add CSS for the auth page card, form fields, mode switching, and messages. +- [ ] Add Node tests for pure auth helper functions where practical. + +### Task 4: Gate Home And Study Pages + +**Files:** +- Modify: `index.html` +- Modify: `home.js` +- Modify: `study.html` +- Modify: `app.js` +- Modify: `styles.css` + +- [ ] Remove inline email login/register forms. +- [ ] Load `auth.js` before page scripts. +- [ ] Require a valid session before rendering home/study content. +- [ ] Show username and logout in the top bar. +- [ ] Show backend/admin entry only for admin users. +- [ ] Remove duplicate study-entry control from the study-side/right-side area. +- [ ] Keep existing browser-local learning progress data intact. + +### Task 5: Admin Account And Activation Code UI + +**Files:** +- Modify: `admin.html` +- Modify: `admin.js` +- Modify: `styles.css` +- Test: existing admin Node tests plus syntax checks + +- [ ] Switch admin session to the shared bearer-token auth flow while keeping existing Basic helper functions exportable for tests if needed. +- [ ] Add account management panel with user status rows and enable/disable buttons. +- [ ] Add activation code panel with quantity input, generated code list, copy buttons, used status, and unused delete buttons. +- [ ] Ensure material upload/edit/delete continues to use authenticated admin requests. + +### Task 6: Verification, Commit, Push + +**Files:** +- All changed files + +- [ ] Run Python compile checks. +- [ ] Run backend route/helper tests. +- [ ] Run Node syntax checks. +- [ ] Run existing Node helper tests. +- [ ] Start local server and smoke-test login, admin code generation, registration, normal-user blocking, and admin material page access. +- [ ] Commit implementation. +- [ ] Push to `origin feature/deepseek-subtitle-ai`. + diff --git a/home.js b/home.js index 878633e..bc840c5 100644 --- a/home.js +++ b/home.js @@ -2,9 +2,6 @@ const STORAGE_KEY = "speaking-lab-state-v1"; const els = { searchInput: document.querySelector("#homeSearchInput"), - loginForm: document.querySelector("#homeLoginForm"), - emailInput: document.querySelector("#homeEmailInput"), - passwordInput: document.querySelector("#homePasswordInput"), userMenu: document.querySelector("#homeUserMenu"), userLabel: document.querySelector("#homeUserLabel"), logoutBtn: document.querySelector("#homeLogoutBtn"), @@ -20,25 +17,20 @@ let state = loadState(); let videos = []; let activeTag = "全部"; let activeStatus = "all"; +let currentSessionUser = null; bindEvents(); initializeHome(); function bindEvents() { els.searchInput.addEventListener("input", renderHome); - els.loginForm.addEventListener("submit", (event) => { - event.preventDefault(); - loginOrRegister(); - }); - els.logoutBtn.addEventListener("click", () => { - state.currentUserId = null; - saveState(); - renderAccount(); - renderHome(); - }); + els.logoutBtn.addEventListener("click", () => window.SpeakingAuth.logout()); } async function initializeHome() { + currentSessionUser = await window.SpeakingAuth.requireSession(); + if (!currentSessionUser) return; + ensureLocalUserForSession(currentSessionUser); renderAccount(); els.status.textContent = "正在加载素材..."; @@ -369,41 +361,29 @@ function getCoverTone(id) { } function renderAccount() { - const user = getCurrentUser(); - els.loginForm.hidden = Boolean(user); - els.userMenu.hidden = !user; - if (user) { - els.userLabel.textContent = user.email; + els.userMenu.hidden = false; + els.userLabel.textContent = currentSessionUser?.username || ""; + if (els.adminLink) { + els.adminLink.hidden = currentSessionUser?.role !== "admin"; } } -function loginOrRegister() { - const email = els.emailInput.value.trim().toLowerCase(); - const password = els.passwordInput.value; - if (!email || !password) return; - +function ensureLocalUserForSession(sessionUser) { + const email = sessionUser.username; let user = state.users.find((item) => item.email === email); if (!user) { user = { - id: `user-${Date.now()}`, + id: `server-${sessionUser.id || email}`, email, - password, - role: "user", + role: sessionUser.role || "user", favorites: [], watchLater: [], progress: {}, }; state.users.push(user); - } else if (user.password !== password) { - alert("密码不匹配。"); - return; } - state.currentUserId = user.id; saveState(); - els.loginForm.reset(); - renderAccount(); - renderHome(); } function toggleFavorite(videoId) { diff --git a/index.html b/index.html index 65817cc..7572936 100644 --- a/index.html +++ b/index.html @@ -4,7 +4,7 @@ Speaking Lab - +
@@ -14,13 +14,8 @@
- - 后台 -
- -