This commit is contained in:
@@ -33,6 +33,7 @@
|
||||
async function authFetch(input, options = {}) {
|
||||
const response = await fetch(input, {
|
||||
...options,
|
||||
credentials: options.credentials || "same-origin",
|
||||
headers: authHeaders(options.headers),
|
||||
});
|
||||
|
||||
@@ -47,6 +48,7 @@
|
||||
async function login(username, password) {
|
||||
const response = await fetch("/api/auth/login", {
|
||||
method: "POST",
|
||||
credentials: "same-origin",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ username, password }),
|
||||
});
|
||||
@@ -60,6 +62,18 @@
|
||||
return data.token;
|
||||
}
|
||||
|
||||
async function hasServerSession() {
|
||||
if (token()) return true;
|
||||
|
||||
const response = await fetch("/api/auth/check", {
|
||||
method: "GET",
|
||||
credentials: "same-origin",
|
||||
cache: "no-store",
|
||||
});
|
||||
|
||||
return response.status === 204;
|
||||
}
|
||||
|
||||
function initLoginForm() {
|
||||
const form = document.getElementById("login-form");
|
||||
if (!form) return;
|
||||
@@ -91,15 +105,19 @@
|
||||
fetch: authFetch,
|
||||
headers: authHeaders,
|
||||
token,
|
||||
logout: () => {
|
||||
logout: async () => {
|
||||
await fetch("/api/auth/logout", {
|
||||
method: "POST",
|
||||
credentials: "same-origin",
|
||||
}).catch(() => {});
|
||||
window.localStorage.removeItem(TOKEN_KEY);
|
||||
redirectToLogin();
|
||||
},
|
||||
};
|
||||
|
||||
document.addEventListener("DOMContentLoaded", () => {
|
||||
document.addEventListener("DOMContentLoaded", async () => {
|
||||
initLoginForm();
|
||||
if (!isLoginPage() && !token()) {
|
||||
if (!isLoginPage() && !(await hasServerSession())) {
|
||||
redirectToLogin();
|
||||
}
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user