va-tracker-middleware/public/js/common/sidebar.js

91 lines
2.3 KiB
JavaScript

const currentPath = window.location.pathname;
document.querySelectorAll('.nav-button').forEach(link => {
if (link.getAttribute('href') === currentPath) {
link.classList.add('active');
} else {
link.classList.remove('active');
}
});
document.querySelectorAll('.sidebar-link').forEach(link => {
if (link.getAttribute('href') === currentPath) {
link.classList.add('active');
} else {
link.classList.remove('active');
}
});
// Auth helpers
function getAuthToken() {
return localStorage.getItem("knoptpq");
}
async function fetchWithAuth(url, options = {}) {
const token = getAuthToken();
if (!token) {
window.location.href = "/client/login";
return;
}
const res = await fetch(url, {
...options,
headers: {
"token": token,
"Content-Type": "application/json",
...options.headers,
}
});
if (res.status === 401) {
localStorage.clear();
window.location.href = "/client/login";
return;
}
return res;
}
// Logout modal
function openLogoutModal() {
document.getElementById("logoutModal").style.display = "flex";
document.body.style.overflow = "hidden";
}
function closeLogoutModal() {
document.getElementById("logoutModal").style.display = "none";
document.body.style.overflow = "auto";
}
// Final logout
async function handleLogout() {
try {
await fetchWithAuth("/api/v1/client/logout", { method: "POST" });
} catch (e) {
console.error("Logout error", e);
} finally {
localStorage.clear();
window.location.href = "/client/login";
}
}
// DOM bindings
document.addEventListener("DOMContentLoaded", () => {
// Logout button
const logoutBtn = document.getElementById("logoutButton");
if (logoutBtn) logoutBtn.addEventListener("click", openLogoutModal);
// Confirm logout
const confirmBtn = document.getElementById("confirmLogoutBtn");
if (confirmBtn) confirmBtn.addEventListener("click", handleLogout);
// Click outside modal
const modal = document.getElementById("logoutModal");
if (modal) {
modal.addEventListener("click", (e) => {
if (e.target === modal) closeLogoutModal();
});
}
});