62 lines
1.8 KiB
JavaScript
62 lines
1.8 KiB
JavaScript
const form = document.querySelector("#login-form");
|
|
const nextInput = document.querySelector("#next-url");
|
|
const statusEl = document.querySelector("#login-status");
|
|
|
|
const params = new URLSearchParams(window.location.search);
|
|
const requestedNext = params.get("next") || "/software.html";
|
|
|
|
function safeNext(value) {
|
|
if (!value) return "/software.html";
|
|
if (value.startsWith("/") && !value.startsWith("//")) return value;
|
|
if (/^[a-z0-9._/-]+$/i.test(value)) return value;
|
|
return "/software.html";
|
|
}
|
|
|
|
function setStatus(message, type = "") {
|
|
statusEl.textContent = message;
|
|
statusEl.classList.toggle("is-error", type === "error");
|
|
statusEl.classList.toggle("is-ok", type === "ok");
|
|
}
|
|
|
|
async function checkExistingLogin() {
|
|
try {
|
|
const response = await fetch("/api/auth/me", { headers: { Accept: "application/json" } });
|
|
const payload = await response.json();
|
|
if (payload.authenticated) {
|
|
window.location.href = safeNext(requestedNext);
|
|
}
|
|
} catch {
|
|
setStatus("");
|
|
}
|
|
}
|
|
|
|
nextInput.value = safeNext(requestedNext);
|
|
|
|
form.addEventListener("submit", async (event) => {
|
|
event.preventDefault();
|
|
const formData = new FormData(form);
|
|
const payload = Object.fromEntries(formData.entries());
|
|
|
|
try {
|
|
setStatus("正在登录...");
|
|
const response = await fetch("/api/auth/login", {
|
|
method: "POST",
|
|
headers: {
|
|
Accept: "application/json",
|
|
"Content-Type": "application/json",
|
|
},
|
|
body: JSON.stringify(payload),
|
|
});
|
|
const data = await response.json();
|
|
if (!response.ok) {
|
|
throw new Error(data.error || "登录失败");
|
|
}
|
|
setStatus("登录成功,正在跳转。", "ok");
|
|
window.location.href = safeNext(data.next || payload.next);
|
|
} catch (error) {
|
|
setStatus(error.message, "error");
|
|
}
|
|
});
|
|
|
|
checkExistingLogin();
|