hm_ai_qc_report_tool/static/js/auth.js
nickviljoen 84326352b2 Phase 1: replace local username/password auth with Azure AD SSO
Lifted JWT-cookie auth pattern from the AI QC sibling project:
  core/auth/middleware.py validates Azure AD JWTs and stores them in
  an httpOnly cookie (hm_aiqc_auth_token). Tenant membership is
  enforced by JWTValidator's tid check, which is sufficient for the
  tenant-wide access policy chosen for this project.

  templates/login.html now drives an MSAL.js popup that POSTs the
  ID token to /auth/login. base.html exposes Azure config to all
  pages so the logout button can also clear the MSAL session.

  app.py's @before_request now checks the JWT cookie and exposes
  g.user; modules read user identity via core.auth.current_user_email
  so usage logs and created_by columns now record the signed-in
  user's email rather than a session value.

  Legacy username/password code removed: top-level auth_middleware.py,
  jwt_validator.py, deploy/generate_password.py.
2026-05-09 13:59:29 +02:00

49 lines
1.6 KiB
JavaScript

/**
* Logout handler — clears server cookie and MSAL session, then redirects.
*
* MSAL.js is loaded by base.html so the popup can also sign the user out
* of Microsoft for this app — otherwise sessionStorage would silently
* re-authenticate on the next page load.
*/
(function () {
const logoutBtn = document.getElementById('logoutBtn');
if (!logoutBtn) return;
let msalApp = null;
try {
if (typeof msal !== 'undefined' && window.AZURE_TENANT_ID && window.AZURE_CLIENT_ID) {
msalApp = new msal.PublicClientApplication({
auth: {
clientId: window.AZURE_CLIENT_ID,
authority: 'https://login.microsoftonline.com/' + window.AZURE_TENANT_ID,
redirectUri: window.location.origin + (window.BASE_URL || '/')
},
cache: {
cacheLocation: 'sessionStorage',
storeAuthStateInCookie: true
}
});
}
} catch (e) {
console.warn('MSAL init failed in auth.js:', e);
}
logoutBtn.addEventListener('click', async () => {
try {
await fetch(window.BASE_URL + '/auth/logout', {
method: 'POST',
credentials: 'include'
});
} catch (e) { /* ignore */ }
if (msalApp) {
try {
await msalApp.logoutPopup({
postLogoutRedirectUri: window.location.origin + (window.BASE_URL || '/')
});
} catch (e) { /* ignore */ }
}
window.location.href = window.BASE_URL + '/auth/login-page';
});
})();