44 lines
1.4 KiB
JavaScript
Executable File
44 lines
1.4 KiB
JavaScript
Executable File
function nextPath() {
|
|
const candidate = new URLSearchParams(window.location.search).get("next");
|
|
return candidate?.startsWith("/") && !candidate.startsWith("//") ? candidate : "/";
|
|
}
|
|
|
|
async function readAuthStatus() {
|
|
const response = await fetch("/api/auth/status", { cache: "no-store" });
|
|
if (!response.ok) return;
|
|
const status = await response.json();
|
|
if (status.authenticated) window.location.replace(nextPath());
|
|
}
|
|
|
|
async function submitLogin(event) {
|
|
event.preventDefault();
|
|
const button = document.querySelector("#loginButton");
|
|
const message = document.querySelector("#loginMessage");
|
|
button.disabled = true;
|
|
message.textContent = "";
|
|
|
|
try {
|
|
const response = await fetch("/api/auth/login", {
|
|
method: "POST",
|
|
headers: { "Content-Type": "application/json" },
|
|
body: JSON.stringify({
|
|
username: document.querySelector("#username").value,
|
|
password: document.querySelector("#password").value,
|
|
}),
|
|
});
|
|
const result = await response.json();
|
|
if (!response.ok) throw new Error(result.message || "登录失败");
|
|
window.location.replace(nextPath());
|
|
} catch (error) {
|
|
message.textContent = error.message;
|
|
document.querySelector("#password").select();
|
|
} finally {
|
|
button.disabled = false;
|
|
}
|
|
}
|
|
|
|
document.addEventListener("DOMContentLoaded", () => {
|
|
document.querySelector("#loginForm").addEventListener("submit", submitLogin);
|
|
readAuthStatus().catch(() => {});
|
|
});
|