72 lines
1.9 KiB
JavaScript
72 lines
1.9 KiB
JavaScript
const $ = (id) => document.getElementById(id);
|
|
|
|
function setStatus(msg, danger = false) {
|
|
const el = $("status");
|
|
if (!el) return;
|
|
el.style.color = danger ? "#b42318" : "#0f5f3d";
|
|
el.textContent = msg;
|
|
}
|
|
|
|
function setLoading(button, loading, idleText, loadingText) {
|
|
if (!button) return;
|
|
button.disabled = loading;
|
|
button.textContent = loading ? loadingText : idleText;
|
|
}
|
|
|
|
async function postJSON(url, body) {
|
|
const res = await fetch(url, {
|
|
method: "POST",
|
|
headers: { "Content-Type": "application/json" },
|
|
body: JSON.stringify(body),
|
|
});
|
|
const data = await res.json();
|
|
if (!res.ok) throw new Error(data.detail || "请求失败");
|
|
return data;
|
|
}
|
|
|
|
function nextPath() {
|
|
const nxt = (window.__NEXT_PATH__ || "/").trim();
|
|
if (!nxt.startsWith("/")) return "/";
|
|
return nxt;
|
|
}
|
|
|
|
function fields() {
|
|
return {
|
|
username: ($("username") && $("username").value.trim()) || "",
|
|
password: ($("password") && $("password").value) || "",
|
|
remember_me: Boolean($("rememberMe") && $("rememberMe").checked),
|
|
};
|
|
}
|
|
|
|
async function authAction(url, button, idleText, loadingText, okMessage) {
|
|
setLoading(button, true, idleText, loadingText);
|
|
try {
|
|
const data = await postJSON(url, fields());
|
|
if (!data.ok) {
|
|
setStatus(data.detail || "操作失败", true);
|
|
return;
|
|
}
|
|
setStatus(okMessage);
|
|
window.location.href = nextPath();
|
|
} catch (e) {
|
|
setStatus(e.message || "请求异常", true);
|
|
} finally {
|
|
setLoading(button, false, idleText, loadingText);
|
|
}
|
|
}
|
|
|
|
const loginBtn = $("loginBtn");
|
|
const registerBtn = $("registerBtn");
|
|
|
|
if (loginBtn) {
|
|
loginBtn.addEventListener("click", async () => {
|
|
await authAction("/api/auth/login", loginBtn, "登录", "登录中...", "登录成功,正在跳转...");
|
|
});
|
|
}
|
|
|
|
if (registerBtn) {
|
|
registerBtn.addEventListener("click", async () => {
|
|
await authAction("/api/auth/register", registerBtn, "注册", "注册中...", "注册成功,正在跳转...");
|
|
});
|
|
}
|