// ===== USER.JS - Авторизация и сессия ===== const STORAGE_KEYS = { username: 'turborfq_username', columns: 'turborfq_columns', lastTable: 'turborfq_lastTable', tableState: 'turborfq_tableState' }; // Сохранить состояние таблицы (фильтры, страница) function saveTableState() { if (!currentSchema || !currentTable || !table) return; const tableKey = `${currentSchema}.${currentTable}`; const headerFilters = table.getHeaderFilters ? table.getHeaderFilters() : []; const page = table.getPage ? table.getPage() : 1; let allStates = {}; try { const saved = localStorage.getItem(STORAGE_KEYS.tableState); if (saved) allStates = JSON.parse(saved); } catch (e) {} allStates[tableKey] = { filters: headerFilters.filter(f => f.value), page: page }; localStorage.setItem(STORAGE_KEYS.tableState, JSON.stringify(allStates)); } // Загрузить состояние таблицы function loadTableState() { if (!currentSchema || !currentTable) return null; const tableKey = `${currentSchema}.${currentTable}`; try { const saved = localStorage.getItem(STORAGE_KEYS.tableState); if (saved) { const allStates = JSON.parse(saved); return allStates[tableKey] || null; } } catch (e) {} return null; } // Сохранить последнюю открытую таблицу function saveLastTable() { if (!currentSchema || !currentTable) return; localStorage.setItem(STORAGE_KEYS.lastTable, JSON.stringify({ schema: currentSchema, table: currentTable })); } // Загрузить последнюю таблицу function loadLastTable() { try { const saved = localStorage.getItem(STORAGE_KEYS.lastTable); if (saved) return JSON.parse(saved); } catch (e) {} return null; } // Сохранить видимость столбцов function saveColumnVisibility(visibilityMap) { if (!currentSchema || !currentTable) return; const tableKey = `${currentSchema}.${currentTable}`; let allSettings = {}; try { const saved = localStorage.getItem(STORAGE_KEYS.columns); if (saved) allSettings = JSON.parse(saved); } catch (e) {} allSettings[tableKey] = visibilityMap; localStorage.setItem(STORAGE_KEYS.columns, JSON.stringify(allSettings)); console.log('💾 Видимость столбцов сохранена:', tableKey); } // Загрузить видимость столбцов function loadColumnVisibility() { if (!currentSchema || !currentTable) return null; const tableKey = `${currentSchema}.${currentTable}`; try { const saved = localStorage.getItem(STORAGE_KEYS.columns); if (saved) { const allSettings = JSON.parse(saved); return allSettings[tableKey] || null; } } catch (e) { console.error('Ошибка загрузки видимости столбцов:', e); } return null; } // Показать основной интерфейс function showApp(username) { document.getElementById('loginScreen').style.display = 'none'; document.getElementById('header').style.display = 'flex'; document.getElementById('appContent').style.display = 'flex'; document.getElementById('userName').textContent = username; } // Показать экран авторизации function showLogin() { document.getElementById('loginScreen').style.display = 'flex'; document.getElementById('header').style.display = 'none'; document.getElementById('appContent').style.display = 'none'; document.getElementById('loginUser').value = localStorage.getItem(STORAGE_KEYS.username) || ''; document.getElementById('loginPass').value = ''; document.getElementById('loginStatus').textContent = ''; document.getElementById('loginStatus').className = ''; } // Выполнить авторизацию async function doLogin(user, pass, saveUsername = true) { const statusEl = document.getElementById('loginStatus'); try { const res = await api('/api/login', 'POST', { user, pass }); if (res.ok) { if (saveUsername) { localStorage.setItem(STORAGE_KEYS.username, user); } showApp(user); await loadTree(); return true; } else { statusEl.textContent = res.error || 'Ошибка авторизации'; statusEl.className = 'error'; return false; } } catch (e) { console.error('Login error:', e); statusEl.textContent = 'Ошибка подключения'; statusEl.className = 'error'; return false; } } // Выйти из системы async function logout() { try { await api('/api/logout', 'POST', {}); } catch (e) { console.error('Logout error:', e); } showLogin(); document.getElementById('tree').innerHTML = ''; if (table) { table.destroy(); table = null; } } // Сбросить все настройки function resetSettings() { if (confirm('Сбросить все сохранённые настройки (столбцы, фильтры, последняя таблица)?')) { localStorage.removeItem(STORAGE_KEYS.columns); localStorage.removeItem(STORAGE_KEYS.tableState); localStorage.removeItem(STORAGE_KEYS.lastTable); alert('Настройки сброшены. Перезагрузите страницу.'); location.reload(); } } // Автологин при загрузке async function tryAutoLogin() { try { const session = await api('/api/session'); if (session.authenticated) { showApp(session.user || 'MariaDB User'); await loadTree(); return; } } catch (e) { console.error('Session restore error:', e); } showLogin(); } // Инициализация обработчиков авторизации function initUserHandlers() { // Обработчик кнопки "Войти" document.getElementById('loginBtn').addEventListener('click', async () => { const user = document.getElementById('loginUser').value.trim(); const pass = document.getElementById('loginPass').value; const statusEl = document.getElementById('loginStatus'); const btn = document.getElementById('loginBtn'); if (!user || !pass) { statusEl.textContent = 'Введите логин и пароль'; statusEl.className = 'error'; return; } btn.disabled = true; btn.textContent = 'Вход...'; statusEl.textContent = ''; await doLogin(user, pass); btn.disabled = false; btn.textContent = 'Войти'; }); // Enter для входа document.getElementById('loginPass').addEventListener('keypress', (e) => { if (e.key === 'Enter') { document.getElementById('loginBtn').click(); } }); // Меню пользователя document.getElementById('userIcon').addEventListener('click', (e) => { e.stopPropagation(); document.getElementById('userDropdown').classList.toggle('dropdown-hidden'); }); document.addEventListener('click', () => { document.getElementById('userDropdown').classList.add('dropdown-hidden'); }); document.getElementById('menuLogout').addEventListener('click', logout); document.getElementById('menuResetSettings').addEventListener('click', resetSettings); // Автологин при загрузке страницы tryAutoLogin(); } console.log('✅ user.js загружен');