Files
speaking-practice/auth.js
T
TTlaji 2d3ff21222
Deploy Speaking Practice / deploy (push) Successful in 24s
feat: add activation-code auth
2026-06-05 16:56:30 +08:00

128 lines
3.4 KiB
JavaScript

(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";
},
};
}
})();