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:
1 parent
c54d2b251f
commit
6272322f31
28 files changed
+1523
-461
No files matched your search
+22
-50
@@ -11,72 +11,44 @@
|
||||
|
||||
<nav>
|
||||
<div class="nav-left">
|
||||
<a href="/index.html" class="nav-brand">🥃 Bourbonacci</a>
|
||||
<div class="nav-links" id="nav-links"></div>
|
||||
<span class="nav-brand">🥃 Bourbonacci — Admin</span>
|
||||
</div>
|
||||
<div class="nav-user">
|
||||
<button onclick="Admin.signOut()" class="btn btn-sm btn-ghost">Sign out</button>
|
||||
</div>
|
||||
<div id="nav-user"></div>
|
||||
</nav>
|
||||
|
||||
<main>
|
||||
<h1 class="page-title">Admin — User Management</h1>
|
||||
|
||||
<div id="msg"></div>
|
||||
|
||||
<div class="section-header">
|
||||
<h2>All Users</h2>
|
||||
<button class="btn btn-ghost btn-sm" onclick="loadUsers()">Refresh</button>
|
||||
<div class="tabs">
|
||||
<div class="tab" data-tab="users" onclick="Admin.showTab('users')">Users</div>
|
||||
<div class="tab" data-tab="notifications" onclick="Admin.showTab('notifications')">Notifications</div>
|
||||
<div class="tab" data-tab="backups" onclick="Admin.showTab('backups')">Backups</div>
|
||||
<div class="tab" data-tab="reset" onclick="Admin.showTab('reset')">Reset</div>
|
||||
</div>
|
||||
|
||||
<div class="table-wrap">
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Display Name</th>
|
||||
<th>Email</th>
|
||||
<th>Role</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>
|
||||
<div id="tab-content"></div>
|
||||
|
||||
<!-- Reset password modal -->
|
||||
<div id="reset-modal" class="modal-overlay" style="display:none">
|
||||
<div class="modal-box">
|
||||
<h2>Reset Password</h2>
|
||||
<p style="margin-bottom:1rem;color:var(--cream-dim)">Setting new password for: <strong id="reset-username"></strong></p>
|
||||
<div id="reset-msg"></div>
|
||||
<div class="form-group" style="margin-bottom:1rem">
|
||||
<label>New Password</label>
|
||||
<input type="password" id="reset-password" placeholder="Min 8 characters" />
|
||||
</div>
|
||||
<div style="display:flex;gap:0.5rem;justify-content:flex-end">
|
||||
<button class="btn btn-ghost" onclick="hideResetModal()">Cancel</button>
|
||||
<button class="btn btn-primary" onclick="submitReset()">Set Password</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Delete confirmation modal -->
|
||||
<!-- Delete user confirmation modal -->
|
||||
<div id="delete-modal" class="modal-overlay" style="display:none">
|
||||
<div class="modal-box">
|
||||
<h2>Delete User</h2>
|
||||
<p style="margin-bottom:1.5rem;color:var(--cream-dim)">Delete <strong id="delete-username"></strong>? This will permanently remove their account and all associated data.</p>
|
||||
<p style="margin-bottom:1rem;color:var(--cream-dim)">
|
||||
This permanently deletes <strong id="delete-email"></strong>'s account and every entry they own.
|
||||
This cannot be undone. Type the email address to confirm.
|
||||
</p>
|
||||
<div id="delete-msg"></div>
|
||||
<div class="form-group">
|
||||
<input type="text" id="delete-confirm" autocomplete="off" oninput="Admin.onDeleteConfirmInput()" />
|
||||
</div>
|
||||
<div style="display:flex;gap:0.5rem;justify-content:flex-end">
|
||||
<button class="btn btn-ghost" onclick="hideDeleteModal()">Cancel</button>
|
||||
<button class="btn btn-danger" onclick="submitDelete()">Delete</button>
|
||||
<button class="btn btn-ghost" onclick="Admin.hideDeleteModal()">Cancel</button>
|
||||
<button class="btn btn-danger" id="delete-submit" disabled onclick="Admin.submitDelete()">Delete permanently</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
|
||||
<script src="/js/api.js"></script>
|
||||
<script src="/js/auth.js"></script>
|
||||
<script src="/js/admin.js"></script>
|
||||
<script src="/js/admin.js?v=2"></script>
|
||||
</body>
|
||||
</html>
|
||||
+19
-16
@@ -81,20 +81,6 @@ nav {
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.nav-impersonating {
|
||||
color: var(--amber-light);
|
||||
font-size: 0.85rem;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.btn-amber {
|
||||
background: var(--amber);
|
||||
color: #0d0800;
|
||||
border: none;
|
||||
}
|
||||
|
||||
.btn-amber:hover { background: var(--amber-light); }
|
||||
|
||||
/* ---- Modal ---- */
|
||||
.modal-overlay {
|
||||
position: fixed;
|
||||
@@ -140,8 +126,6 @@ nav {
|
||||
}
|
||||
|
||||
/* ---- Admin badges ---- */
|
||||
.badge-admin { background: rgba(200,134,10,.2); color: var(--amber-light); border: 1px solid var(--amber-dim); }
|
||||
.badge-user { background: rgba(245,230,200,.1); color: var(--cream-dim); border: 1px solid var(--border); }
|
||||
.badge-active { background: rgba(39,174,96,.15); color: #5dd490; border: 1px solid #1e6b3d; }
|
||||
.badge-disabled { background: rgba(192,57,43,.2); color: #e07060; border: 1px solid var(--danger-dim); }
|
||||
|
||||
@@ -475,6 +459,25 @@ tbody td {
|
||||
.tab.active, .tab:hover { color: var(--amber-light); }
|
||||
.tab.active { border-bottom-color: var(--amber); }
|
||||
|
||||
/* ---- Admin panel ---- */
|
||||
.admin-card { margin-bottom: 1.5rem; }
|
||||
.card + .admin-card { margin-top: 0; }
|
||||
.admin-muted { color: var(--cream-dim); font-size: .85rem; margin-bottom: 1rem; }
|
||||
.admin-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 0 1rem; }
|
||||
.admin-check { display: flex; align-items: center; gap: .5rem; color: var(--cream); margin-bottom: 1rem; cursor: pointer; }
|
||||
.admin-check input { width: auto; }
|
||||
.admin-confirm { display: flex; gap: .5rem; align-items: center; }
|
||||
.admin-confirm input { max-width: 220px; padding: .4rem .7rem; font-size: .85rem; }
|
||||
.admin-file { padding: 1rem; margin-bottom: .75rem; }
|
||||
.admin-file .admin-muted { margin-bottom: 0; }
|
||||
.admin-file-head { display: flex; justify-content: space-between; align-items: center; gap: 1rem; flex-wrap: wrap; }
|
||||
.admin-restore { display: flex; gap: 1.5rem; flex-wrap: wrap; margin-top: .75rem; }
|
||||
.admin-restore label, .admin-card label code { font-size: .8rem; }
|
||||
.temp-pw { display: flex; gap: .75rem; align-items: center; background: rgba(200,134,10,.12); border: 1px solid var(--amber-dim); border-radius: var(--radius); padding: .5rem .75rem; font-size: .85rem; color: var(--amber-light); }
|
||||
.temp-pw code { font-size: .95rem; color: var(--cream); }
|
||||
.text-success { color: #5dd490; }
|
||||
.text-danger { color: #e07060; }
|
||||
|
||||
/* ---- Custom scrollbar ---- */
|
||||
::-webkit-scrollbar { width: 8px; }
|
||||
::-webkit-scrollbar-track { background: var(--bg-card); }
|
||||
|
||||
+573
-143
@@ -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,
|
||||
};
|
||||
})();
|
||||
@@ -66,15 +66,5 @@ const API = (() => {
|
||||
public: {
|
||||
stats: () => request('GET', '/public/stats'),
|
||||
},
|
||||
admin: {
|
||||
listUsers: () => request('GET', '/admin/users'),
|
||||
createUser: (body) => request('POST', '/admin/users', body),
|
||||
resetPassword: (id, body) => request('POST', `/admin/users/${id}/reset-password`, body),
|
||||
disable: (id) => request('POST', `/admin/users/${id}/disable`, {}),
|
||||
enable: (id) => request('POST', `/admin/users/${id}/enable`, {}),
|
||||
delete: (id) => request('DELETE', `/admin/users/${id}`),
|
||||
impersonate: (id) => request('POST', `/admin/users/${id}/impersonate`, {}),
|
||||
unimpersonate: () => request('POST', '/admin/unimpersonate', {}),
|
||||
},
|
||||
};
|
||||
})();
|
||||
+6
-30
@@ -55,28 +55,17 @@ const Auth = (() => {
|
||||
try { user = await API.users.me(); saveUser(user); } catch (_) {}
|
||||
}
|
||||
|
||||
const payload = _decodePayload();
|
||||
const isImpersonating = !!(payload && payload.admin_id);
|
||||
|
||||
navLinksEl.innerHTML = `
|
||||
<a href="/dashboard.html" class="btn btn-ghost btn-sm${activePage === 'dashboard' ? ' active' : ''}">My Bottle</a>
|
||||
<a href="/log.html" class="btn btn-ghost btn-sm${activePage === 'log' ? ' active' : ''}">Log Entry</a>
|
||||
`;
|
||||
|
||||
if (isImpersonating) {
|
||||
navUserEl.innerHTML = `
|
||||
<span class="nav-impersonating">Viewing as <strong>${escHtml(user?.display_name || user?.email || 'User')}</strong></span>
|
||||
<button onclick="Auth.returnToAdmin()" class="btn btn-sm btn-amber">↩ Return to Admin</button>
|
||||
`;
|
||||
} else {
|
||||
navUserEl.innerHTML = `
|
||||
<span class="nav-username">${escHtml(user?.display_name || user?.email || 'Account')}</span>
|
||||
${user?.is_admin ? '<a href="/admin.html" class="btn btn-sm btn-ghost">Admin</a>' : ''}
|
||||
<button onclick="Auth.showSettingsModal()" class="btn btn-sm btn-ghost" title="Settings">⚙</button>
|
||||
<button onclick="Auth.logout()" class="btn btn-sm btn-ghost">Logout</button>
|
||||
`;
|
||||
_injectSettingsModal(user);
|
||||
}
|
||||
navUserEl.innerHTML = `
|
||||
<span class="nav-username">${escHtml(user?.display_name || user?.email || 'Account')}</span>
|
||||
<button onclick="Auth.showSettingsModal()" class="btn btn-sm btn-ghost" title="Settings">⚙</button>
|
||||
<button onclick="Auth.logout()" class="btn btn-sm btn-ghost">Logout</button>
|
||||
`;
|
||||
_injectSettingsModal(user);
|
||||
} else {
|
||||
navLinksEl.innerHTML = '';
|
||||
navUserEl.innerHTML = `<a href="/login.html" class="btn btn-primary btn-sm">Login</a>`;
|
||||
@@ -229,22 +218,9 @@ const Auth = (() => {
|
||||
if (type === 'success') setTimeout(() => { el.innerHTML = ''; }, 3000);
|
||||
}
|
||||
|
||||
async function returnToAdmin() {
|
||||
try {
|
||||
const data = await API.post('/admin/unimpersonate', {});
|
||||
saveToken(data.access_token);
|
||||
const user = await API.users.me();
|
||||
saveUser(user);
|
||||
window.location.href = '/admin.html';
|
||||
} catch (_) {
|
||||
logout();
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
getToken, saveToken, getUser, saveUser,
|
||||
logout, isLoggedIn, requireAuth, redirectIfLoggedIn, renderNav,
|
||||
showSettingsModal, hideSettingsModal, detectTimezone, saveProfile, submitPasswordChange,
|
||||
returnToAdmin,
|
||||
};
|
||||
})();
|
||||
+41
-10
@@ -28,7 +28,7 @@
|
||||
<form id="login-form">
|
||||
<div class="form-group">
|
||||
<label for="email">Email</label>
|
||||
<input type="email" id="email" autocomplete="email" required placeholder="[email protected]" />
|
||||
<input type="text" id="email" autocomplete="username" required placeholder="[email protected]" />
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label for="password">Password</label>
|
||||
@@ -60,19 +60,50 @@ document.addEventListener('DOMContentLoaded', () => {
|
||||
btn.disabled = true;
|
||||
btn.textContent = 'Signing in…';
|
||||
|
||||
const email = document.getElementById('email').value.trim();
|
||||
const password = document.getElementById('password').value;
|
||||
|
||||
try {
|
||||
const email = document.getElementById('email').value.trim();
|
||||
const password = document.getElementById('password').value;
|
||||
const data = await API.auth.login(email, password);
|
||||
Auth.saveToken(data.access_token);
|
||||
// Raw fetch (not API.auth.login) so a 401 doesn't trigger the global sign-out redirect.
|
||||
const res = await fetch('/api/auth/login', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ email, password }),
|
||||
});
|
||||
const data = await res.json().catch(() => null);
|
||||
|
||||
// Pre-fetch user info so nav renders immediately
|
||||
const user = await API.users.me();
|
||||
Auth.saveUser(user);
|
||||
if (res.ok) {
|
||||
Auth.saveToken(data.access_token);
|
||||
// Pre-fetch user info so nav renders immediately
|
||||
const user = await API.users.me();
|
||||
Auth.saveUser(user);
|
||||
window.location.href = '/index.html';
|
||||
return;
|
||||
}
|
||||
|
||||
window.location.href = '/index.html';
|
||||
// A rejected normal login might be the out-of-band admin account.
|
||||
if (res.status === 401 || res.status === 422) {
|
||||
const adminRes = await fetch('/api/admin/login', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ username: email, password }),
|
||||
});
|
||||
if (adminRes.ok) {
|
||||
const adminData = await adminRes.json();
|
||||
localStorage.setItem('bb_admin_token', adminData.access_token);
|
||||
window.location.href = '/admin.html?v=2';
|
||||
return;
|
||||
}
|
||||
if (adminRes.status === 429) {
|
||||
const adminErr = await adminRes.json().catch(() => null);
|
||||
throw new Error(adminErr?.detail || 'Too many attempts. Try again later.');
|
||||
}
|
||||
throw new Error('Invalid credentials');
|
||||
}
|
||||
|
||||
throw new Error(data?.detail || `HTTP ${res.status}`);
|
||||
} catch (err) {
|
||||
alert.innerHTML = `<div class="alert alert-error">${err.message}</div>`;
|
||||
alert.innerHTML = `<div class="alert alert-error">${escHtml(err.message)}</div>`;
|
||||
btn.disabled = false;
|
||||
btn.textContent = 'Sign In';
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user