Migrate auth to AuthGuard, retiring local Postgres-backed accounts
Same pattern as GameStream (commit 6a46007), adapted for CollabTable being genuinely multi-user (not single-admin): admin user management (list/create/update/delete, role reassignment, superadmin protection) is fully proxied to AuthGuard, which already enforces the same rules CollabTable checked locally. Cookie forwarding, no local session token, AUTHGUARD_URL optional (unset = auth fully disabled), transport failures always surface as errAuthGuardUnavailable rather than ever letting a request through - proven with live tests against a closed socket. CollabTable's device-sync API token feature (separate from browser sessions) is deliberately left local-only regardless of AUTHGUARD_URL, keyed by a new currentUserID helper (AuthGuard's id when enabled, the shared placeholder id 0 when disabled) - a real, functional token either way, not faked data. Real bug found and fixed: api_tokens.user_id had a hard FK into the local auth_users table, which would reject new tokens once accounts stop being written locally. Dropped the now-invalid FK. Known, accepted gap (same as GameStream): self-service profile editing for non-admin accounts is lost, since AuthGuard only exposes an admin endpoint, no self-edit. TOTP QR issuer branding now comes from AuthGuard rather than CollabTable. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
1 parent
a1c29728f0
commit
9a6ec940f7
48 files changed
+12401
-511
No files matched your search
@@ -0,0 +1,47 @@
|
||||
(() => {
|
||||
if (window.NCAuthForm) return;
|
||||
|
||||
function bindJsonSubmit(options) {
|
||||
const { endpoint, formId, resultId, buildPayload, onSuccess, onError } = options || {};
|
||||
|
||||
if (!endpoint || !formId || !resultId || typeof buildPayload !== 'function') {
|
||||
return false;
|
||||
}
|
||||
|
||||
const form = document.getElementById(formId);
|
||||
const result = document.getElementById(resultId);
|
||||
if (!form || !result) return false;
|
||||
|
||||
form.addEventListener('submit', async event => {
|
||||
event.preventDefault();
|
||||
|
||||
try {
|
||||
const response = await fetch(endpoint, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(buildPayload()),
|
||||
});
|
||||
|
||||
const payload = await response.json();
|
||||
result.textContent = payload.message || JSON.stringify(payload);
|
||||
|
||||
if (response.ok && typeof onSuccess === 'function') {
|
||||
onSuccess(payload, response);
|
||||
} else if (!response.ok && typeof onError === 'function') {
|
||||
onError(payload, response);
|
||||
}
|
||||
} catch (error) {
|
||||
result.textContent = 'Request failed. Please try again.';
|
||||
if (typeof onError === 'function') {
|
||||
onError({ error: error && error.message ? error.message : String(error) }, null);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
window.NCAuthForm = {
|
||||
bindJsonSubmit,
|
||||
};
|
||||
})();
|
||||
@@ -0,0 +1,13 @@
|
||||
(() => {
|
||||
const opener = document.getElementById('authLoginOpenBtn');
|
||||
if (!opener) return;
|
||||
const buttons = document.querySelectorAll('[data-auth-guard-login]');
|
||||
buttons.forEach(button => {
|
||||
if (button.dataset.authGuardWired === '1') return;
|
||||
button.dataset.authGuardWired = '1';
|
||||
button.addEventListener('click', event => {
|
||||
event.preventDefault();
|
||||
opener.click();
|
||||
});
|
||||
});
|
||||
})();
|
||||
@@ -0,0 +1,646 @@
|
||||
// Shared Auth Modals (login + signup)
|
||||
/* global toast */
|
||||
(function () {
|
||||
// Button references - may not exist yet if using dynamic component loading
|
||||
let loginOpenBtn = document.getElementById('authLoginOpenBtn');
|
||||
let signupOpenBtn = document.getElementById('authSignupOpenBtn');
|
||||
let logoutBtn = document.getElementById('authLogoutBtn');
|
||||
let profileMenu = document.getElementById('authProfileMenu');
|
||||
|
||||
// Overlay references - may not exist yet if using dynamic component loading
|
||||
let loginOverlay = document.getElementById('authLoginOverlay');
|
||||
let signupOverlay = document.getElementById('authSignupOverlay');
|
||||
let overlays = [loginOverlay, signupOverlay].filter(Boolean);
|
||||
// eslint-disable-next-line no-unused-vars
|
||||
let _loginPanel = loginOverlay ? loginOverlay.querySelector('#authLoginPanel') : null;
|
||||
let signupPanel = signupOverlay ? signupOverlay.querySelector('#authSignupPanel') : null;
|
||||
let submitBtns = document.querySelectorAll('[data-auth-submit]');
|
||||
let pwInput = document.getElementById('signupPassword');
|
||||
let pwMeter = document.getElementById('signupPwMeter');
|
||||
let pwFeedback = document.getElementById('signupPwFeedback');
|
||||
let pwConfirm = document.getElementById('signupConfirm');
|
||||
let pwConfirmErr = document.getElementById('signupConfirmError');
|
||||
let loginTotpRow = document.getElementById('loginTotpRow');
|
||||
let loginTotpInput = document.getElementById('loginTotp');
|
||||
let loginTotpHint = document.getElementById('loginTotpHint');
|
||||
let isAdminApp = !!document.querySelector('[data-bottom-nav] a[href="/dashboard"]');
|
||||
|
||||
const STORAGE_KEY = 'authLoggedIn';
|
||||
let authKnown = false;
|
||||
let authLoggedIn = false;
|
||||
let buttonListenersAttached = false;
|
||||
let overlayListenersAttached = false;
|
||||
|
||||
// Optimistically initialize from localStorage to avoid button flicker on page load
|
||||
// This will be confirmed/corrected by the /auth/me fetch below
|
||||
try {
|
||||
const storedAuth = localStorage.getItem(STORAGE_KEY);
|
||||
if (storedAuth === '1') {
|
||||
authKnown = true;
|
||||
authLoggedIn = true;
|
||||
}
|
||||
} catch {
|
||||
// LocalStorage might not be available in some contexts
|
||||
}
|
||||
|
||||
// Function to refresh button references (for dynamic component loading)
|
||||
function refreshButtonReferences() {
|
||||
loginOpenBtn = document.getElementById('authLoginOpenBtn');
|
||||
signupOpenBtn = document.getElementById('authSignupOpenBtn');
|
||||
logoutBtn = document.getElementById('authLogoutBtn');
|
||||
profileMenu = document.getElementById('authProfileMenu');
|
||||
// Reset dropdown listener flag so toggle is re-attached to fresh DOM elements
|
||||
buttonListenersAttached = false;
|
||||
}
|
||||
|
||||
// Function to refresh overlay references (for dynamic component loading)
|
||||
function refreshOverlayReferences() {
|
||||
loginOverlay = document.getElementById('authLoginOverlay');
|
||||
signupOverlay = document.getElementById('authSignupOverlay');
|
||||
overlays = [loginOverlay, signupOverlay].filter(Boolean);
|
||||
_loginPanel = loginOverlay ? loginOverlay.querySelector('#authLoginPanel') : null;
|
||||
signupPanel = signupOverlay ? signupOverlay.querySelector('#authSignupPanel') : null;
|
||||
submitBtns = document.querySelectorAll('[data-auth-submit]');
|
||||
pwInput = document.getElementById('signupPassword');
|
||||
pwMeter = document.getElementById('signupPwMeter');
|
||||
pwFeedback = document.getElementById('signupPwFeedback');
|
||||
pwConfirm = document.getElementById('signupConfirm');
|
||||
pwConfirmErr = document.getElementById('signupConfirmError');
|
||||
loginTotpRow = document.getElementById('loginTotpRow');
|
||||
loginTotpInput = document.getElementById('loginTotp');
|
||||
loginTotpHint = document.getElementById('loginTotpHint');
|
||||
isAdminApp = !!document.querySelector('[data-bottom-nav] a[href="/dashboard"]');
|
||||
// Reset listener flags when overlays are re-loaded
|
||||
overlayListenersAttached = false;
|
||||
}
|
||||
|
||||
function setHiddenClass(element, hidden) {
|
||||
if (!element) return;
|
||||
element.classList.toggle('hidden', !!hidden);
|
||||
}
|
||||
|
||||
function setLoginTotpPrompt(visible, message = '') {
|
||||
if (!loginTotpRow) return;
|
||||
setHiddenClass(loginTotpRow, !visible);
|
||||
if (loginTotpHint) {
|
||||
loginTotpHint.textContent =
|
||||
message || 'Two-factor authentication is enabled for this account.';
|
||||
}
|
||||
if (!visible && loginTotpInput) {
|
||||
loginTotpInput.value = '';
|
||||
}
|
||||
}
|
||||
|
||||
function isLoggedIn() {
|
||||
return authKnown && authLoggedIn;
|
||||
}
|
||||
function setLoggedIn(v) {
|
||||
authKnown = true;
|
||||
authLoggedIn = !!v;
|
||||
if (v) {
|
||||
localStorage.setItem(STORAGE_KEY, '1');
|
||||
} else {
|
||||
localStorage.removeItem(STORAGE_KEY);
|
||||
}
|
||||
updateHeaderButton();
|
||||
}
|
||||
|
||||
// Toggle both the HTML hidden attribute (accessibility/semantics) and the
|
||||
// Tailwind .hidden CSS class. Tailwind's preflight wraps [hidden] in
|
||||
// :where() (zero specificity) so utility classes like .inline-flex override
|
||||
// it. The .hidden utility class has normal specificity and wins correctly.
|
||||
function setHidden(el, hide) {
|
||||
if (!el) return;
|
||||
el.hidden = !!hide;
|
||||
el.classList.toggle('hidden', !!hide);
|
||||
}
|
||||
|
||||
function updateHeaderButton() {
|
||||
if (isLoggedIn()) {
|
||||
setHidden(loginOpenBtn, true);
|
||||
setHidden(signupOpenBtn, true);
|
||||
setHidden(profileMenu, false);
|
||||
} else {
|
||||
setHidden(loginOpenBtn, false);
|
||||
if (loginOpenBtn) {
|
||||
loginOpenBtn.setAttribute('aria-haspopup', 'dialog');
|
||||
loginOpenBtn.title = 'Log in';
|
||||
}
|
||||
// Keep signup button hidden - users can access signup via the "Sign up" link in the login modal
|
||||
setHidden(signupOpenBtn, true);
|
||||
setHidden(profileMenu, true);
|
||||
// Ensure dropdown is closed when logging out
|
||||
const dropdown = document.getElementById('authProfileDropdown');
|
||||
const profileBtn = document.getElementById('authProfileBtn');
|
||||
if (dropdown) {
|
||||
dropdown.classList.add('hidden');
|
||||
}
|
||||
if (profileBtn) {
|
||||
profileBtn.setAttribute('aria-expanded', 'false');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function isBootstrapLocked(overlay) {
|
||||
return overlay && overlay.querySelector('[data-admin-bootstrap]') != null;
|
||||
}
|
||||
function anyOverlayOpen() {
|
||||
return overlays.some(item => item && item.hidden === false);
|
||||
}
|
||||
|
||||
function setNoScroll(enabled) {
|
||||
document.documentElement.classList.toggle('overflow-hidden', !!enabled);
|
||||
document.body.classList.toggle('overflow-hidden', !!enabled);
|
||||
}
|
||||
|
||||
function openOverlay(overlay) {
|
||||
if (!overlay) return;
|
||||
overlays.forEach(item => {
|
||||
if (item) setHidden(item, item !== overlay);
|
||||
});
|
||||
if (overlay === loginOverlay) setLoginTotpPrompt(false);
|
||||
setHidden(overlay, false);
|
||||
setNoScroll(true);
|
||||
setTimeout(() => {
|
||||
const el = overlay.querySelector('input');
|
||||
if (el) el.focus();
|
||||
}, 0);
|
||||
}
|
||||
|
||||
function switchOverlay(fromOverlay, toOverlay) {
|
||||
if (!fromOverlay || !toOverlay) return;
|
||||
setHidden(fromOverlay, true);
|
||||
setHidden(toOverlay, false);
|
||||
if (toOverlay === loginOverlay) setLoginTotpPrompt(false);
|
||||
// Keep scroll lock active during switch
|
||||
setTimeout(() => {
|
||||
const el = toOverlay.querySelector('input');
|
||||
if (el) el.focus();
|
||||
}, 0);
|
||||
}
|
||||
|
||||
function closeOverlay(overlay) {
|
||||
if (!overlay) return;
|
||||
setHidden(overlay, true);
|
||||
if (!anyOverlayOpen()) setNoScroll(false);
|
||||
}
|
||||
|
||||
function closeAll() {
|
||||
overlays.forEach(item => {
|
||||
if (item) setHidden(item, true);
|
||||
});
|
||||
setNoScroll(false);
|
||||
}
|
||||
|
||||
async function handleLogout() {
|
||||
// Verify session still valid first (in case local flag drifted)
|
||||
try {
|
||||
const r = await fetch('/auth/me');
|
||||
const j = await r.json().catch(() => ({}));
|
||||
if (!r.ok || !j?.user) {
|
||||
setLoggedIn(false);
|
||||
// Always redirect to root; each app's root resolves to its main page (Admin -> /dashboard, Forge -> /generator)
|
||||
window.location.replace('/');
|
||||
return;
|
||||
}
|
||||
} catch {
|
||||
/* ignore session probe failure */
|
||||
}
|
||||
try {
|
||||
await fetch('/auth/logout', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
});
|
||||
} catch {
|
||||
/* ignore network */
|
||||
}
|
||||
setLoggedIn(false);
|
||||
// Provide lightweight feedback then redirect to canonical root for ALL apps
|
||||
if (window.toast && typeof toast?.info === 'function') {
|
||||
toast.info('Logged out');
|
||||
} else {
|
||||
console.info('[LOGOUT] Logged out');
|
||||
}
|
||||
// Unified behavior: always navigate to root. Individual apps define their own root redirect target.
|
||||
window.location.replace('/');
|
||||
}
|
||||
|
||||
// Header login/signup buttons - wrapped in function to support dynamic loading
|
||||
function attachButtonListeners() {
|
||||
// Only attach once to prevent duplicate listeners
|
||||
if (buttonListenersAttached) return;
|
||||
|
||||
if (loginOpenBtn) {
|
||||
loginOpenBtn.addEventListener('click', () => {
|
||||
openOverlay(loginOverlay);
|
||||
});
|
||||
}
|
||||
if (signupOpenBtn) {
|
||||
signupOpenBtn.addEventListener('click', () => {
|
||||
openOverlay(signupOverlay);
|
||||
});
|
||||
}
|
||||
|
||||
if (logoutBtn) {
|
||||
logoutBtn.addEventListener('click', handleLogout);
|
||||
}
|
||||
|
||||
// Profile dropdown toggle
|
||||
const profileBtn = document.getElementById('authProfileBtn');
|
||||
const profileDropdown = document.getElementById('authProfileDropdown');
|
||||
if (profileBtn && profileDropdown) {
|
||||
profileBtn.addEventListener('click', e => {
|
||||
e.stopPropagation();
|
||||
const isOpen = !profileDropdown.classList.contains('hidden');
|
||||
profileDropdown.classList.toggle('hidden', isOpen);
|
||||
profileBtn.setAttribute('aria-expanded', String(!isOpen));
|
||||
profileDropdown.querySelectorAll('[role="menuitem"]').forEach(el => {
|
||||
el.tabIndex = isOpen ? -1 : 0;
|
||||
});
|
||||
});
|
||||
// Close when clicking outside
|
||||
document.addEventListener('click', () => {
|
||||
if (!profileDropdown.classList.contains('hidden')) {
|
||||
profileDropdown.classList.add('hidden');
|
||||
profileBtn.setAttribute('aria-expanded', 'false');
|
||||
profileDropdown.querySelectorAll('[role="menuitem"]').forEach(el => {
|
||||
el.tabIndex = -1;
|
||||
});
|
||||
}
|
||||
});
|
||||
// Close on Escape
|
||||
document.addEventListener('keydown', e => {
|
||||
if (e.key === 'Escape' && !profileDropdown.classList.contains('hidden')) {
|
||||
profileDropdown.classList.add('hidden');
|
||||
profileBtn.setAttribute('aria-expanded', 'false');
|
||||
profileDropdown.querySelectorAll('[role="menuitem"]').forEach(el => {
|
||||
el.tabIndex = -1;
|
||||
});
|
||||
profileBtn.focus();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
if (loginOpenBtn || signupOpenBtn || logoutBtn || profileMenu) {
|
||||
buttonListenersAttached = true;
|
||||
}
|
||||
}
|
||||
|
||||
// Initial attachment (buttons may not exist yet if using component loader)
|
||||
attachButtonListeners();
|
||||
|
||||
// Initial button visibility update (will be called again after components load or /auth/me completes)
|
||||
updateHeaderButton();
|
||||
|
||||
// Function to attach overlay listeners (for dynamic component loading)
|
||||
function attachOverlayListeners() {
|
||||
// Only attach once to prevent duplicate listeners
|
||||
if (overlayListenersAttached || overlays.length === 0) return;
|
||||
|
||||
// Close handlers
|
||||
// Close logic disabled when bootstrap admin (modal element has data-admin-bootstrap).
|
||||
// Additionally, if overlay has data-lock-close (set by MediaModerator), backdrop click will not close.
|
||||
overlays.forEach(overlay => {
|
||||
if (!overlay) return;
|
||||
const closeBtn = overlay.querySelector('button[aria-label="Close"]');
|
||||
if (closeBtn) {
|
||||
closeBtn.addEventListener('click', () => {
|
||||
closeOverlay(overlay);
|
||||
});
|
||||
}
|
||||
overlay.addEventListener('click', e => {
|
||||
const lockBackdrop = overlay.hasAttribute('data-lock-close');
|
||||
if (e.target === overlay && !isBootstrapLocked(overlay) && !lockBackdrop)
|
||||
closeOverlay(overlay);
|
||||
});
|
||||
});
|
||||
|
||||
// Escape key handler
|
||||
const escapeHandler = e => {
|
||||
if (e.key !== 'Escape') return;
|
||||
overlays.forEach(overlay => {
|
||||
if (!overlay || overlay.hidden) return;
|
||||
const lockBackdrop = overlay.hasAttribute('data-lock-close');
|
||||
if (!isBootstrapLocked(overlay) && !lockBackdrop) closeOverlay(overlay);
|
||||
});
|
||||
};
|
||||
// Store handler reference to prevent duplicates
|
||||
if (!window.__authModalEscapeHandler) {
|
||||
window.__authModalEscapeHandler = escapeHandler;
|
||||
window.addEventListener('keydown', escapeHandler);
|
||||
}
|
||||
|
||||
// Prevent form submission and call backend
|
||||
overlays.forEach(overlay => {
|
||||
if (!overlay) return;
|
||||
overlay.addEventListener('submit', e => e.preventDefault());
|
||||
});
|
||||
|
||||
// Enter key submits the active overlay (but not when a non-submit button has focus,
|
||||
// e.g. the switchToLogin / switchToSignup links — let the browser fire their click)
|
||||
overlays.forEach(overlay => {
|
||||
if (!overlay) return;
|
||||
overlay.addEventListener('keydown', e => {
|
||||
if (e.key === 'Enter' && !e.shiftKey && !e.ctrlKey && !e.altKey) {
|
||||
const focused = document.activeElement;
|
||||
if (
|
||||
focused &&
|
||||
focused.tagName === 'BUTTON' &&
|
||||
!focused.hasAttribute('data-auth-submit')
|
||||
) {
|
||||
return; // let the focused button handle its own click
|
||||
}
|
||||
e.preventDefault();
|
||||
const mode = overlay.getAttribute('data-auth-mode') || 'login';
|
||||
handleSubmit(mode);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// Submit button handlers
|
||||
submitBtns.forEach(btn => {
|
||||
btn.addEventListener('click', async () => {
|
||||
const mode = btn.getAttribute('data-mode');
|
||||
await handleSubmit(mode);
|
||||
});
|
||||
});
|
||||
|
||||
// Password strength listeners
|
||||
if (pwInput) {
|
||||
pwInput.addEventListener('input', () => {
|
||||
updatePwStrength();
|
||||
updateSignupState();
|
||||
});
|
||||
}
|
||||
if (pwConfirm) {
|
||||
pwConfirm.addEventListener('input', updateSignupState);
|
||||
}
|
||||
updatePwStrength();
|
||||
updateSignupState();
|
||||
|
||||
// Password visibility toggles
|
||||
overlays.forEach(overlay => {
|
||||
if (!overlay) return;
|
||||
overlay.querySelectorAll('button[data-target]').forEach(btn => {
|
||||
btn.addEventListener('click', () => {
|
||||
const targetId = btn.getAttribute('data-target');
|
||||
const input = targetId ? overlay.querySelector('#' + CSS.escape(targetId)) : null;
|
||||
if (!input) return;
|
||||
const isPw = input.getAttribute('type') === 'password';
|
||||
input.setAttribute('type', isPw ? 'text' : 'password');
|
||||
// Swap icon
|
||||
const icon = btn.querySelector('i');
|
||||
if (icon) {
|
||||
icon.classList.toggle('fa-eye');
|
||||
icon.classList.toggle('fa-eye-slash');
|
||||
}
|
||||
// Keep focus on input
|
||||
input.focus();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
// Switch between login and signup overlays
|
||||
const switchToSignupBtn = document.getElementById('switchToSignup');
|
||||
const switchToLoginBtn = document.getElementById('switchToLogin');
|
||||
|
||||
if (switchToSignupBtn && loginOverlay && signupOverlay) {
|
||||
switchToSignupBtn.addEventListener('click', e => {
|
||||
e.preventDefault();
|
||||
switchOverlay(loginOverlay, signupOverlay);
|
||||
});
|
||||
}
|
||||
|
||||
if (switchToLoginBtn && loginOverlay && signupOverlay) {
|
||||
switchToLoginBtn.addEventListener('click', e => {
|
||||
e.preventDefault();
|
||||
switchOverlay(signupOverlay, loginOverlay);
|
||||
});
|
||||
}
|
||||
|
||||
// Initialize overlays to hidden
|
||||
overlays.forEach(overlay => {
|
||||
if (!overlay) return;
|
||||
setHidden(overlay, true);
|
||||
overlay.classList.remove('active');
|
||||
});
|
||||
|
||||
overlayListenersAttached = true;
|
||||
}
|
||||
|
||||
// Initial overlay setup
|
||||
attachOverlayListeners();
|
||||
|
||||
// Submission helper used by both buttons and Enter key (needs to be accessible before listeners)
|
||||
async function handleSubmit(mode) {
|
||||
try {
|
||||
const isSignup = mode === 'signup' && signupPanel;
|
||||
let payload;
|
||||
if (isSignup) {
|
||||
const email = document.getElementById('signupEmail')?.value || '';
|
||||
const password = document.getElementById('signupPassword')?.value || '';
|
||||
const confirm = document.getElementById('signupConfirm')?.value || '';
|
||||
const username = document.getElementById('signupUsername')?.value || '';
|
||||
if (password !== confirm) {
|
||||
if (window.toast) {
|
||||
toast.error('Passwords do not match');
|
||||
} else {
|
||||
alert('Passwords do not match');
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (scorePassword(password) < 3) {
|
||||
if (window.toast) {
|
||||
toast.error('Password is too weak');
|
||||
} else {
|
||||
alert('Password is too weak');
|
||||
}
|
||||
return;
|
||||
}
|
||||
payload = { email, password, username };
|
||||
} else {
|
||||
payload = {
|
||||
email: document.getElementById('loginEmail')?.value || '',
|
||||
password: document.getElementById('loginPassword')?.value || '',
|
||||
totpToken: (loginTotpInput?.value || '').trim(),
|
||||
};
|
||||
}
|
||||
const res = await fetch(`/auth/${isSignup ? 'signup' : 'login'}`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
const data = await res.json().catch(() => ({}));
|
||||
if (!res.ok) {
|
||||
if (!isSignup && data?.mfaRequired) {
|
||||
setLoginTotpPrompt(true, data?.error || 'Authenticator code required');
|
||||
if (loginTotpInput) loginTotpInput.focus();
|
||||
}
|
||||
throw new Error(data?.error || 'Request failed');
|
||||
}
|
||||
if (!isSignup) setLoginTotpPrompt(false);
|
||||
setLoggedIn(true);
|
||||
const activeOverlay = isSignup ? signupOverlay : loginOverlay;
|
||||
if (!isBootstrapLocked(activeOverlay)) closeAll();
|
||||
try {
|
||||
window.dispatchEvent(
|
||||
new CustomEvent('auth:login-success', { detail: { mode: isSignup ? 'signup' : 'login' } })
|
||||
);
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
if (window.toast && typeof toast?.success === 'function') {
|
||||
toast.success(
|
||||
isSignup ? 'Account created. You are now logged in.' : 'Logged in successfully.'
|
||||
);
|
||||
}
|
||||
// If inside admin app, always redirect to dashboard after login
|
||||
if (isAdminApp) {
|
||||
window.location.replace('/dashboard');
|
||||
}
|
||||
} catch (e) {
|
||||
if (window.toast && typeof toast?.error === 'function') {
|
||||
toast.error(e?.message || 'Login failed');
|
||||
} else {
|
||||
alert(e?.message || 'Login failed');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// (keydown submit handler is registered inside attachOverlayListeners above)
|
||||
// Password strength evaluation
|
||||
function scorePassword(p) {
|
||||
if (!p) return 0;
|
||||
let score = 0;
|
||||
const length = p.length;
|
||||
if (length >= 6) score += 1;
|
||||
if (length >= 10) score += 1;
|
||||
if (/[a-z]/.test(p) && /[A-Z]/.test(p)) score += 1;
|
||||
if (/\d/.test(p)) score += 1;
|
||||
if (/[^A-Za-z0-9]/.test(p)) score += 1;
|
||||
if (length >= 14) score += 1;
|
||||
return Math.min(score, 5); // 0-5
|
||||
}
|
||||
function describeScore(s) {
|
||||
switch (s) {
|
||||
case 0:
|
||||
return 'Enter a password';
|
||||
case 1:
|
||||
return 'Very weak';
|
||||
case 2:
|
||||
return 'Weak';
|
||||
case 3:
|
||||
return 'Fair';
|
||||
case 4:
|
||||
return 'Good';
|
||||
case 5:
|
||||
return 'Strong';
|
||||
default:
|
||||
return '';
|
||||
}
|
||||
}
|
||||
function updatePwStrength() {
|
||||
if (!pwInput || !pwMeter || !pwFeedback) return;
|
||||
const val = pwInput.value || '';
|
||||
const s = scorePassword(val);
|
||||
pwMeter.dataset.score = String(s);
|
||||
pwFeedback.textContent = describeScore(s);
|
||||
// Visual width & color via inline style (can be refined in CSS)
|
||||
const bar = pwMeter.querySelector('span');
|
||||
if (bar) {
|
||||
const pct = (s / 5) * 100;
|
||||
bar.style.width = pct + '%';
|
||||
const colorClasses = [
|
||||
'bg-red-500',
|
||||
'bg-amber-500',
|
||||
'bg-amber-400',
|
||||
'bg-emerald-500',
|
||||
'bg-emerald-500',
|
||||
];
|
||||
colorClasses.forEach(c => bar.classList.remove(c));
|
||||
if (s >= 5) bar.classList.add('bg-emerald-500');
|
||||
else if (s >= 4) bar.classList.add('bg-emerald-500');
|
||||
else if (s >= 3) bar.classList.add('bg-amber-400');
|
||||
else if (s >= 2) bar.classList.add('bg-amber-500');
|
||||
else bar.classList.add('bg-red-500');
|
||||
}
|
||||
}
|
||||
function updateSignupState() {
|
||||
const btn = signupOverlay
|
||||
? signupOverlay.querySelector('[data-auth-submit][data-mode="signup"]')
|
||||
: null;
|
||||
if (!btn) return;
|
||||
const pw = pwInput ? pwInput.value || '' : '';
|
||||
const cf = pwConfirm ? pwConfirm.value || '' : '';
|
||||
const s = scorePassword(pw);
|
||||
const okStrength = s >= 3; // Fair or better
|
||||
const match = pw && cf && pw === cf;
|
||||
if (pwConfirmErr) {
|
||||
setHiddenClass(pwConfirmErr, !(cf && !match));
|
||||
}
|
||||
btn.disabled = !(okStrength && match);
|
||||
}
|
||||
|
||||
// Initialize scroll lock state (uses overflow-hidden Tailwind class)
|
||||
setNoScroll(false);
|
||||
|
||||
// Check authentication status
|
||||
(async () => {
|
||||
try {
|
||||
const r = await fetch('/auth/me');
|
||||
if (r.ok) {
|
||||
const j = await r.json();
|
||||
const isLoggedIn = !!(j && j.user);
|
||||
setLoggedIn(isLoggedIn);
|
||||
} else {
|
||||
setLoggedIn(false);
|
||||
}
|
||||
} catch {
|
||||
setLoggedIn(false);
|
||||
}
|
||||
// Admin bootstrap detection must run only in MediaModerator.
|
||||
if (isAdminApp) {
|
||||
try {
|
||||
const r2 = await fetch('/auth/bootstrap/admin-needed');
|
||||
if (r2.ok) {
|
||||
const j2 = await r2.json().catch(() => ({}));
|
||||
if (j2 && j2.adminNeeded) {
|
||||
const modalEl = signupOverlay ? signupOverlay.querySelector('[role="document"]') : null;
|
||||
if (modalEl) modalEl.removeAttribute('data-admin-bootstrap');
|
||||
setHidden(loginOpenBtn, false);
|
||||
setHidden(signupOpenBtn, false);
|
||||
const note =
|
||||
(signupOverlay &&
|
||||
signupOverlay.querySelector('[data-auth-note], #authNote, .u-text-dim')) ||
|
||||
document.querySelector('[data-auth-note], #authNote, .u-text-dim');
|
||||
if (note) {
|
||||
note.textContent =
|
||||
'No admin account exists yet. Sign up to create the first admin account.';
|
||||
}
|
||||
} else {
|
||||
const modalEl = signupOverlay ? signupOverlay.querySelector('[role="document"]') : null;
|
||||
if (modalEl) modalEl.removeAttribute('data-admin-bootstrap');
|
||||
const note =
|
||||
(loginOverlay &&
|
||||
loginOverlay.querySelector('[data-auth-note], #authNote, .u-text-dim')) ||
|
||||
document.querySelector('[data-auth-note], #authNote, .u-text-dim');
|
||||
if (note && !signupPanel) {
|
||||
note.textContent = 'Sign up disabled for admin panel.';
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
}
|
||||
})();
|
||||
|
||||
// Listen for dynamic component loading (when header is injected after initial page load)
|
||||
document.addEventListener('nc:componentsLoaded', () => {
|
||||
refreshButtonReferences();
|
||||
refreshOverlayReferences();
|
||||
attachButtonListeners();
|
||||
attachOverlayListeners();
|
||||
updateHeaderButton();
|
||||
});
|
||||
})();
|
||||
@@ -0,0 +1,15 @@
|
||||
(() => {
|
||||
const openAuth = () => {
|
||||
const mode =
|
||||
document.body?.dataset?.authOpenMode ||
|
||||
document.querySelector('[data-auth-open-mode]')?.getAttribute('data-auth-open-mode') ||
|
||||
'login';
|
||||
const button = document.getElementById(
|
||||
mode === 'signup' ? 'authSignupOpenBtn' : 'authLoginOpenBtn'
|
||||
);
|
||||
if (button) button.click();
|
||||
};
|
||||
|
||||
const forceButton = document.getElementById('forceAuthOpen');
|
||||
if (forceButton) forceButton.addEventListener('click', openAuth);
|
||||
})();
|
||||
@@ -0,0 +1,63 @@
|
||||
/**
|
||||
* NCAuthRequired — standardized "login required" screen.
|
||||
*
|
||||
* Usage:
|
||||
* NCAuthRequired.render(containerEl);
|
||||
*
|
||||
* The rendered prompt includes a "Log In" button that opens the shared auth
|
||||
* modal. On successful login (auth:login-success event) the page reloads
|
||||
* automatically so the protected content can be fetched.
|
||||
*/
|
||||
window.NCAuthRequired = (() => {
|
||||
function escapeHtml(s) {
|
||||
const d = document.createElement('div');
|
||||
d.textContent = s;
|
||||
return d.innerHTML;
|
||||
}
|
||||
|
||||
/**
|
||||
* Render a login-required prompt inside `container`.
|
||||
* @param {HTMLElement} container — element whose innerHTML will be replaced.
|
||||
*/
|
||||
function render(container) {
|
||||
if (!container) return;
|
||||
const message = 'You need to log in to view this page.';
|
||||
const icon = 'fas fa-lock';
|
||||
|
||||
// Reset container layout so the prompt always spans full width and centers.
|
||||
container.classList.add('flex', 'justify-center');
|
||||
container.innerHTML = [
|
||||
'<div class="flex min-h-[60vh] w-full flex-col items-center justify-center gap-3 px-4 py-4 text-center" data-auth-required="1" role="region" aria-label="Authentication required">',
|
||||
' <i class="' +
|
||||
escapeHtml(icon) +
|
||||
' text-4xl text-[var(--color-text-dim)]" aria-hidden="true"></i>',
|
||||
' <p class="max-w-xs text-base text-[var(--color-text-dim)]">' +
|
||||
escapeHtml(message) +
|
||||
'</p>',
|
||||
' <button type="button" data-auth-required-login class="inline-flex cursor-pointer items-center gap-2 rounded-full bg-blue-600 px-4 py-3 text-sm font-semibold text-white shadow-md hover:bg-blue-500 focus:outline-none focus:ring-2 focus:ring-blue-400 focus:ring-offset-2 focus:ring-offset-[var(--color-bg)]">',
|
||||
' <i class="fas fa-right-to-bracket" aria-hidden="true"></i> Log In',
|
||||
' </button>',
|
||||
'</div>',
|
||||
].join('\n');
|
||||
|
||||
// Wire the Log In button to open the shared auth modal
|
||||
const btn = container.querySelector('[data-auth-required-login]');
|
||||
if (btn) {
|
||||
btn.addEventListener('click', () => {
|
||||
const opener = document.getElementById('authLoginOpenBtn');
|
||||
if (opener) opener.click();
|
||||
});
|
||||
}
|
||||
|
||||
// Auto-reload on successful login so the page can fetch protected data
|
||||
window.addEventListener(
|
||||
'auth:login-success',
|
||||
() => {
|
||||
window.location.reload();
|
||||
},
|
||||
{ once: true }
|
||||
);
|
||||
}
|
||||
|
||||
return { render };
|
||||
})();
|
||||
@@ -0,0 +1,24 @@
|
||||
(() => {
|
||||
const tokenInput = document.getElementById('token');
|
||||
const passwordInput = document.getElementById('newPassword');
|
||||
if (
|
||||
!tokenInput ||
|
||||
!passwordInput ||
|
||||
!window.NCAuthForm ||
|
||||
typeof window.NCAuthForm.bindJsonSubmit !== 'function'
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
window.NCAuthForm.bindJsonSubmit({
|
||||
endpoint: '/auth/reset/perform',
|
||||
formId: 'resetForm',
|
||||
resultId: 'resetDone',
|
||||
buildPayload() {
|
||||
return {
|
||||
token: tokenInput.value,
|
||||
password: passwordInput.value,
|
||||
};
|
||||
},
|
||||
});
|
||||
})();
|
||||
@@ -0,0 +1,15 @@
|
||||
(() => {
|
||||
const emailInput = document.getElementById('resetEmail');
|
||||
if (!emailInput || !window.NCAuthForm || typeof window.NCAuthForm.bindJsonSubmit !== 'function') {
|
||||
return;
|
||||
}
|
||||
|
||||
window.NCAuthForm.bindJsonSubmit({
|
||||
endpoint: '/auth/reset/request',
|
||||
formId: 'resetReqForm',
|
||||
resultId: 'resetResult',
|
||||
buildPayload() {
|
||||
return { email: emailInput.value };
|
||||
},
|
||||
});
|
||||
})();
|
||||
@@ -0,0 +1,21 @@
|
||||
/**
|
||||
* login-gate.js
|
||||
* Client-side initialiser for the server-side login gate page
|
||||
* (served by requireLoginIfConfigured middleware in MediaShared).
|
||||
*
|
||||
* Sources: /shared/js/ui/toast.js, /shared/js/auth/auth-modal.js,
|
||||
* /shared/js/auth/auth-required.js must be loaded before this script.
|
||||
*
|
||||
* On successful login the page is reloaded so the browser re-enters the
|
||||
* protected service with a valid session.
|
||||
*/
|
||||
document.addEventListener('DOMContentLoaded', function () {
|
||||
const gate = document.getElementById('auth-gate');
|
||||
if (gate && window.NCAuthRequired) {
|
||||
window.NCAuthRequired.render(gate);
|
||||
}
|
||||
|
||||
document.addEventListener('auth:login-success', function () {
|
||||
window.location.reload();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,485 @@
|
||||
const toast = globalThis.toast;
|
||||
const profileEditState = {
|
||||
editing: false,
|
||||
snapshot: { username: '', email: '' },
|
||||
};
|
||||
|
||||
function byId(id) {
|
||||
return document.getElementById(id);
|
||||
}
|
||||
|
||||
function setText(id, value) {
|
||||
const element = byId(id);
|
||||
if (element) element.textContent = value;
|
||||
}
|
||||
|
||||
function setValue(id, value) {
|
||||
const element = byId(id);
|
||||
if (element) element.value = value;
|
||||
}
|
||||
|
||||
function parseApiError(payload, fallback) {
|
||||
return payload?.error || payload?.message || payload?.data?.error || fallback;
|
||||
}
|
||||
|
||||
function setButtonBusy(id, busy) {
|
||||
const button = byId(id);
|
||||
if (!button) return;
|
||||
button.disabled = !!busy;
|
||||
}
|
||||
|
||||
function setMfaBadge(enabled) {
|
||||
const badge = byId('mfaBadge');
|
||||
if (!badge) return;
|
||||
if (enabled) {
|
||||
badge.className =
|
||||
'inline-flex items-center rounded-full border border-emerald-500/40 bg-emerald-500/15 px-3 py-1 text-xs font-semibold text-emerald-300';
|
||||
badge.textContent = 'MFA Enabled';
|
||||
return;
|
||||
}
|
||||
badge.className =
|
||||
'inline-flex items-center rounded-full border border-amber-500/40 bg-amber-500/10 px-3 py-1 text-xs font-semibold text-amber-300';
|
||||
badge.textContent = 'MFA Disabled';
|
||||
}
|
||||
|
||||
function resetTotpWizard() {
|
||||
const wizard = byId('totpWizard');
|
||||
if (wizard) wizard.hidden = true;
|
||||
setValue('totpCode', '');
|
||||
const manualLabel = byId('totpManualLabel');
|
||||
if (manualLabel) manualLabel.hidden = true;
|
||||
setText('totpManualKey', '');
|
||||
}
|
||||
|
||||
function extractTotpSecret(otpauth) {
|
||||
try {
|
||||
const parsed = new URL(String(otpauth || ''));
|
||||
return parsed.searchParams.get('secret') || '';
|
||||
} catch {
|
||||
return '';
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeTotpCode(raw) {
|
||||
return String(raw || '')
|
||||
.replace(/\D+/g, '')
|
||||
.slice(0, 6);
|
||||
}
|
||||
|
||||
function showBackupCodes(codes) {
|
||||
const panel = byId('backupCodesPanel');
|
||||
const list = byId('backupCodesList');
|
||||
if (!panel || !list || !Array.isArray(codes)) return;
|
||||
list.innerHTML = '';
|
||||
codes.forEach(code => {
|
||||
const li = document.createElement('li');
|
||||
li.textContent = code;
|
||||
list.appendChild(li);
|
||||
});
|
||||
panel.hidden = false;
|
||||
}
|
||||
|
||||
function hideBackupCodes() {
|
||||
const panel = byId('backupCodesPanel');
|
||||
if (panel) panel.hidden = true;
|
||||
const list = byId('backupCodesList');
|
||||
if (list) list.innerHTML = '';
|
||||
}
|
||||
|
||||
function hideBackupCodesRegenerateForm() {
|
||||
const form = byId('backupCodesRegenerateForm');
|
||||
if (form) form.hidden = true;
|
||||
}
|
||||
|
||||
async function loadBackupCodesStatus() {
|
||||
const manage = byId('backupCodesManage');
|
||||
if (!manage) return;
|
||||
try {
|
||||
const response = await fetch('/api/security/totp/backup-codes/status');
|
||||
const payload = await response.json().catch(() => ({}));
|
||||
if (!response.ok || !payload?.data?.mfaEnabled) {
|
||||
manage.hidden = true;
|
||||
return;
|
||||
}
|
||||
manage.hidden = false;
|
||||
const remaining = Number(payload.data.remaining) || 0;
|
||||
setText(
|
||||
'backupCodesRemaining',
|
||||
`Backup codes: ${remaining} of 10 remaining.` +
|
||||
(remaining <= 2 ? ' Consider regenerating soon.' : '')
|
||||
);
|
||||
} catch {
|
||||
manage.hidden = true;
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeProfileEntryValue(value) {
|
||||
return String(value || '').trim();
|
||||
}
|
||||
|
||||
function readProfileEntryInputs() {
|
||||
return {
|
||||
username: normalizeProfileEntryValue(byId('usernameInput')?.value),
|
||||
email: normalizeProfileEntryValue(byId('emailInput')?.value),
|
||||
};
|
||||
}
|
||||
|
||||
function applyProfileEntryInputs({ username = '', email = '' } = {}) {
|
||||
setValue('usernameInput', username);
|
||||
setValue('emailInput', email);
|
||||
}
|
||||
|
||||
function profileEntryValuesEqual(a, b) {
|
||||
return (
|
||||
normalizeProfileEntryValue(a?.username) === normalizeProfileEntryValue(b?.username) &&
|
||||
normalizeProfileEntryValue(a?.email) === normalizeProfileEntryValue(b?.email)
|
||||
);
|
||||
}
|
||||
|
||||
function setProfileEditMode(editing, { restore = false } = {}) {
|
||||
const isEditing = Boolean(editing);
|
||||
const form = byId('editProfileForm');
|
||||
if (form) form.hidden = !isEditing;
|
||||
if (!isEditing && restore) {
|
||||
applyProfileEntryInputs(profileEditState.snapshot);
|
||||
}
|
||||
const editButton = byId('editProfileButton');
|
||||
if (editButton) editButton.disabled = isEditing;
|
||||
profileEditState.editing = isEditing;
|
||||
}
|
||||
|
||||
async function fetchUserProfile({ silent = false } = {}) {
|
||||
if (!byId('profile-container')) return;
|
||||
try {
|
||||
const response = await fetch('/api/profile');
|
||||
const payload = await response.json().catch(() => ({}));
|
||||
const user = payload?.data || payload?.profile || payload?.user || null;
|
||||
if (!response.ok || !user) {
|
||||
throw new Error(parseApiError(payload, 'Failed to load profile'));
|
||||
}
|
||||
|
||||
const entries = {
|
||||
username: normalizeProfileEntryValue(user.username || 'Anonymous'),
|
||||
email: normalizeProfileEntryValue(user.email || 'Not set'),
|
||||
};
|
||||
|
||||
setText('username', entries.username);
|
||||
setText('email', entries.email);
|
||||
|
||||
const profilePicture = byId('profilePicture');
|
||||
if (profilePicture) {
|
||||
profilePicture.src =
|
||||
user.avatar_url || user.profilePicture || '/shared/images/default-avatar.svg';
|
||||
}
|
||||
|
||||
if (!profileEditState.editing) {
|
||||
applyProfileEntryInputs(entries);
|
||||
profileEditState.snapshot = entries;
|
||||
}
|
||||
|
||||
const mfaEnabled = !!user.mfaEnabled;
|
||||
setMfaBadge(mfaEnabled);
|
||||
setText('mfaStatus', mfaEnabled ? 'TOTP is enabled on your account.' : 'TOTP is not enabled.');
|
||||
|
||||
const setup = byId('mfaSetup');
|
||||
const disable = byId('mfaDisable');
|
||||
if (setup) setup.hidden = mfaEnabled;
|
||||
if (disable) disable.hidden = !mfaEnabled;
|
||||
if (mfaEnabled) resetTotpWizard();
|
||||
if (mfaEnabled) {
|
||||
await loadBackupCodesStatus();
|
||||
} else {
|
||||
const manage = byId('backupCodesManage');
|
||||
if (manage) manage.hidden = true;
|
||||
hideBackupCodesRegenerateForm();
|
||||
}
|
||||
} catch (error) {
|
||||
if (!silent) {
|
||||
toast?.error?.(error?.message || 'Profile load error');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function openProfileEdit() {
|
||||
if (profileEditState.editing) return;
|
||||
profileEditState.snapshot = {
|
||||
username: normalizeProfileEntryValue(
|
||||
byId('usernameInput')?.value || byId('username')?.textContent || ''
|
||||
),
|
||||
email: normalizeProfileEntryValue(
|
||||
byId('emailInput')?.value || byId('email')?.textContent || ''
|
||||
),
|
||||
};
|
||||
applyProfileEntryInputs(profileEditState.snapshot);
|
||||
setProfileEditMode(true);
|
||||
byId('usernameInput')?.focus();
|
||||
}
|
||||
|
||||
function closeProfileEdit({ restore = true } = {}) {
|
||||
setProfileEditMode(false, { restore });
|
||||
}
|
||||
|
||||
async function saveProfileChanges() {
|
||||
const draft = readProfileEntryInputs();
|
||||
if (profileEntryValuesEqual(draft, profileEditState.snapshot)) {
|
||||
closeProfileEdit({ restore: false });
|
||||
return;
|
||||
}
|
||||
|
||||
setButtonBusy('profileSaveBtn', true);
|
||||
setButtonBusy('profileCancelBtn', true);
|
||||
try {
|
||||
const response = await fetch('/api/profile', {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(draft),
|
||||
});
|
||||
const payload = await response.json().catch(() => ({}));
|
||||
if (!response.ok) {
|
||||
throw new Error(parseApiError(payload, 'Save failed'));
|
||||
}
|
||||
profileEditState.snapshot = draft;
|
||||
toast?.success?.('Profile updated');
|
||||
closeProfileEdit({ restore: false });
|
||||
await fetchUserProfile({ silent: true });
|
||||
} catch (error) {
|
||||
toast?.error?.(error?.message || 'Save failed');
|
||||
} finally {
|
||||
setButtonBusy('profileSaveBtn', false);
|
||||
setButtonBusy('profileCancelBtn', false);
|
||||
const editButton = byId('editProfileButton');
|
||||
if (editButton) editButton.disabled = profileEditState.editing;
|
||||
}
|
||||
}
|
||||
|
||||
async function changePassword() {
|
||||
const newPassword = byId('newPw')?.value || '';
|
||||
if (!newPassword) {
|
||||
toast?.error?.('New password is required');
|
||||
return;
|
||||
}
|
||||
|
||||
setButtonBusy('btnChangePw', true);
|
||||
try {
|
||||
const response = await fetch('/api/profile/password', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ newPassword }),
|
||||
});
|
||||
const payload = await response.json().catch(() => ({}));
|
||||
if (!response.ok) {
|
||||
throw new Error(parseApiError(payload, 'Change failed'));
|
||||
}
|
||||
toast?.success?.('Password updated');
|
||||
setValue('newPw', '');
|
||||
} catch (error) {
|
||||
toast?.error?.(error?.message || 'Change failed');
|
||||
} finally {
|
||||
setButtonBusy('btnChangePw', false);
|
||||
}
|
||||
}
|
||||
|
||||
async function startTotpSetup() {
|
||||
setButtonBusy('btnStartTotp', true);
|
||||
try {
|
||||
const response = await fetch('/api/security/totp/initiate');
|
||||
const payload = await response.json().catch(() => ({}));
|
||||
if (!response.ok || !(payload?.data?.qr || payload?.data?.otpauth)) {
|
||||
throw new Error(parseApiError(payload, 'Failed to start TOTP'));
|
||||
}
|
||||
|
||||
const wizard = byId('totpWizard');
|
||||
const qrImage = byId('totpQr');
|
||||
if (wizard) wizard.hidden = false;
|
||||
if (qrImage && payload?.data?.qr) qrImage.src = payload.data.qr;
|
||||
|
||||
const secret = extractTotpSecret(payload?.data?.otpauth);
|
||||
if (secret) {
|
||||
setText('totpManualKey', secret);
|
||||
const manualLabel = byId('totpManualLabel');
|
||||
if (manualLabel) manualLabel.hidden = false;
|
||||
}
|
||||
byId('totpCode')?.focus();
|
||||
} catch (error) {
|
||||
toast?.error?.(error?.message || 'Failed to start TOTP');
|
||||
} finally {
|
||||
setButtonBusy('btnStartTotp', false);
|
||||
}
|
||||
}
|
||||
|
||||
async function verifyTotpSetup() {
|
||||
const token = normalizeTotpCode(byId('totpCode')?.value || '');
|
||||
if (token.length !== 6) {
|
||||
toast?.error?.('Enter a valid 6-digit TOTP code');
|
||||
return;
|
||||
}
|
||||
|
||||
setButtonBusy('btnVerifyTotp', true);
|
||||
try {
|
||||
const response = await fetch('/api/security/totp/verify', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ token }),
|
||||
});
|
||||
const payload = await response.json().catch(() => ({}));
|
||||
if (!response.ok) {
|
||||
throw new Error(parseApiError(payload, 'Invalid code'));
|
||||
}
|
||||
|
||||
toast?.success?.('MFA enabled');
|
||||
resetTotpWizard();
|
||||
if (Array.isArray(payload?.data?.backupCodes)) {
|
||||
showBackupCodes(payload.data.backupCodes);
|
||||
}
|
||||
await fetchUserProfile({ silent: true });
|
||||
} catch (error) {
|
||||
toast?.error?.(error?.message || 'Invalid code');
|
||||
} finally {
|
||||
setButtonBusy('btnVerifyTotp', false);
|
||||
}
|
||||
}
|
||||
|
||||
async function regenerateBackupCodes() {
|
||||
setButtonBusy('btnConfirmRegenerateBackupCodes', true);
|
||||
try {
|
||||
const response = await fetch('/api/security/totp/backup-codes/regenerate', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({}),
|
||||
});
|
||||
const payload = await response.json().catch(() => ({}));
|
||||
if (!response.ok) {
|
||||
throw new Error(parseApiError(payload, 'Failed to regenerate backup codes'));
|
||||
}
|
||||
|
||||
toast?.success?.('Backup codes regenerated');
|
||||
hideBackupCodesRegenerateForm();
|
||||
if (Array.isArray(payload?.data?.backupCodes)) {
|
||||
showBackupCodes(payload.data.backupCodes);
|
||||
}
|
||||
await loadBackupCodesStatus();
|
||||
} catch (error) {
|
||||
toast?.error?.(error?.message || 'Failed to regenerate backup codes');
|
||||
} finally {
|
||||
setButtonBusy('btnConfirmRegenerateBackupCodes', false);
|
||||
}
|
||||
}
|
||||
|
||||
async function disableTotp() {
|
||||
const token = normalizeTotpCode(window.prompt('Enter the current 6-digit authenticator code to disable MFA:') || '');
|
||||
if (token.length !== 6) {
|
||||
toast?.error?.('Enter a valid 6-digit TOTP code');
|
||||
return;
|
||||
}
|
||||
setButtonBusy('btnDisableTotp', true);
|
||||
try {
|
||||
const response = await fetch('/api/security/totp/disable', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ token }),
|
||||
});
|
||||
const payload = await response.json().catch(() => ({}));
|
||||
if (!response.ok) {
|
||||
throw new Error(parseApiError(payload, 'Disable failed'));
|
||||
}
|
||||
|
||||
toast?.success?.('MFA disabled');
|
||||
await fetchUserProfile({ silent: true });
|
||||
} catch (error) {
|
||||
toast?.error?.(error?.message || 'Disable failed');
|
||||
} finally {
|
||||
setButtonBusy('btnDisableTotp', false);
|
||||
}
|
||||
}
|
||||
|
||||
async function uploadAvatar() {
|
||||
const file = byId('avatarFile')?.files?.[0];
|
||||
if (!file) {
|
||||
toast?.error?.('Choose an image');
|
||||
return;
|
||||
}
|
||||
|
||||
setButtonBusy('btnUploadAvatar', true);
|
||||
try {
|
||||
const formData = new FormData();
|
||||
formData.append('avatar', file);
|
||||
const response = await fetch('/api/profile/avatar', { method: 'POST', body: formData });
|
||||
const payload = await response.json().catch(() => ({}));
|
||||
if (!response.ok) {
|
||||
throw new Error(parseApiError(payload, 'Upload failed'));
|
||||
}
|
||||
|
||||
toast?.success?.('Avatar updated');
|
||||
await fetchUserProfile({ silent: true });
|
||||
} catch (error) {
|
||||
toast?.error?.(error?.message || 'Upload failed');
|
||||
} finally {
|
||||
setButtonBusy('btnUploadAvatar', false);
|
||||
}
|
||||
}
|
||||
|
||||
function wireProfileEvents() {
|
||||
byId('editProfileButton')?.addEventListener('click', openProfileEdit);
|
||||
byId('editProfileForm')?.addEventListener('submit', event => {
|
||||
event.preventDefault();
|
||||
saveProfileChanges();
|
||||
});
|
||||
byId('profileCancelBtn')?.addEventListener('click', () => closeProfileEdit({ restore: true }));
|
||||
byId('changePasswordForm')?.addEventListener('submit', event => {
|
||||
event.preventDefault();
|
||||
changePassword();
|
||||
});
|
||||
byId('btnStartTotp')?.addEventListener('click', startTotpSetup);
|
||||
byId('btnVerifyTotp')?.addEventListener('click', verifyTotpSetup);
|
||||
byId('mfaDisableForm')?.addEventListener('submit', event => {
|
||||
event.preventDefault();
|
||||
disableTotp();
|
||||
});
|
||||
byId('btnUploadAvatar')?.addEventListener('click', uploadAvatar);
|
||||
|
||||
byId('btnDismissBackupCodes')?.addEventListener('click', hideBackupCodes);
|
||||
byId('btnCopyBackupCodes')?.addEventListener('click', async () => {
|
||||
const codes = Array.from(byId('backupCodesList')?.children || []).map(li => li.textContent);
|
||||
if (!codes.length) return;
|
||||
try {
|
||||
await navigator.clipboard.writeText(codes.join('\n'));
|
||||
toast?.success?.('Backup codes copied');
|
||||
} catch {
|
||||
toast?.error?.('Could not copy — please copy manually');
|
||||
}
|
||||
});
|
||||
byId('btnRegenerateBackupCodes')?.addEventListener('click', () => {
|
||||
const form = byId('backupCodesRegenerateForm');
|
||||
if (form) form.hidden = false;
|
||||
});
|
||||
byId('btnCancelRegenerateBackupCodes')?.addEventListener('click', hideBackupCodesRegenerateForm);
|
||||
byId('backupCodesRegenerateForm')?.addEventListener('submit', event => {
|
||||
event.preventDefault();
|
||||
regenerateBackupCodes();
|
||||
});
|
||||
|
||||
byId('totpCode')?.addEventListener('keydown', event => {
|
||||
if (event.key === 'Enter') {
|
||||
event.preventDefault();
|
||||
verifyTotpSetup();
|
||||
}
|
||||
});
|
||||
|
||||
const profileImage = byId('profilePicture');
|
||||
if (profileImage) {
|
||||
profileImage.addEventListener(
|
||||
'error',
|
||||
() => {
|
||||
const fallbackSrc = profileImage.getAttribute('data-fallback-src');
|
||||
if (fallbackSrc && profileImage.src !== fallbackSrc) profileImage.src = fallbackSrc;
|
||||
},
|
||||
{ once: true }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
document.addEventListener('DOMContentLoaded', () => {
|
||||
if (!byId('profile-container')) return;
|
||||
wireProfileEvents();
|
||||
fetchUserProfile();
|
||||
});
|
||||
Reference in new issue
Block a user