/** * Authentication helpers: login, logout, page guard and header profile. * Session is stored in HttpOnly cookies by the server; localStorage is optional cache. */ (function () { "use strict"; /** * Page shells are already gated by AdminPageAuth middleware. * Keep a soft client check for pages that still call this. */ function requireAuth() { return true; } /** Sign in; server sets HttpOnly cookies. */ async function login(loginValue, password) { const pair = await Api.post("/api/v1/admin/login", { login: loginValue, password: password, }); if (!pair || !pair.accessToken) { throw new Api.ApiError("Login failed. Please try again.", 500); } Api.tokens.set(pair); } async function logout() { try { await Api.post("/api/v1/admin/logout", {}); } catch (_) { /* still clear local state and leave */ } Api.tokens.clear(); window.location.href = "/admin/login"; } /** Load the admin profile and render it into the header. */ async function loadProfile() { const nameEl = document.getElementById("profile-name"); const avatarEl = document.getElementById("profile-avatar"); const initialEl = document.getElementById("profile-initial"); if (!nameEl) return; try { const profile = await Api.get("/api/v1/admin/get-profile"); const fullName = (profile && profile.fullName) || "Admin"; nameEl.textContent = fullName; if (avatarEl && profile && profile.avatar) { avatarEl.src = profile.avatar; avatarEl.alt = fullName; avatarEl.classList.remove("hidden"); if (initialEl) initialEl.classList.add("hidden"); } else if (initialEl) { initialEl.textContent = fullName.charAt(0).toUpperCase(); } } catch (_) { /* profile is decorative; auth errors already redirect */ } } function bindLogoutButtons() { document.querySelectorAll("[data-logout]").forEach((button) => { button.addEventListener("click", (event) => { event.preventDefault(); logout(); }); }); } window.Auth = { requireAuth, login, logout, loadProfile, bindLogoutButtons }; })();