feat(admin): rebuild admin panel as out-of-band login with backups

- Separate admin login (ADMIN_USERNAME/ADMIN_PASSWORD) with its own JWT,
  no longer a seeded user account; lockout after 5 failed attempts
- Admin panel tabs: Users, Notifications, Backups, Reset
- Ntfy settings moved from .env/compose into admin_settings (token encrypted)
- Scheduled and on-demand mariadb-dump backups to NFS volume, with
  restore (entries only or all) and retention pruning
- Reset all entries, guarded by an automatic safety backup
- Remove user impersonation and the admin link in the user nav
- Login page falls back to admin login; nginx sends Cache-Control: no-cache

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
derekcandClaude Opus 5.5 committed 2026-11-23 00:24:19 -08:00
1 parent c54d2b251f
commit 6272322f31
28 files changed
+1523 -461

No files matched your search

+573 -143
View File
@@ -1,164 +1,594 @@
// admin.js — admin user management page
// 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.
let resetTargetId = null;
let deleteTargetId = null;
let currentAdminId = null;
const Admin = (() => {
const TOKEN_KEY = 'bb_admin_token';
const TABS = ['users', 'notifications', 'backups', 'reset'];
const WEEKDAYS = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'];
document.addEventListener('DOMContentLoaded', async () => {
if (!Auth.requireAuth()) return;
await Auth.renderNav();
// ── API ────────────────────────────────────────────────────────────────────
const user = Auth.getUser();
if (!user || !user.is_admin) {
window.location.href = '/dashboard.html';
return;
}
currentAdminId = user.id;
await loadUsers();
});
async function loadUsers() {
try {
const users = await API.admin.listUsers();
renderUsers(users);
} catch (err) {
showMsg(err.message, 'error');
}
}
function renderUsers(users) {
const tbody = document.getElementById('users-body');
if (!users.length) {
tbody.innerHTML = '<tr class="empty-row"><td colspan="6">No users found.</td></tr>';
return;
function signOut() {
localStorage.removeItem(TOKEN_KEY);
window.location.href = '/login.html';
}
tbody.innerHTML = users.map(u => {
const isSelf = u.id === currentAdminId;
const name = escHtml(u.display_name || u.email);
const roleLabel = u.is_admin
? '<span class="badge badge-admin">Admin</span>'
: '<span class="badge badge-user">User</span>';
const statusLabel = u.is_disabled
? '<span class="badge badge-disabled">Disabled</span>'
: '<span class="badge badge-active">Active</span>';
const joined = new Date(u.created_at).toLocaleDateString();
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 toggleBtn = u.is_disabled
? `<button class="btn btn-sm btn-primary" onclick="toggleUser(${u.id}, false)">Enable</button>`
: `<button class="btn btn-sm btn-ghost" onclick="toggleUser(${u.id}, true)"${isSelf ? ' disabled title="Cannot disable yourself"' : ''}>Disable</button>`;
const res = await fetch('/api/admin' + path, {
method,
headers,
body: body !== undefined ? JSON.stringify(body) : undefined,
});
const impersonateBtn = !isSelf
? `<button class="btn btn-sm btn-ghost" onclick="impersonateUser(${u.id})">Login As</button>`
: '';
if (res.status === 401 || res.status === 403) {
signOut();
throw new Error('Signed out');
}
if (res.status === 204) return null;
const deleteBtn = !isSelf
? `<button class="btn btn-sm btn-danger" onclick="showDeleteModal(${u.id}, '${name}')">Delete</button>`
: '';
return `<tr>
<td><strong>${name}</strong></td>
<td>${escHtml(u.email)}</td>
<td>${roleLabel}</td>
<td>${statusLabel}</td>
<td>${joined}</td>
<td style="display:flex;gap:0.35rem;flex-wrap:wrap">
<button class="btn btn-sm btn-ghost" onclick="showResetModal(${u.id}, '${name}')">Reset PW</button>
${toggleBtn}
${impersonateBtn}
${deleteBtn}
</td>
</tr>`;
}).join('');
}
function showResetModal(id, name) {
resetTargetId = id;
document.getElementById('reset-username').textContent = name;
document.getElementById('reset-password').value = '';
document.getElementById('reset-msg').innerHTML = '';
document.getElementById('reset-modal').style.display = 'flex';
document.getElementById('reset-password').focus();
}
function hideResetModal() {
document.getElementById('reset-modal').style.display = 'none';
resetTargetId = null;
}
async function submitReset() {
const password = document.getElementById('reset-password').value;
const msgEl = document.getElementById('reset-msg');
if (password.length < 8) {
msgEl.innerHTML = '<div class="alert alert-error">Password must be at least 8 characters.</div>';
return;
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;
}
try {
await API.admin.resetPassword(resetTargetId, { new_password: password });
msgEl.innerHTML = '<div class="alert alert-success">Password reset successfully.</div>';
setTimeout(hideResetModal, 1200);
} catch (err) {
msgEl.innerHTML = `<div class="alert alert-error">${escHtml(err.message)}</div>`;
}
}
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'),
};
async function toggleUser(id, disable) {
try {
if (disable) await API.admin.disable(id);
else await API.admin.enable(id);
// ── 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 `<div class="alert ${cls}">${escHtml(text)}</div>`;
}
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 `
<div class="admin-confirm">
<input type="text" id="${id}-input" placeholder="${escHtml(word)}" autocomplete="off"
data-word="${escHtml(word)}" oninput="Admin.armConfirm('${id}')" />
<button class="btn btn-sm btn-danger" id="${id}-btn" disabled>${escHtml(label)}</button>
</div>`;
}
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 = '<p class="admin-muted">Loading…</p>';
({ 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 = `
<div id="users-msg"></div>
<div class="section-header">
<input type="text" id="user-search" placeholder="Search users…" oninput="Admin.renderUserRows()" style="max-width:320px" />
<button class="btn btn-ghost btn-sm" onclick="Admin.loadUsers()">Refresh</button>
</div>
<div class="table-wrap">
<table>
<thead>
<tr><th>Display Name</th><th>Email</th><th>Entries</th><th>Status</th><th>Joined</th><th>Actions</th></tr>
</thead>
<tbody id="users-body"><tr class="empty-row"><td colspan="6">Loading…</td></tr></tbody>
</table>
</div>`;
await loadUsers();
} catch (err) {
showMsg(err.message, 'error');
}
}
async function impersonateUser(id) {
try {
const data = await API.admin.impersonate(id);
Auth.saveToken(data.access_token);
const user = await API.users.me();
Auth.saveUser(user);
window.location.href = '/dashboard.html';
} catch (err) {
showMsg(err.message, 'error');
async function loadUsers() {
try {
users = await api.listUsers();
renderUserRows();
} catch (err) {
const body = document.getElementById('users-body');
if (body) body.innerHTML = '<tr class="empty-row"><td colspan="6">Failed to load users.</td></tr>';
setMsg('users-msg', err.message, 'error');
}
}
}
function showDeleteModal(id, name) {
deleteTargetId = id;
document.getElementById('delete-username').textContent = name;
document.getElementById('delete-modal').style.display = 'flex';
}
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));
function hideDeleteModal() {
document.getElementById('delete-modal').style.display = 'none';
deleteTargetId = null;
}
if (!filtered.length) {
tbody.innerHTML = `<tr class="empty-row"><td colspan="6">${users.length ? 'No matching users.' : 'No users found.'}</td></tr>`;
return;
}
async function submitDelete() {
try {
await API.admin.delete(deleteTargetId);
hideDeleteModal();
showMsg('User deleted.', 'success');
await loadUsers();
} catch (err) {
hideDeleteModal();
showMsg(err.message, 'error');
tbody.innerHTML = filtered.map(u => {
const status = u.is_disabled
? '<span class="badge badge-disabled">Disabled</span>'
: '<span class="badge badge-active">Active</span>';
const toggle = u.is_disabled
? `<button class="btn btn-sm btn-primary" onclick="Admin.toggleUser(${u.id}, false)">Enable</button>`
: `<button class="btn btn-sm btn-ghost" onclick="Admin.toggleUser(${u.id}, true)">Disable</button>`;
const temp = tempPasswords[u.id]
? `<tr><td colspan="6"><div class="temp-pw"><code>${escHtml(tempPasswords[u.id])}</code>
<span>shown once — relay this to ${escHtml(u.email)}</span></div></td></tr>`
: '';
return `<tr${u.is_disabled ? ' style="opacity:.6"' : ''}>
<td><strong>${escHtml(u.display_name || u.email)}</strong></td>
<td>${escHtml(u.email)}</td>
<td>${u.entry_count}</td>
<td>${status}</td>
<td>${new Date(u.created_at).toLocaleDateString()}</td>
<td style="display:flex;gap:0.35rem;flex-wrap:wrap">
<button class="btn btn-sm btn-ghost" onclick="Admin.resetPassword(${u.id})">Reset PW</button>
${toggle}
<button class="btn btn-sm btn-danger" onclick="Admin.showDeleteModal(${u.id})">Delete</button>
</td>
</tr>${temp}`;
}).join('');
}
}
function showMsg(text, type) {
const el = document.getElementById('msg');
if (!el) return;
const cls = type === 'success' ? 'alert-success' : 'alert-error';
el.innerHTML = `<div class="alert ${cls}" style="margin-bottom:1rem">${escHtml(text)}</div>`;
if (type === 'success') setTimeout(() => { el.innerHTML = ''; }, 3000);
}
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');
}
}
document.addEventListener('click', (e) => {
if (e.target.id === 'reset-modal') hideResetModal();
if (e.target.id === 'delete-modal') hideDeleteModal();
});
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 = `
<div class="card admin-card">
<h3 class="card-title">Admin push notifications</h3>
<p class="admin-muted">Sent via ntfy for new registrations, admin logins and lockouts, user changes, resets and restores. Token auth only.</p>
<div class="form-group">
<label for="ntfy-server">Server URL</label>
<input type="text" id="ntfy-server" placeholder="https://ntfy.sh" value="${escHtml(cfg.ntfy_server_url || '')}" />
</div>
<div class="form-group">
<label for="ntfy-topic">Topic</label>
<input type="text" id="ntfy-topic" placeholder="my-secret-admin-topic" value="${escHtml(cfg.ntfy_topic || '')}" />
</div>
<div class="form-group">
<label for="ntfy-token">Access token <span id="ntfy-token-hint">${cfg.has_token ? '(configured — leave blank to keep)' : ''}</span></label>
<input type="password" id="ntfy-token" autocomplete="new-password" placeholder="${cfg.has_token ? '••••••••' : 'tk_…'}" />
</div>
<div id="ntfy-msg"></div>
<div style="display:flex;gap:0.5rem">
<button class="btn btn-primary" id="ntfy-save" onclick="Admin.saveNtfy()">Save</button>
<button class="btn btn-ghost" id="ntfy-test" onclick="Admin.testNtfy()">Send test</button>
</div>
</div>`;
}
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) =>
`<option value="${h}"${h === cfg.backup_hour ? ' selected' : ''}>${String(h).padStart(2, '0')}:00</option>`).join('');
const dayOpts = WEEKDAYS.map((w, i) =>
`<option value="${i}"${i === cfg.backup_weekday ? ' selected' : ''}>${w}</option>`).join('');
document.getElementById('tab-content').innerHTML = `
<div class="card admin-card">
<h3 class="card-title">Backup schedule</h3>
<p class="admin-muted">Runs a full database dump into /backups, the NFS share set via BACKUP_NFS_HOST / BACKUP_NFS_PATH in .env. All times are UTC.</p>
<label class="admin-check">
<input type="checkbox" id="bk-enabled"${cfg.backup_enabled ? ' checked' : ''} /> Enable scheduled backups
</label>
<div class="admin-grid">
<div class="form-group">
<label for="bk-frequency">Frequency</label>
<select id="bk-frequency" onchange="Admin.onFrequencyChange()">
<option value="daily"${cfg.backup_frequency === 'daily' ? ' selected' : ''}>Daily</option>
<option value="weekly"${cfg.backup_frequency === 'weekly' ? ' selected' : ''}>Weekly</option>
</select>
</div>
<div class="form-group">
<label for="bk-hour">Hour (UTC)</label>
<select id="bk-hour">${hourOpts}</select>
</div>
<div class="form-group" id="bk-weekday-group"${cfg.backup_frequency === 'weekly' ? '' : ' style="display:none"'}>
<label for="bk-weekday">Day of week</label>
<select id="bk-weekday">${dayOpts}</select>
</div>
<div class="form-group">
<label for="bk-retention">Keep last N backups</label>
<input type="number" id="bk-retention" min="1" max="365" value="${cfg.backup_retention}" />
</div>
<div class="form-group">
<label for="bk-location">Subfolder (optional)</label>
<input type="text" id="bk-location" placeholder="e.g. nightly" value="${escHtml(cfg.backup_location || '')}" />
</div>
</div>
<div id="bk-save-msg"></div>
<button class="btn btn-primary btn-sm" id="bk-save" onclick="Admin.saveBackupCfg()">Save schedule</button>
<p class="admin-muted" id="bk-last" style="margin-top:1rem"></p>
</div>
<div class="card admin-card">
<h3 class="card-title">Backup now</h3>
<p class="admin-muted">Run an immediate backup outside the schedule.</p>
<button class="btn btn-primary btn-sm" id="bk-run" onclick="Admin.runBackup()">Backup now</button>
<div id="bk-run-msg" style="margin-top:.75rem"></div>
</div>
<div class="section-header" style="margin-top:1.5rem"><h2>Backup files</h2></div>
<div id="bk-files"><p class="admin-muted">Loading…</p></div>`;
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'
? '<span class="text-success">success</span>'
: `<span class="text-danger">failed: ${escHtml(cfg.last_backup_error || '')}</span>`);
}
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 = '<p class="admin-muted"><em>No backups yet.</em></p>';
return;
}
el.innerHTML = backupFiles.map((f, i) => `
<div class="card admin-card admin-file">
<div class="admin-file-head">
<div>
<code>${escHtml(f.filename)}</code>
<div class="admin-muted">${fmtBytes(f.size_bytes)} · ${escHtml(fmtDateTime(f.created_at))}</div>
</div>
<button class="btn btn-sm btn-ghost" id="bk-del-${i}" onclick="Admin.deleteBackup(${i})">Delete</button>
</div>
<div class="admin-restore">
<div>
<label>Type <code>restore entries</code></label>
${confirmWidget(`rs-e-${i}`, 'restore entries', 'Restore entries only')}
</div>
<div>
<label>Type <code>restore all</code></label>
${confirmWidget(`rs-a-${i}`, 'restore all', 'Restore all data')}
</div>
</div>
<div id="bk-row-msg-${i}"></div>
</div>`).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 = `
<div class="alert alert-error">
<strong>Destructive actions</strong><br />
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.
</div>
<div class="card admin-card">
<h3 class="card-title">Reset all entries</h3>
<p class="admin-muted">Permanently delete every bottle entry (adds and removes) for every user — each bottle starts empty again.</p>
<label>Type <code>reset entries</code> to confirm</label>
${confirmWidget('reset-entries', 'reset entries', 'Reset all entries')}
<div id="reset-entries-msg" style="margin-top:.75rem"></div>
</div>`;
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,
};
})();