This commit is contained in:
1 parent
8f3fd04618
commit
2d3ff21222
17 files changed
+1566
-136
No files matched your search
+27
-15
@@ -4,30 +4,22 @@
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>Speaking Lab 后台管理</title>
|
||||
<link rel="stylesheet" href="./styles.css?v=20260604-admin-polish">
|
||||
<link rel="stylesheet" href="./styles.css?v=20260605-auth">
|
||||
</head>
|
||||
<body class="admin-page">
|
||||
<header class="topbar admin-topbar">
|
||||
<div class="brand">
|
||||
<div>
|
||||
<h1>后台管理</h1>
|
||||
<p id="adminIdentity">请先使用管理员账号登录。</p>
|
||||
<p id="adminIdentity">正在验证管理员账号...</p>
|
||||
</div>
|
||||
</div>
|
||||
<a class="secondary-action" href="./index.html">返回学习页</a>
|
||||
<div class="top-actions">
|
||||
<a class="secondary-action" href="./index.html">返回首页</a>
|
||||
<button id="adminLogoutBtn" type="button">退出</button>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<main id="adminLocked" class="admin-locked empty-state" hidden>
|
||||
<h2>需要管理员账号</h2>
|
||||
<p>请输入 .env 中配置的管理员账号密码。</p>
|
||||
<form id="adminLoginForm" class="admin-login-form">
|
||||
<input id="adminUsername" type="text" placeholder="管理员账号" autocomplete="username" required>
|
||||
<input id="adminPassword" type="password" placeholder="管理员密码" autocomplete="current-password" required>
|
||||
<button type="submit">登录后台</button>
|
||||
</form>
|
||||
<p id="adminLoginMessage" class="admin-message" hidden></p>
|
||||
</main>
|
||||
|
||||
<main id="adminContent" class="admin-shell" hidden>
|
||||
<section class="admin-panel">
|
||||
<div class="admin-form-heading">
|
||||
@@ -81,8 +73,28 @@
|
||||
<div id="adminMessage" class="admin-message" hidden></div>
|
||||
<div id="adminVideoList" class="admin-video-list"></div>
|
||||
</section>
|
||||
|
||||
<section class="admin-panel">
|
||||
<div class="admin-list-heading">
|
||||
<h2>账号管理</h2>
|
||||
<button id="refreshUsersBtn" class="secondary-action" type="button">刷新</button>
|
||||
</div>
|
||||
<div id="adminUserList" class="admin-user-list"></div>
|
||||
</section>
|
||||
|
||||
<section class="admin-panel">
|
||||
<div class="admin-list-heading">
|
||||
<h2>激活卡密</h2>
|
||||
</div>
|
||||
<form id="activationCodeForm" class="activation-code-form">
|
||||
<input id="activationCodeQuantity" type="number" min="1" max="100" value="1" aria-label="生成数量">
|
||||
<button type="submit">生成卡密</button>
|
||||
</form>
|
||||
<div id="activationCodeList" class="activation-code-list"></div>
|
||||
</section>
|
||||
</main>
|
||||
|
||||
<script src="./admin.js?v=20260604-admin-polish"></script>
|
||||
<script src="./auth.js?v=20260605-auth"></script>
|
||||
<script src="./admin.js?v=20260605-auth"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -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 = `<div class="empty-state">正在加载账号...</div>`;
|
||||
try {
|
||||
users = await apiRequest("/api/admin/users");
|
||||
renderUsers();
|
||||
} catch (error) {
|
||||
els.userList.innerHTML = `<div class="empty-state">${error.message || "账号加载失败。"}</div>`;
|
||||
}
|
||||
}
|
||||
|
||||
function renderUsers() {
|
||||
if (!els.userList) return;
|
||||
els.userList.innerHTML = "";
|
||||
if (!users.length) {
|
||||
els.userList.innerHTML = `<div class="empty-state">还没有注册用户。</div>`;
|
||||
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 = `
|
||||
<h3></h3>
|
||||
<p></p>
|
||||
`;
|
||||
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 = `<div class="empty-state">正在加载卡密...</div>`;
|
||||
try {
|
||||
activationCodes = await apiRequest("/api/admin/activation-codes");
|
||||
renderActivationCodes();
|
||||
} catch (error) {
|
||||
els.activationCodeList.innerHTML = `<div class="empty-state">${error.message || "卡密加载失败。"}</div>`;
|
||||
}
|
||||
}
|
||||
|
||||
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 = `<div class="empty-state">还没有激活卡密。</div>`;
|
||||
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 = `
|
||||
<h3></h3>
|
||||
<p></p>
|
||||
`;
|
||||
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(" / ") : "未分类";
|
||||
}
|
||||
|
||||
@@ -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() {
|
||||
|
||||
@@ -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";
|
||||
},
|
||||
};
|
||||
}
|
||||
})();
|
||||
@@ -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)
|
||||
+232
@@ -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 ""
|
||||
|
||||
+223
-16
@@ -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")
|
||||
|
||||
@@ -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 <token>` 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`.
|
||||
|
||||
@@ -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) {
|
||||
|
||||
+5
-9
@@ -4,7 +4,7 @@
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>Speaking Lab</title>
|
||||
<link rel="stylesheet" href="./styles.css?v=20260604-plan-card">
|
||||
<link rel="stylesheet" href="./styles.css?v=20260605-auth">
|
||||
</head>
|
||||
<body class="home-page">
|
||||
<header class="topbar home-topbar">
|
||||
@@ -14,13 +14,8 @@
|
||||
|
||||
<div class="top-actions">
|
||||
<input id="homeSearchInput" class="search-input home-search" type="search" placeholder="搜索素材、演讲者、标签">
|
||||
<form id="homeLoginForm" class="login-form">
|
||||
<input id="homeEmailInput" type="email" placeholder="邮箱" autocomplete="email" required>
|
||||
<input id="homePasswordInput" type="password" placeholder="密码" autocomplete="current-password" required>
|
||||
<button id="homeLoginBtn" type="submit">登录 / 注册</button>
|
||||
</form>
|
||||
<a id="homeAdminLink" class="secondary-action" href="./admin.html">后台</a>
|
||||
<div id="homeUserMenu" class="user-menu" hidden>
|
||||
<a id="homeAdminLink" class="secondary-action" href="./admin.html" hidden>后台</a>
|
||||
<div id="homeUserMenu" class="user-menu">
|
||||
<span id="homeUserLabel"></span>
|
||||
<button id="homeLogoutBtn" type="button">退出</button>
|
||||
</div>
|
||||
@@ -54,6 +49,7 @@
|
||||
</section>
|
||||
</main>
|
||||
|
||||
<script src="./home.js?v=20260604-plan-card"></script>
|
||||
<script src="./auth.js?v=20260605-auth"></script>
|
||||
<script src="./home.js?v=20260605-auth"></script>
|
||||
</body>
|
||||
</html>
|
||||
+54
@@ -0,0 +1,54 @@
|
||||
<!doctype html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>登录 Speaking Lab</title>
|
||||
<link rel="stylesheet" href="./styles.css?v=20260605-auth">
|
||||
</head>
|
||||
<body class="auth-page">
|
||||
<main class="auth-shell">
|
||||
<section class="auth-card" aria-labelledby="authTitle">
|
||||
<div class="auth-heading">
|
||||
<h1 id="authTitle">登录 Speaking Lab</h1>
|
||||
<p>真实语料学英语</p>
|
||||
</div>
|
||||
|
||||
<form id="authForm" class="auth-form">
|
||||
<label id="activationCodeField" hidden>
|
||||
<span>激活卡密</span>
|
||||
<input id="activationCodeInput" type="text" autocomplete="one-time-code" spellcheck="false">
|
||||
</label>
|
||||
<label>
|
||||
<span>账号</span>
|
||||
<input id="usernameInput" type="text" autocomplete="username" autocapitalize="off" autocorrect="off" spellcheck="false" required>
|
||||
</label>
|
||||
<label>
|
||||
<span>密码</span>
|
||||
<input id="passwordInput" type="password" autocomplete="current-password" required>
|
||||
</label>
|
||||
<label id="confirmPasswordField" hidden>
|
||||
<span>确认密码</span>
|
||||
<input id="confirmPasswordInput" type="password" autocomplete="new-password">
|
||||
</label>
|
||||
<button id="authSubmitBtn" type="submit">登录</button>
|
||||
</form>
|
||||
|
||||
<p id="authMessage" class="auth-message" hidden></p>
|
||||
|
||||
<div class="auth-links">
|
||||
<button id="switchToLoginBtn" type="button" hidden>已有账号,去登录</button>
|
||||
<span id="authDivider" aria-hidden="true">|</span>
|
||||
<button id="switchToRegisterBtn" type="button">立即注册</button>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<footer class="auth-footer">
|
||||
<span>Speaking Lab</span>
|
||||
</footer>
|
||||
</main>
|
||||
|
||||
<script src="./auth.js?v=20260605-auth"></script>
|
||||
<script src="./login.js?v=20260605-auth"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,101 @@
|
||||
const els = {
|
||||
title: document.querySelector("#authTitle"),
|
||||
form: document.querySelector("#authForm"),
|
||||
activationCodeField: document.querySelector("#activationCodeField"),
|
||||
activationCodeInput: document.querySelector("#activationCodeInput"),
|
||||
usernameInput: document.querySelector("#usernameInput"),
|
||||
passwordInput: document.querySelector("#passwordInput"),
|
||||
confirmPasswordField: document.querySelector("#confirmPasswordField"),
|
||||
confirmPasswordInput: document.querySelector("#confirmPasswordInput"),
|
||||
submitBtn: document.querySelector("#authSubmitBtn"),
|
||||
message: document.querySelector("#authMessage"),
|
||||
switchToLoginBtn: document.querySelector("#switchToLoginBtn"),
|
||||
switchToRegisterBtn: document.querySelector("#switchToRegisterBtn"),
|
||||
divider: document.querySelector("#authDivider"),
|
||||
};
|
||||
|
||||
let mode = "login";
|
||||
|
||||
bindEvents();
|
||||
initializeLoginPage();
|
||||
|
||||
function bindEvents() {
|
||||
els.form.addEventListener("submit", handleSubmit);
|
||||
els.switchToLoginBtn.addEventListener("click", () => setMode("login"));
|
||||
els.switchToRegisterBtn.addEventListener("click", () => setMode("register"));
|
||||
}
|
||||
|
||||
async function initializeLoginPage() {
|
||||
const user = await window.SpeakingAuth.requireSession({ redirect: false });
|
||||
if (user) {
|
||||
goNext(user);
|
||||
}
|
||||
}
|
||||
|
||||
function setMode(nextMode) {
|
||||
mode = nextMode;
|
||||
const isRegister = mode === "register";
|
||||
els.title.textContent = isRegister ? "注册 Speaking Lab" : "登录 Speaking Lab";
|
||||
els.activationCodeField.hidden = !isRegister;
|
||||
els.confirmPasswordField.hidden = !isRegister;
|
||||
els.activationCodeInput.required = isRegister;
|
||||
els.confirmPasswordInput.required = isRegister;
|
||||
els.passwordInput.autocomplete = isRegister ? "new-password" : "current-password";
|
||||
els.submitBtn.textContent = isRegister ? "激活并注册" : "登录";
|
||||
els.switchToLoginBtn.hidden = !isRegister;
|
||||
els.switchToRegisterBtn.hidden = isRegister;
|
||||
els.divider.hidden = isRegister;
|
||||
clearMessage();
|
||||
}
|
||||
|
||||
async function handleSubmit(event) {
|
||||
event.preventDefault();
|
||||
clearMessage();
|
||||
|
||||
const username = els.usernameInput.value.trim();
|
||||
const password = els.passwordInput.value;
|
||||
const activationCode = els.activationCodeInput.value.trim();
|
||||
const confirmPassword = els.confirmPasswordInput.value;
|
||||
|
||||
if (mode === "register" && password !== confirmPassword) {
|
||||
showMessage("两次输入的密码不一致。", true);
|
||||
return;
|
||||
}
|
||||
|
||||
els.submitBtn.disabled = true;
|
||||
els.submitBtn.textContent = mode === "register" ? "正在注册..." : "正在登录...";
|
||||
|
||||
try {
|
||||
const user = mode === "register"
|
||||
? await window.SpeakingAuth.register(activationCode, username, password)
|
||||
: await window.SpeakingAuth.login(username, password);
|
||||
goNext(user);
|
||||
} catch (error) {
|
||||
showMessage(error.message || "操作失败,请重试。", true);
|
||||
} finally {
|
||||
els.submitBtn.disabled = false;
|
||||
els.submitBtn.textContent = mode === "register" ? "激活并注册" : "登录";
|
||||
}
|
||||
}
|
||||
|
||||
function goNext(user) {
|
||||
const params = new URLSearchParams(window.location.search);
|
||||
const next = params.get("next") || "./index.html";
|
||||
if (next.includes("admin.html") && user.role !== "admin") {
|
||||
window.location.href = "./index.html";
|
||||
return;
|
||||
}
|
||||
window.location.href = next;
|
||||
}
|
||||
|
||||
function showMessage(text, isError = false) {
|
||||
els.message.hidden = false;
|
||||
els.message.textContent = text;
|
||||
els.message.classList.toggle("error", isError);
|
||||
}
|
||||
|
||||
function clearMessage() {
|
||||
els.message.hidden = true;
|
||||
els.message.textContent = "";
|
||||
els.message.classList.remove("error");
|
||||
}
|
||||
+9
-11
@@ -3,8 +3,8 @@
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>Speaking Lab</title>
|
||||
<link rel="stylesheet" href="./styles.css?v=20260604-study-toolbar">
|
||||
<title>Speaking Lab 学习页</title>
|
||||
<link rel="stylesheet" href="./styles.css?v=20260605-auth">
|
||||
</head>
|
||||
<body>
|
||||
<header class="topbar">
|
||||
@@ -13,12 +13,9 @@
|
||||
</div>
|
||||
|
||||
<div class="top-actions">
|
||||
<form id="loginForm" class="login-form">
|
||||
<input id="emailInput" type="email" placeholder="邮箱" autocomplete="email" required>
|
||||
<input id="passwordInput" type="password" placeholder="密码" autocomplete="current-password" required>
|
||||
<button id="loginBtn" type="submit">登录 / 注册</button>
|
||||
</form>
|
||||
<div id="userMenu" class="user-menu" hidden>
|
||||
<a class="secondary-action" href="./index.html">首页</a>
|
||||
<a id="adminEntryBtn" class="secondary-action" href="./admin.html" hidden>后台</a>
|
||||
<div id="userMenu" class="user-menu">
|
||||
<span id="userLabel"></span>
|
||||
<button id="logoutBtn" type="button">退出</button>
|
||||
</div>
|
||||
@@ -31,8 +28,8 @@
|
||||
<div class="video-frame">
|
||||
<video id="video" controls preload="metadata" crossorigin="anonymous"></video>
|
||||
<div id="emptyVideo" class="empty-video">
|
||||
<strong>选择或上传一个视频</strong>
|
||||
<span>支持本地 MP4/WebM 和 HLS 地址</span>
|
||||
<strong>选择一个视频</strong>
|
||||
<span>从首页选择素材后开始练习。</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -77,6 +74,7 @@
|
||||
</aside>
|
||||
</main>
|
||||
|
||||
<script src="./app.js?v=20260604-study-toolbar"></script>
|
||||
<script src="./auth.js?v=20260605-auth"></script>
|
||||
<script src="./app.js?v=20260605-auth"></script>
|
||||
</body>
|
||||
</html>
|
||||
+169
@@ -30,6 +30,135 @@ body {
|
||||
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
|
||||
}
|
||||
|
||||
.auth-page {
|
||||
min-height: 100vh;
|
||||
background:
|
||||
radial-gradient(circle at 20% 10%, rgba(15, 118, 110, 0.10), transparent 28%),
|
||||
radial-gradient(circle at 80% 20%, rgba(15, 39, 66, 0.08), transparent 30%),
|
||||
#f7fafc;
|
||||
}
|
||||
|
||||
.auth-shell {
|
||||
min-height: 100vh;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 24px;
|
||||
padding: 24px 14px;
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.auth-card {
|
||||
width: min(100%, 420px);
|
||||
padding: 34px 30px 24px;
|
||||
border: 1px solid rgba(15, 23, 42, 0.08);
|
||||
border-radius: 24px;
|
||||
background: rgba(255, 255, 255, 0.82);
|
||||
box-shadow: 0 18px 48px rgba(15, 23, 42, 0.10);
|
||||
backdrop-filter: blur(18px);
|
||||
}
|
||||
|
||||
.auth-heading {
|
||||
text-align: center;
|
||||
margin-bottom: 24px;
|
||||
}
|
||||
|
||||
.auth-heading h1 {
|
||||
margin: 0;
|
||||
font-size: 28px;
|
||||
font-weight: 700;
|
||||
letter-spacing: 0;
|
||||
}
|
||||
|
||||
.auth-heading p {
|
||||
margin: 8px 0 0;
|
||||
color: rgba(23, 32, 51, 0.52);
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.auth-form {
|
||||
display: grid;
|
||||
gap: 15px;
|
||||
}
|
||||
|
||||
.auth-form label {
|
||||
display: grid;
|
||||
gap: 8px;
|
||||
font-size: 14px;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.auth-form input {
|
||||
min-height: 48px;
|
||||
border-radius: 12px;
|
||||
padding: 0 14px;
|
||||
background: rgba(248, 250, 252, 0.92);
|
||||
border-color: #dbe3ec;
|
||||
font-size: 16px;
|
||||
}
|
||||
|
||||
.auth-form button[type="submit"] {
|
||||
min-height: 50px;
|
||||
margin-top: 4px;
|
||||
border: 0;
|
||||
border-radius: 999px;
|
||||
color: #ffffff;
|
||||
background: #111827;
|
||||
font-weight: 700;
|
||||
box-shadow: 0 10px 22px rgba(17, 24, 39, 0.18);
|
||||
}
|
||||
|
||||
.auth-form button[type="submit"]:hover {
|
||||
background: #0f172a;
|
||||
transform: translateY(-1px);
|
||||
}
|
||||
|
||||
.auth-message {
|
||||
margin: 14px 0 0;
|
||||
padding: 10px 12px;
|
||||
border-radius: 12px;
|
||||
color: #155e75;
|
||||
background: #ecfeff;
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.auth-message.error {
|
||||
color: var(--danger);
|
||||
background: #fef3f2;
|
||||
}
|
||||
|
||||
.auth-links {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
margin-top: 18px;
|
||||
color: rgba(23, 32, 51, 0.34);
|
||||
}
|
||||
|
||||
.auth-links button {
|
||||
min-height: 24px;
|
||||
border: 0;
|
||||
padding: 0;
|
||||
color: rgba(23, 32, 51, 0.56);
|
||||
background: transparent;
|
||||
text-decoration: underline;
|
||||
text-underline-offset: 4px;
|
||||
}
|
||||
|
||||
.auth-links button:hover {
|
||||
color: var(--ink);
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
.auth-footer {
|
||||
position: absolute;
|
||||
bottom: 18px;
|
||||
color: rgba(23, 32, 51, 0.45);
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
button,
|
||||
input,
|
||||
select,
|
||||
@@ -1030,6 +1159,46 @@ video {
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.admin-user-list,
|
||||
.activation-code-list {
|
||||
display: grid;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.admin-user-item,
|
||||
.activation-code-item {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1fr) auto;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
padding: 13px;
|
||||
border: 1px solid #e2e8f0;
|
||||
border-radius: 10px;
|
||||
background: #f8fafc;
|
||||
}
|
||||
|
||||
.admin-user-item h3,
|
||||
.activation-code-item h3 {
|
||||
margin: 0 0 5px;
|
||||
font-size: 14px;
|
||||
line-height: 1.35;
|
||||
}
|
||||
|
||||
.admin-user-item p,
|
||||
.activation-code-item p {
|
||||
margin: 0;
|
||||
color: var(--muted);
|
||||
font-size: 12px;
|
||||
line-height: 1.45;
|
||||
}
|
||||
|
||||
.activation-code-form {
|
||||
display: grid;
|
||||
grid-template-columns: 110px auto;
|
||||
gap: 8px;
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
|
||||
.danger-action {
|
||||
border-color: #fecdd3;
|
||||
border-radius: 8px;
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
import assert from "node:assert/strict";
|
||||
import authHelpers from "../auth.js";
|
||||
|
||||
const { getLoginUrlForPath, shouldShowAdminEntry } = authHelpers;
|
||||
|
||||
assert.equal(getLoginUrlForPath("/study.html?video=2"), "./login.html?next=%2Fstudy.html%3Fvideo%3D2");
|
||||
assert.equal(shouldShowAdminEntry({ role: "admin" }), true);
|
||||
assert.equal(shouldShowAdminEntry({ role: "user" }), false);
|
||||
assert.equal(shouldShowAdminEntry(null), false);
|
||||
@@ -0,0 +1,73 @@
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
import sys
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||
|
||||
from backend import db
|
||||
from backend.auth import create_auth_token, hash_password, verify_auth_token, verify_password
|
||||
|
||||
|
||||
class TempDatabase:
|
||||
def __enter__(self):
|
||||
self.temp_dir = tempfile.TemporaryDirectory(ignore_cleanup_errors=True)
|
||||
self.original = db.DATABASE_PATH
|
||||
db.DATABASE_PATH = Path(self.temp_dir.name) / "test.sqlite"
|
||||
db.initialize_database()
|
||||
return db.DATABASE_PATH
|
||||
|
||||
def __exit__(self, exc_type, exc, tb):
|
||||
db.DATABASE_PATH = self.original
|
||||
self.temp_dir.cleanup()
|
||||
|
||||
|
||||
def test_password_hash_roundtrip():
|
||||
stored = hash_password("secret123")
|
||||
|
||||
assert stored != "secret123"
|
||||
assert verify_password("secret123", stored) is True
|
||||
assert verify_password("wrong", stored) is False
|
||||
|
||||
|
||||
def test_auth_token_roundtrip_and_tamper_rejection():
|
||||
token = create_auth_token({"username": "student", "role": "user", "userId": 1}, "secret")
|
||||
|
||||
payload = verify_auth_token(token, "secret")
|
||||
assert payload["username"] == "student"
|
||||
assert payload["role"] == "user"
|
||||
assert verify_auth_token(token + "x", "secret") is None
|
||||
|
||||
|
||||
def test_activation_code_registers_user_once():
|
||||
with TempDatabase():
|
||||
created = db.create_activation_codes(["SL-ABC123-DEF456-GHI789"], "admin")
|
||||
assert created[0]["status"] == "unused"
|
||||
|
||||
user = db.register_user_with_activation(
|
||||
username="student",
|
||||
password_hash=hash_password("secret123"),
|
||||
activation_code="SL-ABC123-DEF456-GHI789",
|
||||
)
|
||||
|
||||
assert user["username"] == "student"
|
||||
codes = db.list_activation_codes()
|
||||
assert codes[0]["status"] == "used"
|
||||
assert codes[0]["usedByUsername"] == "student"
|
||||
|
||||
try:
|
||||
db.register_user_with_activation(
|
||||
username="student2",
|
||||
password_hash=hash_password("secret123"),
|
||||
activation_code="SL-ABC123-DEF456-GHI789",
|
||||
)
|
||||
except ValueError as error:
|
||||
assert str(error) == "activation_code_unavailable"
|
||||
else:
|
||||
raise AssertionError("used activation code should not register another user")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
test_password_hash_roundtrip()
|
||||
test_auth_token_roundtrip_and_tamper_rejection()
|
||||
test_activation_code_registers_user_once()
|
||||
@@ -0,0 +1,141 @@
|
||||
import sys
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
from fastapi import HTTPException
|
||||
from fastapi.security import HTTPAuthorizationCredentials
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||
|
||||
from backend import db, main
|
||||
|
||||
|
||||
class EnvPatch:
|
||||
def __init__(self):
|
||||
self.attributes = []
|
||||
|
||||
def setattr(self, target, name, value):
|
||||
self.attributes.append((target, name, getattr(target, name)))
|
||||
setattr(target, name, value)
|
||||
|
||||
def restore(self):
|
||||
while self.attributes:
|
||||
target, name, original = self.attributes.pop()
|
||||
setattr(target, name, original)
|
||||
|
||||
|
||||
class TempDatabase:
|
||||
def __enter__(self):
|
||||
self.temp_dir = tempfile.TemporaryDirectory(ignore_cleanup_errors=True)
|
||||
self.original = db.DATABASE_PATH
|
||||
db.DATABASE_PATH = Path(self.temp_dir.name) / "test.sqlite"
|
||||
db.initialize_database()
|
||||
return db.DATABASE_PATH
|
||||
|
||||
def __exit__(self, exc_type, exc, tb):
|
||||
db.DATABASE_PATH = self.original
|
||||
self.temp_dir.cleanup()
|
||||
|
||||
|
||||
def configure_admin(monkeypatch):
|
||||
monkeypatch.setattr(main, "get_config_value", lambda key, default="": {
|
||||
"ADMIN_USERNAME": "admin",
|
||||
"ADMIN_PASSWORD": "admin123",
|
||||
"AUTH_SECRET": "test-secret",
|
||||
}.get(key, default))
|
||||
|
||||
|
||||
def test_admin_login_can_generate_activation_code(monkeypatch):
|
||||
configure_admin(monkeypatch)
|
||||
|
||||
with TempDatabase():
|
||||
login = main.api_auth_login(main.LoginRequest(username="admin", password="admin123"))
|
||||
assert login["user"]["role"] == "admin"
|
||||
|
||||
bearer = HTTPAuthorizationCredentials(scheme="Bearer", credentials=login["token"])
|
||||
admin = main.require_admin(credentials=None, bearer=bearer)
|
||||
created = main.api_admin_create_activation_codes(
|
||||
main.GenerateActivationCodesRequest(quantity=2),
|
||||
admin=admin,
|
||||
)
|
||||
|
||||
assert len(created["codes"]) == 2
|
||||
assert created["codes"][0]["code"].startswith("SL-")
|
||||
|
||||
|
||||
def test_activation_registration_login_and_reuse_rejection(monkeypatch):
|
||||
configure_admin(monkeypatch)
|
||||
|
||||
with TempDatabase():
|
||||
admin_login = main.api_auth_login(main.LoginRequest(username="admin", password="admin123"))
|
||||
admin = main.require_admin(
|
||||
credentials=None,
|
||||
bearer=HTTPAuthorizationCredentials(scheme="Bearer", credentials=admin_login["token"]),
|
||||
)
|
||||
created = main.api_admin_create_activation_codes(
|
||||
main.GenerateActivationCodesRequest(quantity=1),
|
||||
admin=admin,
|
||||
)
|
||||
code = created["codes"][0]["code"]
|
||||
|
||||
registered = main.api_auth_register(main.RegisterRequest(
|
||||
activationCode=code,
|
||||
username="student",
|
||||
password="secret123",
|
||||
))
|
||||
assert registered["user"]["username"] == "student"
|
||||
assert registered["user"]["role"] == "user"
|
||||
|
||||
login = main.api_auth_login(main.LoginRequest(username="student", password="secret123"))
|
||||
session = main.api_auth_session(main.require_session(
|
||||
HTTPAuthorizationCredentials(scheme="Bearer", credentials=login["token"])
|
||||
))
|
||||
assert session["user"]["username"] == "student"
|
||||
|
||||
try:
|
||||
main.api_auth_register(main.RegisterRequest(
|
||||
activationCode=code,
|
||||
username="student2",
|
||||
password="secret123",
|
||||
))
|
||||
except HTTPException as error:
|
||||
assert error.status_code == 400
|
||||
else:
|
||||
raise AssertionError("used activation code should be rejected")
|
||||
|
||||
|
||||
def test_normal_user_cannot_use_admin_dependency(monkeypatch):
|
||||
configure_admin(monkeypatch)
|
||||
|
||||
with TempDatabase():
|
||||
db.create_activation_codes(["SL-ABC123-DEF456-GHI789"], "admin")
|
||||
registered = main.api_auth_register(main.RegisterRequest(
|
||||
activationCode="SL-ABC123-DEF456-GHI789",
|
||||
username="student",
|
||||
password="secret123",
|
||||
))
|
||||
|
||||
try:
|
||||
main.require_admin(
|
||||
credentials=None,
|
||||
bearer=HTTPAuthorizationCredentials(scheme="Bearer", credentials=registered["token"]),
|
||||
)
|
||||
except HTTPException as error:
|
||||
assert error.status_code == 401
|
||||
else:
|
||||
raise AssertionError("normal user token should not pass admin dependency")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
patch = EnvPatch()
|
||||
try:
|
||||
configure_admin(patch)
|
||||
test_admin_login_can_generate_activation_code(patch)
|
||||
patch.restore()
|
||||
configure_admin(patch)
|
||||
test_activation_registration_login_and_reuse_rejection(patch)
|
||||
patch.restore()
|
||||
configure_admin(patch)
|
||||
test_normal_user_cannot_use_admin_dependency(patch)
|
||||
finally:
|
||||
patch.restore()
|
||||
Reference in new issue
Block a user