// admin.js — out-of-band admin panel (Users / Notifications / Backups / Reset). // Uses its own admin token (bb_admin_token), separate from the normal user token. const Admin = (() => { const TOKEN_KEY = 'bb_admin_token'; const TABS = ['users', 'notifications', 'backups', 'reset']; const WEEKDAYS = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']; // ── API ──────────────────────────────────────────────────────────────────── function signOut() { localStorage.removeItem(TOKEN_KEY); window.location.href = '/login.html'; } async function request(method, path, body) { const headers = { 'Content-Type': 'application/json' }; const tok = localStorage.getItem(TOKEN_KEY); if (tok) headers['Authorization'] = `Bearer ${tok}`; const res = await fetch('/api/admin' + path, { method, headers, body: body !== undefined ? JSON.stringify(body) : undefined, }); if (res.status === 401 || res.status === 403) { signOut(); throw new Error('Signed out'); } if (res.status === 204) return null; const data = await res.json().catch(() => null); if (!res.ok) { const msg = data?.detail || `HTTP ${res.status}`; throw new Error(Array.isArray(msg) ? msg.map(e => e.msg).join(', ') : msg); } return data; } const api = { listUsers: () => request('GET', '/users'), resetPassword: (id) => request('POST', `/users/${id}/reset-password`), disableUser: (id) => request('POST', `/users/${id}/disable`), enableUser: (id) => request('POST', `/users/${id}/enable`), deleteUser: (id) => request('DELETE', `/users/${id}`), getNtfy: () => request('GET', '/ntfy-settings'), updateNtfy: (body) => request('PUT', '/ntfy-settings', body), testNtfy: () => request('POST', '/ntfy-settings/test'), getBackupCfg: () => request('GET', '/backups/settings'), updateBackupCfg:(body) => request('PUT', '/backups/settings', body), listBackups: () => request('GET', '/backups'), runBackup: () => request('POST', '/backups/run'), restoreBackup: (f, scope) => request('POST', `/backups/${encodeURIComponent(f)}/restore`, { scope }), deleteBackup: (f) => request('DELETE', `/backups/${encodeURIComponent(f)}`), resetEntries: () => request('POST', '/reset/entries'), }; // ── Helpers ──────────────────────────────────────────────────────────────── function fmtDateTime(iso) { if (!iso) return ''; const d = new Date(iso); if (Number.isNaN(d.getTime())) return ''; return d.toLocaleString(undefined, { year: 'numeric', month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit', }); } function fmtBytes(n) { if (n < 1024) return `${n} B`; const units = ['KB', 'MB', 'GB']; let v = n, i = -1; do { v /= 1024; i += 1; } while (v >= 1024 && i < units.length - 1); return `${v.toFixed(1)} ${units[i]}`; } function alertHtml(text, type) { const cls = type === 'success' ? 'alert-success' : 'alert-error'; return `
${escHtml(text)}
`; } function setMsg(id, text, type) { const el = document.getElementById(id); if (el) el.innerHTML = text ? alertHtml(text, type) : ''; } // "Type X to arm, then click" confirm widget for destructive actions. function confirmWidget(id, word, label) { return `
`; } function armConfirm(id) { const input = document.getElementById(`${id}-input`); const btn = document.getElementById(`${id}-btn`); btn.disabled = input.value.trim().toLowerCase() !== input.dataset.word; } async function runConfirm(id, fn) { const input = document.getElementById(`${id}-input`); const btn = document.getElementById(`${id}-btn`); if (btn.disabled) return; const label = btn.textContent; btn.disabled = true; input.disabled = true; btn.textContent = 'Working…'; try { await fn(); input.value = ''; } finally { input.disabled = false; btn.textContent = label; armConfirm(id); } } // ── Tabs ─────────────────────────────────────────────────────────────────── function showTab(name) { if (!TABS.includes(name)) name = 'users'; history.replaceState(null, '', `#${name}`); document.querySelectorAll('.tab').forEach(t => t.classList.toggle('active', t.dataset.tab === name)); const content = document.getElementById('tab-content'); content.innerHTML = '

Loading…

'; ({ users: renderUsersTab, notifications: renderNotificationsTab, backups: renderBackupsTab, reset: renderResetTab })[name](); } // ── Users ────────────────────────────────────────────────────────────────── let users = []; let tempPasswords = {}; let deleteTarget = null; async function renderUsersTab() { document.getElementById('tab-content').innerHTML = `
Display NameEmailEntriesStatusJoinedActions
Loading…
`; await loadUsers(); } async function loadUsers() { try { users = await api.listUsers(); renderUserRows(); } catch (err) { const body = document.getElementById('users-body'); if (body) body.innerHTML = 'Failed to load users.'; setMsg('users-msg', err.message, 'error'); } } function renderUserRows() { const tbody = document.getElementById('users-body'); if (!tbody) return; const q = (document.getElementById('user-search')?.value || '').trim().toLowerCase(); const filtered = users.filter(u => !q || u.email.toLowerCase().includes(q) || (u.display_name || '').toLowerCase().includes(q)); if (!filtered.length) { tbody.innerHTML = `${users.length ? 'No matching users.' : 'No users found.'}`; return; } tbody.innerHTML = filtered.map(u => { const status = u.is_disabled ? 'Disabled' : 'Active'; const toggle = u.is_disabled ? `` : ``; const temp = tempPasswords[u.id] ? `
${escHtml(tempPasswords[u.id])} shown once — relay this to ${escHtml(u.email)}
` : ''; return ` ${escHtml(u.display_name || u.email)} ${escHtml(u.email)} ${u.entry_count} ${status} ${new Date(u.created_at).toLocaleDateString()} ${toggle} ${temp}`; }).join(''); } async function resetPassword(id) { const u = users.find(x => x.id === id); if (!u || !confirm(`Reset password for ${u.email}? A new temporary password will be generated.`)) return; try { const { temp_password } = await api.resetPassword(id); tempPasswords[id] = temp_password; await loadUsers(); } catch (err) { setMsg('users-msg', err.message, 'error'); } } async function toggleUser(id, disable) { try { await (disable ? api.disableUser(id) : api.enableUser(id)); await loadUsers(); } catch (err) { setMsg('users-msg', err.message, 'error'); } } function showDeleteModal(id) { deleteTarget = users.find(x => x.id === id) || null; if (!deleteTarget) return; document.getElementById('delete-email').textContent = deleteTarget.email; document.getElementById('delete-confirm').value = ''; document.getElementById('delete-confirm').placeholder = deleteTarget.email; document.getElementById('delete-submit').disabled = true; document.getElementById('delete-msg').innerHTML = ''; document.getElementById('delete-modal').style.display = 'flex'; document.getElementById('delete-confirm').focus(); } function hideDeleteModal() { document.getElementById('delete-modal').style.display = 'none'; deleteTarget = null; } function onDeleteConfirmInput() { const v = document.getElementById('delete-confirm').value; document.getElementById('delete-submit').disabled = !deleteTarget || v !== deleteTarget.email; } async function submitDelete() { if (!deleteTarget || document.getElementById('delete-confirm').value !== deleteTarget.email) return; const btn = document.getElementById('delete-submit'); btn.disabled = true; btn.textContent = 'Deleting…'; try { await api.deleteUser(deleteTarget.id); hideDeleteModal(); setMsg('users-msg', 'User deleted.', 'success'); await loadUsers(); } catch (err) { document.getElementById('delete-msg').innerHTML = alertHtml(err.message, 'error'); btn.disabled = false; } finally { btn.textContent = 'Delete permanently'; } } // ── Notifications ────────────────────────────────────────────────────────── async function renderNotificationsTab() { let cfg; try { cfg = await api.getNtfy(); } catch (err) { document.getElementById('tab-content').innerHTML = alertHtml(err.message, 'error'); return; } document.getElementById('tab-content').innerHTML = `

Admin push notifications

Sent via ntfy for new registrations, admin logins and lockouts, user changes, resets and restores. Token auth only.

`; } async function saveNtfy() { const btn = document.getElementById('ntfy-save'); setMsg('ntfy-msg', ''); btn.disabled = true; btn.textContent = 'Saving…'; try { const body = { ntfy_server_url: document.getElementById('ntfy-server').value.trim(), ntfy_topic: document.getElementById('ntfy-topic').value.trim(), }; const token = document.getElementById('ntfy-token').value; if (token) body.ntfy_token = token; const updated = await api.updateNtfy(body); const tokenInput = document.getElementById('ntfy-token'); tokenInput.value = ''; tokenInput.placeholder = updated.has_token ? '••••••••' : 'tk_…'; document.getElementById('ntfy-token-hint').textContent = updated.has_token ? '(configured — leave blank to keep)' : ''; setMsg('ntfy-msg', 'Saved.', 'success'); } catch (err) { setMsg('ntfy-msg', err.message, 'error'); } finally { btn.disabled = false; btn.textContent = 'Save'; } } async function testNtfy() { const btn = document.getElementById('ntfy-test'); setMsg('ntfy-msg', ''); btn.disabled = true; btn.textContent = 'Sending…'; try { await api.testNtfy(); setMsg('ntfy-msg', 'Test notification sent — check your device!', 'success'); } catch (err) { setMsg('ntfy-msg', err.message, 'error'); } finally { btn.disabled = false; btn.textContent = 'Send test'; } } // ── Backups ──────────────────────────────────────────────────────────────── let backupFiles = []; async function renderBackupsTab() { let cfg; try { cfg = await api.getBackupCfg(); } catch (err) { document.getElementById('tab-content').innerHTML = alertHtml(err.message, 'error'); return; } const hourOpts = Array.from({ length: 24 }, (_, h) => ``).join(''); const dayOpts = WEEKDAYS.map((w, i) => ``).join(''); document.getElementById('tab-content').innerHTML = `

Backup schedule

Runs a full database dump into /backups, the NFS share set via BACKUP_NFS_HOST / BACKUP_NFS_PATH in .env. All times are UTC.

Backup now

Run an immediate backup outside the schedule.

Backup files

Loading…

`; renderLastBackup(cfg); await loadBackupFiles(); } function renderLastBackup(cfg) { const el = document.getElementById('bk-last'); if (!el) return; if (!cfg.last_backup_at) { el.textContent = 'No backups have run yet.'; return; } el.innerHTML = `Last backup: ${escHtml(fmtDateTime(cfg.last_backup_at))} — ` + (cfg.last_backup_status === 'success' ? 'success' : `failed: ${escHtml(cfg.last_backup_error || '')}`); } function onFrequencyChange() { const weekly = document.getElementById('bk-frequency').value === 'weekly'; document.getElementById('bk-weekday-group').style.display = weekly ? '' : 'none'; } async function saveBackupCfg() { const btn = document.getElementById('bk-save'); setMsg('bk-save-msg', ''); btn.disabled = true; btn.textContent = 'Saving…'; try { const updated = await api.updateBackupCfg({ backup_enabled: document.getElementById('bk-enabled').checked, backup_frequency: document.getElementById('bk-frequency').value, backup_hour: Number(document.getElementById('bk-hour').value), backup_weekday: Number(document.getElementById('bk-weekday').value), backup_retention: Number(document.getElementById('bk-retention').value), backup_location: document.getElementById('bk-location').value, }); document.getElementById('bk-location').value = updated.backup_location || ''; setMsg('bk-save-msg', 'Saved.', 'success'); renderLastBackup(updated); await loadBackupFiles(); } catch (err) { setMsg('bk-save-msg', err.message, 'error'); } finally { btn.disabled = false; btn.textContent = 'Save schedule'; } } async function runBackup() { const btn = document.getElementById('bk-run'); setMsg('bk-run-msg', ''); btn.disabled = true; btn.textContent = 'Backing up…'; try { const r = await api.runBackup(); setMsg('bk-run-msg', `Created ${r.filename} (${fmtBytes(r.size_bytes)}).`, 'success'); renderLastBackup(await api.getBackupCfg()); await loadBackupFiles(); } catch (err) { setMsg('bk-run-msg', err.message, 'error'); api.getBackupCfg().then(renderLastBackup).catch(() => {}); } finally { btn.disabled = false; btn.textContent = 'Backup now'; } } async function loadBackupFiles() { const el = document.getElementById('bk-files'); if (!el) return; try { backupFiles = await api.listBackups(); } catch (err) { el.innerHTML = alertHtml('Failed to load backup files: ' + err.message, 'error'); return; } if (!backupFiles.length) { el.innerHTML = '

No backups yet.

'; return; } el.innerHTML = backupFiles.map((f, i) => `
${escHtml(f.filename)}
${fmtBytes(f.size_bytes)} · ${escHtml(fmtDateTime(f.created_at))}
${confirmWidget(`rs-e-${i}`, 'restore entries', 'Restore entries only')}
${confirmWidget(`rs-a-${i}`, 'restore all', 'Restore all data')}
`).join(''); backupFiles.forEach((f, i) => { document.getElementById(`rs-e-${i}-btn`).onclick = () => restore(i, 'entries'); document.getElementById(`rs-a-${i}-btn`).onclick = () => restore(i, 'all'); }); } async function restore(i, scope) { const f = backupFiles[i]; const id = scope === 'all' ? `rs-a-${i}` : `rs-e-${i}`; setMsg(`bk-row-msg-${i}`, ''); await runConfirm(id, async () => { try { await api.restoreBackup(f.filename, scope); setMsg(`bk-row-msg-${i}`, `Restored ${scope === 'all' ? 'all data' : 'entries'}.`, 'success'); } catch (err) { setMsg(`bk-row-msg-${i}`, err.message, 'error'); } }); } async function deleteBackup(i) { const f = backupFiles[i]; if (!confirm(`Delete backup file "${f.filename}"? This cannot be undone.`)) return; const btn = document.getElementById(`bk-del-${i}`); btn.disabled = true; btn.textContent = 'Deleting…'; try { await api.deleteBackup(f.filename); await loadBackupFiles(); } catch (err) { setMsg(`bk-row-msg-${i}`, 'Delete failed: ' + err.message, 'error'); btn.disabled = false; btn.textContent = 'Delete'; } } // ── Reset ────────────────────────────────────────────────────────────────── function renderResetTab() { document.getElementById('tab-content').innerHTML = `
Destructive actions
These run across every user's data and cannot be undone. User accounts, passwords, profile settings and admin settings are always kept. Each one automatically runs a fresh backup first and refuses to proceed if that backup fails.

Reset all entries

Permanently delete every bottle entry (adds and removes) for every user — each bottle starts empty again.

${confirmWidget('reset-entries', 'reset entries', 'Reset all entries')}
`; document.getElementById('reset-entries-btn').onclick = () => { setMsg('reset-entries-msg', ''); runConfirm('reset-entries', async () => { try { const r = await api.resetEntries(); setMsg('reset-entries-msg', `Deleted ${r.entries_deleted} entr${r.entries_deleted === 1 ? 'y' : 'ies'}. Safety backup: ${r.backup_filename}.`, 'success'); } catch (err) { setMsg('reset-entries-msg', err.message, 'error'); } }); }; } // ── Init ─────────────────────────────────────────────────────────────────── document.addEventListener('DOMContentLoaded', () => { if (!localStorage.getItem(TOKEN_KEY)) { window.location.href = '/login.html'; return; } showTab(location.hash.slice(1)); }); document.addEventListener('click', (e) => { if (e.target.id === 'delete-modal') hideDeleteModal(); }); return { signOut, showTab, armConfirm, loadUsers, renderUserRows, resetPassword, toggleUser, showDeleteModal, hideDeleteModal, onDeleteConfirmInput, submitDelete, saveNtfy, testNtfy, onFrequencyChange, saveBackupCfg, runBackup, deleteBackup, }; })();