feat: add shared auth-guard.js with 401 → login redirect

This commit is contained in:
Zac Gaetano 2026-05-18 13:21:22 -04:00
parent 725c3ed292
commit 4f649b41a9

View file

@ -0,0 +1,37 @@
/**
* auth-guard.js
* Included on every protected page.
*
* - If /api/v1/auth/me returns 401 redirect to login.html immediately.
* (When AUTH_ENABLED=false the endpoint returns a synthetic guest user,
* so the redirect only fires in production auth-enabled mode.)
* - On success, populate the sidebar user widget and wire up the logout button.
*/
(async () => {
try {
const r = await fetch('/api/v1/auth/me', { credentials: 'include' });
if (r.status === 401) {
location.replace('login.html');
return;
}
if (r.ok) {
const u = await r.json();
const name = u.display_name || u.username || 'User';
const userNameEl = document.getElementById('userName');
const userAvatarEl = document.getElementById('userAvatar');
const userRoleEl = document.getElementById('userRole');
if (userNameEl) userNameEl.textContent = name;
if (userAvatarEl) userAvatarEl.textContent = name[0].toUpperCase();
if (userRoleEl) userRoleEl.textContent = u.role || '';
}
} catch (_) {
// Network error — don't redirect; the user may be on a dev build without auth.
}
const logoutBtn = document.getElementById('logoutBtn');
if (logoutBtn) {
logoutBtn.onclick = async () => {
try { await fetch('/api/v1/auth/logout', { method: 'POST', credentials: 'include' }); } catch (_) {}
location.href = 'login.html';
};
}
})();