60 lines
1.7 KiB
JavaScript
60 lines
1.7 KiB
JavaScript
async function applySessionState() {
|
|
let session;
|
|
try {
|
|
const response = await fetch("/api/session", { credentials: "same-origin" });
|
|
if (!response.ok) {
|
|
return;
|
|
}
|
|
session = await response.json();
|
|
} catch {
|
|
return;
|
|
}
|
|
|
|
window.__KA_SESSION__ = session;
|
|
const isLoggedIn = session.authenticated === true;
|
|
document.querySelectorAll(".logged-in-only").forEach((element) => {
|
|
setVisible(element, isLoggedIn);
|
|
});
|
|
document.querySelectorAll(".logged-out-only").forEach((element) => {
|
|
setVisible(element, !isLoggedIn);
|
|
});
|
|
document.querySelectorAll(".admin-only").forEach((element) => {
|
|
setVisible(element, isLoggedIn && session.is_admin === true);
|
|
});
|
|
markCurrentNavLink();
|
|
|
|
const csrf = document.getElementById("landing-csrf");
|
|
if (csrf && session.csrf_token) {
|
|
csrf.value = session.csrf_token;
|
|
}
|
|
}
|
|
|
|
function setVisible(element, visible) {
|
|
element.hidden = !visible;
|
|
element.style.display = visible ? "" : "none";
|
|
}
|
|
|
|
function markCurrentNavLink() {
|
|
const currentPath = normalizePath(window.location.pathname);
|
|
document.querySelectorAll(".nav-links a").forEach((link) => {
|
|
const href = link.getAttribute("href");
|
|
if (!href || href === "#" || href.startsWith("http")) {
|
|
return;
|
|
}
|
|
const targetPath = normalizePath(new URL(href, window.location.origin).pathname);
|
|
const isCurrent = targetPath === currentPath;
|
|
link.classList.toggle("current", isCurrent);
|
|
if (isCurrent) {
|
|
link.setAttribute("aria-current", "page");
|
|
} else {
|
|
link.removeAttribute("aria-current");
|
|
}
|
|
});
|
|
}
|
|
|
|
function normalizePath(path) {
|
|
return String(path || "").replace(/\/+$/, "") || "/";
|
|
}
|
|
|
|
window.__KA_SESSION_PROMISE__ = applySessionState();
|