From 4f649b41a9b134e34634c4e4c4b1b4dcb089b52c Mon Sep 17 00:00:00 2001 From: ZGaetano Date: Mon, 18 May 2026 13:21:22 -0400 Subject: [PATCH] =?UTF-8?q?feat:=20add=20shared=20auth-guard.js=20with=204?= =?UTF-8?q?01=20=E2=86=92=20login=20redirect?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- services/web-ui/public/js/auth-guard.js | 37 +++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 services/web-ui/public/js/auth-guard.js diff --git a/services/web-ui/public/js/auth-guard.js b/services/web-ui/public/js/auth-guard.js new file mode 100644 index 0000000..67851d8 --- /dev/null +++ b/services/web-ui/public/js/auth-guard.js @@ -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'; + }; + } +})();