37 lines
1.4 KiB
JavaScript
37 lines
1.4 KiB
JavaScript
/**
|
|
* 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';
|
|
};
|
|
}
|
|
})();
|