import { showToast, toggleVisibility, attachEnterKeyListener } from './domUtils.js'; import { sendRequest } from './networkUtils.js'; import { t, applyTranslations, setLocale } from './i18n.js'; import { loadAdminConfigFunc, updateAuthenticatedUI } from './auth.js'; let lastLoginData = null; export function setLastLoginData(data) { lastLoginData = data; // expose to auth.js so it can tell form-login vs basic/oidc //window.__lastLoginData = data; } export function openTOTPLoginModal() { let totpLoginModal = document.getElementById("totpLoginModal"); const isDarkMode = document.body.classList.contains("dark-mode"); const modalBg = isDarkMode ? "#2c2c2c" : "#fff"; const textColor = isDarkMode ? "#e0e0e0" : "#000"; if (!totpLoginModal) { totpLoginModal = document.createElement("div"); totpLoginModal.id = "totpLoginModal"; totpLoginModal.style.cssText = ` position: fixed; top: 0; left: 0; width: 100vw; height: 100vh; background-color: rgba(0,0,0,0.5); display: flex; justify-content: center; align-items: center; z-index: 3200; `; totpLoginModal.innerHTML = `
`; document.body.appendChild(totpLoginModal); // Close button document.getElementById("closeTOTPLoginModal").addEventListener("click", () => { totpLoginModal.style.display = "none"; }); // Toggle between TOTP and Recovery document.getElementById("toggleRecovery").addEventListener("click", function (e) { e.preventDefault(); const totpSection = document.getElementById("totpSection"); const recoverySection = document.getElementById("recoverySection"); const toggleLink = this; if (recoverySection.style.display === "none") { totpSection.style.display = "none"; recoverySection.style.display = "block"; toggleLink.textContent = t("use_totp_code_instead"); } else { recoverySection.style.display = "none"; totpSection.style.display = "block"; toggleLink.textContent = t("use_recovery_code_instead"); } }); // Recovery submission document.getElementById("submitRecovery").addEventListener("click", () => { const recoveryCode = document.getElementById("recoveryInput").value.trim(); if (!recoveryCode) { showToast(t("please_enter_recovery_code")); return; } fetch("/api/totp_recover.php", { method: "POST", credentials: "include", headers: { "Content-Type": "application/json", "X-CSRF-Token": window.csrfToken }, body: JSON.stringify({ recovery_code: recoveryCode }) }) .then(res => res.json()) .then(json => { if (json.status === "ok") { window.location.href = "/index.html"; } else { showToast(json.message || t("recovery_code_verification_failed")); } }) .catch(() => { showToast(t("error_verifying_recovery_code")); }); }); // TOTP submission const totpInput = document.getElementById("totpLoginInput"); totpInput.focus(); totpInput.addEventListener("input", async function () { const code = this.value.trim(); if (code.length !== 6) return; const tokenRes = await fetch("/api/auth/token.php", { credentials: "include" }); if (!tokenRes.ok) { showToast(t("totp_verification_failed")); return; } window.csrfToken = (await tokenRes.json()).csrf_token; const res = await fetch("/api/totp_verify.php", { method: "POST", credentials: "include", headers: { "Content-Type": "application/json", "X-CSRF-Token": window.csrfToken }, body: JSON.stringify({ totp_code: code }) }); if (res.ok) { const json = await res.json(); if (json.status === "ok") { window.location.href = "/index.html"; return; } showToast(json.message || t("totp_verification_failed")); } else { showToast(t("totp_verification_failed")); } this.value = ""; totpLoginModal.style.display = "flex"; this.focus(); }); } else { // Re-open existing modal totpLoginModal.style.display = "flex"; const totpInput = document.getElementById("totpLoginInput"); totpInput.value = ""; totpInput.style.display = "block"; totpInput.focus(); document.getElementById("recoverySection").style.display = "none"; } } /** * Fetch current user info (username, profile_picture, totp_enabled) */ async function fetchCurrentUser() { try { const res = await fetch('/api/profile/getCurrentUser.php', { credentials: 'include' }); if (!res.ok) throw new Error(`HTTP ${res.status}`); return await res.json(); } catch (e) { console.warn('fetchCurrentUser failed:', e); return {}; } } /** * Normalize any profile‐picture URL: * - strip leading colons * - ensure exactly one leading slash */ function normalizePicUrl(raw) { if (!raw) return ''; // take only what's after the last colon const parts = raw.split(':'); let pic = parts[parts.length - 1]; // strip any stray colons pic = pic.replace(/^:+/, ''); // ensure leading slash if (pic && !pic.startsWith('/')) pic = '/' + pic; return pic; } export async function openUserPanel() { // 1) load data const { username = 'User', profile_picture = '', totp_enabled = false } = await fetchCurrentUser(); const raw = profile_picture; const picUrl = normalizePicUrl(raw); // 2) dark‐mode helpers const isDark = document.body.classList.contains('dark-mode'); const overlayBg = isDark ? 'rgba(0,0,0,0.7)' : 'rgba(0,0,0,0.3)'; const contentCss = ` background: ${isDark ? '#2c2c2c' : '#fff'}; color: ${isDark ? '#e0e0e0' : '#000'}; padding: 20px; max-width: 600px; width: 90%; border-radius: 8px; overflow-y: auto; max-height: 415px; border: ${isDark ? '1px solid #444' : '1px solid #ccc'}; box-sizing: border-box; /* hide scrollbar in Firefox */ scrollbar-width: none; /* hide scrollbar in IE 10+ */ -ms-overflow-style: none; `; // 3) build or re-use modal let modal = document.getElementById('userPanelModal'); if (!modal) { modal = document.createElement('div'); modal.id = 'userPanelModal'; modal.style.cssText = ` position:fixed; top:0; left:0; right:0; bottom:0; background:${overlayBg}; display:flex; align-items:center; justify-content:center; z-index:1000; `; modal.innerHTML = ` `; document.body.appendChild(modal); // --- wire up handlers --- modal.querySelector('#closeUserPanel') .addEventListener('click', () => modal.style.display = 'none'); modal.querySelector('#openChangePasswordModalBtn') .addEventListener('click', () => { document.getElementById('changePasswordModal').style.display = 'block'; }); // TOTP const totpCb = modal.querySelector('#userTOTPEnabled'); totpCb.addEventListener('change', async function () { const resp = await fetch('/api/updateUserPanel.php', { method: 'POST', credentials: 'include', headers: { 'Content-Type': 'application/json', 'X-CSRF-Token': window.csrfToken }, body: JSON.stringify({ totp_enabled: this.checked }) }); const js = await resp.json(); if (!js.success) showToast(js.error || t('error_updating_totp_setting')); else if (this.checked) openTOTPModal(); }); // Language const langSel = modal.querySelector('#languageSelector'); langSel.addEventListener('change', function () { localStorage.setItem('language', this.value); setLocale(this.value); applyTranslations(); }); // Auto‐upload on file select const fileInput = modal.querySelector('#profilePicInput'); fileInput.addEventListener('change', async function () { const file = this.files[0]; if (!file) return; // preview immediately const img = modal.querySelector('#profilePicPreview'); img.src = URL.createObjectURL(file); // upload const fd = new FormData(); fd.append('profile_picture', file); try { const res = await fetch('/api/profile/uploadPicture.php', { method: 'POST', credentials: 'include', headers: { 'X-CSRF-Token': window.csrfToken }, body: fd }); const text = await res.text(); const js = JSON.parse(text || '{}'); if (!res.ok) { showToast(js.error || t('error_updating_picture')); return; } const newUrl = normalizePicUrl(js.url); img.src = newUrl; localStorage.setItem('profilePicUrl', newUrl); // refresh the header immediately updateAuthenticatedUI(window.__lastAuthData || {}); showToast(t('profile_picture_updated')); } catch (e) { console.error(e); showToast(t('error_updating_picture')); } }); } else { modal.style.background = overlayBg; const contentEl = modal.querySelector('.modal-content'); contentEl.style.cssText = contentCss; // re-open: sync current values modal.querySelector('#profilePicPreview').src = picUrl || '/images/default-avatar.png'; modal.querySelector('#userTOTPEnabled').checked = totp_enabled; modal.querySelector('#languageSelector').value = localStorage.getItem('language') || 'en'; } // show modal.style.display = 'flex'; } function showRecoveryCodeModal(recoveryCode) { const recoveryModal = document.createElement("div"); recoveryModal.id = "recoveryModal"; recoveryModal.style.cssText = ` position: fixed; top: 0; left: 0; width: 100vw; height: 100vh; background-color: rgba(0,0,0,0.3); display: flex; justify-content: center; align-items: center; z-index: 3200; `; recoveryModal.innerHTML = `${t("please_save_recovery_code")}
${recoveryCode}