Admin dashboard (phase 1): users, disable, invite-gated signup
Adds an operator dashboard for self-hosters, gated on a passkey-
authenticated admin flag (ADMIN_UIDS env) and enforced server-side.
Backend:
- ADMIN_UIDS / INVITE_ONLY env (both off by default, OSS-friendly).
- Invite codes in db.json; /api/register gated when INVITE_ONLY, code
burned on successful signup.
- disabled users are rejected by readSession — locked out everywhere.
- /api/admin/{users,user,user/disable,invites,invites/new,invites/revoke}
behind an admin guard; /api/config exposes invite_only to the login UI.
- admin flag surfaced on /api/me, register/verify, login/verify.
Frontend:
- New /admin route + Settings link, shown only to admins: user list with
workout counts and last-sync, disable/enable, invite generation, and a
per-user workout-history drill-down.
- Registration sheet shows an invite-code field when the instance is
invite-only.
Phase 2 (live 'training now' via a heartbeat) is separate.
This commit is contained in:
1 parent
dabffdebc0
commit
046217079c
18 files changed
+338
-23
No files matched your search
@@ -18,6 +18,7 @@ import Stats from './views/Stats.jsx'
|
||||
import History from './views/History.jsx'
|
||||
import Library from './views/Library.jsx'
|
||||
import Settings from './views/Settings.jsx'
|
||||
import Admin from './views/Admin.jsx'
|
||||
|
||||
function applyPrefs(theme, accent) {
|
||||
const de = document.documentElement
|
||||
@@ -56,6 +57,7 @@ function Shell() {
|
||||
<Route path="/history" element={<History />} />
|
||||
<Route path="/library" element={<Library />} />
|
||||
<Route path="/settings" element={<Settings />} />
|
||||
<Route path="/admin" element={user?.admin ? <Admin /> : <Navigate to="/home" replace />} />
|
||||
<Route path="*" element={<Navigate to="/home" replace />} />
|
||||
</Routes>
|
||||
)}
|
||||
|
||||
@@ -45,8 +45,8 @@ function credToJSON(cred) {
|
||||
}
|
||||
return out
|
||||
}
|
||||
export async function passkeyRegister(name) {
|
||||
const { cid, options } = await api('/api/register/options', { method: 'POST', body: JSON.stringify({ name }) })
|
||||
export async function passkeyRegister(name, code) {
|
||||
const { cid, options } = await api('/api/register/options', { method: 'POST', body: JSON.stringify({ name, code: code || '' }) })
|
||||
const cred = await navigator.credentials.create({ publicKey: toCreationOptions(options) })
|
||||
const res = await api('/api/register/verify', { method: 'POST', body: JSON.stringify({ cid, credential: credToJSON(cred) }) })
|
||||
return res.user
|
||||
|
||||
@@ -352,5 +352,9 @@ export default {
|
||||
'Edit or delete this exercise': 'Übung bearbeiten oder löschen',
|
||||
'Remove from routine': 'Aus Routine entfernen',
|
||||
'Minimize': 'Verkleinern',
|
||||
'Expand': 'Vergrössern'
|
||||
'Expand': 'Vergrössern',
|
||||
'Invite code': 'Einladungscode',
|
||||
'This app is invite-only — enter the code you were given.': 'Diese App ist nur mit Einladung — gib den Code ein, den du erhalten hast.',
|
||||
'An invite code is required': 'Ein Einladungscode ist erforderlich',
|
||||
'Admin dashboard': 'Admin-Dashboard'
|
||||
}
|
||||
@@ -334,5 +334,9 @@ export default {
|
||||
'Edit or delete this exercise': 'Editar o eliminar este ejercicio',
|
||||
'Remove from routine': 'Quitar de la rutina',
|
||||
'Minimize': 'Minimizar',
|
||||
'Expand': 'Ampliar'
|
||||
'Expand': 'Ampliar',
|
||||
'Invite code': 'Código de invitación',
|
||||
'This app is invite-only — enter the code you were given.': 'Esta app es solo por invitación: introduce el código que te dieron.',
|
||||
'An invite code is required': 'Se requiere un código de invitación',
|
||||
'Admin dashboard': 'Panel de administración'
|
||||
}
|
||||
@@ -334,5 +334,9 @@ export default {
|
||||
'Edit or delete this exercise': 'Modifier ou supprimer cet exercice',
|
||||
'Remove from routine': 'Retirer de la routine',
|
||||
'Minimize': 'Réduire',
|
||||
'Expand': 'Agrandir'
|
||||
'Expand': 'Agrandir',
|
||||
'Invite code': 'Code d’invitation',
|
||||
'This app is invite-only — enter the code you were given.': 'Cette appli est sur invitation — saisissez le code qu’on vous a donné.',
|
||||
'An invite code is required': 'Un code d’invitation est requis',
|
||||
'Admin dashboard': 'Tableau d’administration'
|
||||
}
|
||||
@@ -334,5 +334,9 @@ export default {
|
||||
'Edit or delete this exercise': 'इस एक्सरसाइज़ को संपादित या हटाएं',
|
||||
'Remove from routine': 'रूटीन से हटाएं',
|
||||
'Minimize': 'छोटा करें',
|
||||
'Expand': 'बड़ा करें'
|
||||
'Expand': 'बड़ा करें',
|
||||
'Invite code': 'इनवाइट कोड',
|
||||
'This app is invite-only — enter the code you were given.': 'यह ऐप केवल इनवाइट से है — आपको दिया गया कोड डालें।',
|
||||
'An invite code is required': 'एक इनवाइट कोड आवश्यक है',
|
||||
'Admin dashboard': 'एडमिन डैशबोर्ड'
|
||||
}
|
||||
@@ -334,5 +334,9 @@ export default {
|
||||
'Edit or delete this exercise': 'Modifica o elimina questo esercizio',
|
||||
'Remove from routine': 'Rimuovi dalla routine',
|
||||
'Minimize': 'Riduci',
|
||||
'Expand': 'Ingrandisci'
|
||||
'Expand': 'Ingrandisci',
|
||||
'Invite code': 'Codice di invito',
|
||||
'This app is invite-only — enter the code you were given.': 'Questa app è solo su invito: inserisci il codice che hai ricevuto.',
|
||||
'An invite code is required': 'È richiesto un codice di invito',
|
||||
'Admin dashboard': 'Pannello di amministrazione'
|
||||
}
|
||||
@@ -334,5 +334,9 @@ export default {
|
||||
'Edit or delete this exercise': '이 운동 편집 또는 삭제',
|
||||
'Remove from routine': '루틴에서 제거',
|
||||
'Minimize': '축소',
|
||||
'Expand': '확대'
|
||||
'Expand': '확대',
|
||||
'Invite code': '초대 코드',
|
||||
'This app is invite-only — enter the code you were given.': '이 앱은 초대 전용입니다 — 받은 코드를 입력하세요.',
|
||||
'An invite code is required': '초대 코드가 필요합니다',
|
||||
'Admin dashboard': '관리자 대시보드'
|
||||
}
|
||||
@@ -334,5 +334,9 @@ export default {
|
||||
'Edit or delete this exercise': 'Edytuj lub usuń to ćwiczenie',
|
||||
'Remove from routine': 'Usuń z planu',
|
||||
'Minimize': 'Zmniejsz',
|
||||
'Expand': 'Powiększ'
|
||||
'Expand': 'Powiększ',
|
||||
'Invite code': 'Kod zaproszenia',
|
||||
'This app is invite-only — enter the code you were given.': 'Ta aplikacja jest tylko na zaproszenie — wpisz otrzymany kod.',
|
||||
'An invite code is required': 'Wymagany jest kod zaproszenia',
|
||||
'Admin dashboard': 'Panel administratora'
|
||||
}
|
||||
@@ -334,5 +334,9 @@ export default {
|
||||
'Edit or delete this exercise': 'Editar ou eliminar este exercício',
|
||||
'Remove from routine': 'Remover da rotina',
|
||||
'Minimize': 'Minimizar',
|
||||
'Expand': 'Ampliar'
|
||||
'Expand': 'Ampliar',
|
||||
'Invite code': 'Código de convite',
|
||||
'This app is invite-only — enter the code you were given.': 'Esta app é só por convite — introduz o código que recebeste.',
|
||||
'An invite code is required': 'É necessário um código de convite',
|
||||
'Admin dashboard': 'Painel de administração'
|
||||
}
|
||||
@@ -334,5 +334,9 @@ export default {
|
||||
'Edit or delete this exercise': 'Изменить или удалить это упражнение',
|
||||
'Remove from routine': 'Убрать из программы',
|
||||
'Minimize': 'Свернуть',
|
||||
'Expand': 'Развернуть'
|
||||
'Expand': 'Развернуть',
|
||||
'Invite code': 'Код приглашения',
|
||||
'This app is invite-only — enter the code you were given.': 'Приложение только по приглашению — введите выданный вам код.',
|
||||
'An invite code is required': 'Требуется код приглашения',
|
||||
'Admin dashboard': 'Панель администратора'
|
||||
}
|
||||
@@ -334,5 +334,9 @@ export default {
|
||||
'Edit or delete this exercise': 'Bu egzersizi düzenle veya sil',
|
||||
'Remove from routine': 'Rutinden çıkar',
|
||||
'Minimize': 'Küçült',
|
||||
'Expand': 'Büyüt'
|
||||
'Expand': 'Büyüt',
|
||||
'Invite code': 'Davet kodu',
|
||||
'This app is invite-only — enter the code you were given.': 'Bu uygulama yalnızca davetle — sana verilen kodu gir.',
|
||||
'An invite code is required': 'Bir davet kodu gerekli',
|
||||
'Admin dashboard': 'Yönetici paneli'
|
||||
}
|
||||
@@ -334,5 +334,9 @@ export default {
|
||||
'Edit or delete this exercise': '编辑或删除此动作',
|
||||
'Remove from routine': '从计划中移除',
|
||||
'Minimize': '缩小',
|
||||
'Expand': '放大'
|
||||
'Expand': '放大',
|
||||
'Invite code': '邀请码',
|
||||
'This app is invite-only — enter the code you were given.': '此应用仅限邀请——请输入你收到的邀请码。',
|
||||
'An invite code is required': '需要邀请码',
|
||||
'Admin dashboard': '管理后台'
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
import { useEffect, useState } from 'react'
|
||||
import { useNavigate } from 'react-router-dom'
|
||||
import { useStore } from '../store/useStore.js'
|
||||
import { useUI } from '../store/useUI.js'
|
||||
import { api } from '../lib/api.js'
|
||||
import { fmtDate, fmtNum, fmtVol, fmtDur } from '../lib/format.js'
|
||||
import { workoutVolume, setsDone } from '../lib/history.js'
|
||||
import { confirmSheet } from '../sheets.jsx'
|
||||
|
||||
// Admin-only operator dashboard (owner passkey + admin flag; guarded again server-side).
|
||||
// Deliberately English-only — it isn't part of the translated end-user surface, so it stays
|
||||
// out of the per-language string packs.
|
||||
|
||||
const rel = ts => {
|
||||
if (!ts) return 'never'
|
||||
const s = Math.max(0, (Date.now() - ts) / 1000)
|
||||
if (s < 60) return 'just now'
|
||||
if (s < 3600) return Math.floor(s / 60) + 'm ago'
|
||||
if (s < 86400) return Math.floor(s / 3600) + 'h ago'
|
||||
return Math.floor(s / 86400) + 'd ago'
|
||||
}
|
||||
|
||||
function UserDetail({ id, onChanged, close }) {
|
||||
const [d, setD] = useState(null)
|
||||
const toast = useUI(s => s.toast)
|
||||
useEffect(() => { api('/api/admin/user?id=' + encodeURIComponent(id)).then(setD).catch(e => toast(e.message)) }, [id])
|
||||
if (!d) return <div className="muted small">Loading…</div>
|
||||
const u = d.user
|
||||
const setDisabled = disabled => {
|
||||
api('/api/admin/user/disable', { method: 'POST', body: JSON.stringify({ id: u.id, disabled }) })
|
||||
.then(() => { toast(disabled ? 'User disabled' : 'User enabled'); onChanged(); close() })
|
||||
.catch(e => toast(e.message))
|
||||
}
|
||||
return <>
|
||||
<h3 className="capitalize">{u.name}</h3>
|
||||
<div className="row" style={{ gap: 6, flexWrap: 'wrap', margin: '8px 0 12px' }}>
|
||||
{u.admin && <span className="tag acc">admin</span>}
|
||||
{u.disabled && <span className="tag" style={{ color: 'var(--red)' }}>disabled</span>}
|
||||
{u.invitedBy && <span className="tag">invite {u.invitedBy}</span>}
|
||||
<span className="tag">joined {u.created ? fmtDate(u.created.slice(0, 10)) : '—'}</span>
|
||||
</div>
|
||||
<div className="tiles" style={{ textAlign: 'left' }}>
|
||||
<div className="tile"><div className="l">Workouts</div><div className="v" style={{ fontSize: '1.1rem' }}>{d.workouts.length}</div></div>
|
||||
<div className="tile"><div className="l">Weigh-ins</div><div className="v" style={{ fontSize: '1.1rem' }}>{d.bodyweight.length}</div></div>
|
||||
<div className="tile"><div className="l">Routines</div><div className="v" style={{ fontSize: '1.1rem' }}>{d.routines.length}</div></div>
|
||||
<div className="tile"><div className="l">Last sync</div><div className="v" style={{ fontSize: '.95rem' }}>{rel(d.lastSync)}</div></div>
|
||||
</div>
|
||||
{!u.admin && <button className={'btn ' + (u.disabled ? 'primary' : 'danger')} style={{ margin: '12px 0 4px' }}
|
||||
onClick={() => u.disabled ? setDisabled(false)
|
||||
: confirmSheet({ title: 'Disable ' + u.name + '?', message: 'They are signed out everywhere and can no longer sync or log in until re-enabled.', confirmText: 'Disable', danger: true, onConfirm: () => setDisabled(true) })}>
|
||||
{u.disabled ? 'Enable account' : 'Disable account'}</button>}
|
||||
<h4 className="sec">Workout history</h4>
|
||||
{d.workouts.length ? <div className="list" style={{ gap: 0 }}>
|
||||
{d.workouts.slice(0, 60).map(w => <div key={w.id} className="row between" style={{ padding: '9px 2px', borderBottom: '1px solid var(--bg2)' }}>
|
||||
<div><div className="small" style={{ fontWeight: 700 }}>{w.name}</div>
|
||||
<div className="dim" style={{ fontSize: '.72rem' }}>{fmtDate(w.d, true)} · {fmtDur((w.end || w.start) - w.start)} · {setsDone(w)} sets{w.prs?.length ? ' · 🏆 ' + w.prs.length : ''}</div></div>
|
||||
<span className="small muted">{fmtVol(w.vol ?? workoutVolume(w), d.unit)}</span>
|
||||
</div>)}
|
||||
</div> : <div className="empty small">No workouts logged.</div>}
|
||||
</>
|
||||
}
|
||||
|
||||
function InvitesCard({ invites, reload }) {
|
||||
const toast = useUI(s => s.toast)
|
||||
const gen = () => api('/api/admin/invites/new', { method: 'POST', body: '{}' })
|
||||
.then(({ invite }) => { navigator.clipboard?.writeText(invite.code).catch(() => {}); toast('Code ' + invite.code + ' created & copied'); reload() })
|
||||
.catch(e => toast(e.message))
|
||||
const revoke = code => api('/api/admin/invites/revoke', { method: 'POST', body: JSON.stringify({ code }) })
|
||||
.then(() => { toast('Code revoked'); reload() }).catch(e => toast(e.message))
|
||||
const open = (invites || []).filter(i => !i.usedBy)
|
||||
const used = (invites || []).filter(i => i.usedBy)
|
||||
return <div className="card">
|
||||
<div className="row between"><h2 style={{ margin: 0 }}>Invite codes</h2>
|
||||
<button className="btn sm primary" onClick={gen}>+ Generate</button></div>
|
||||
<div className="small muted" style={{ margin: '6px 0 10px' }}>{open.length} unused · {used.length} redeemed</div>
|
||||
{open.map(i => <div key={i.code} className="row between" style={{ padding: '7px 2px', borderBottom: '1px solid var(--bg2)' }}>
|
||||
<span style={{ fontFamily: 'monospace', fontWeight: 700, letterSpacing: '.06em' }}
|
||||
onClick={() => { navigator.clipboard?.writeText(i.code).catch(() => {}); toast('Copied ' + i.code) }}>{i.code}</span>
|
||||
<button className="iconbtn" style={{ width: 34, height: 30, fontSize: '.9rem' }} onClick={() => revoke(i.code)} aria-label="revoke">🗑</button>
|
||||
</div>)}
|
||||
{used.map(i => <div key={i.code} className="row between dim" style={{ padding: '7px 2px', fontSize: '.8rem' }}>
|
||||
<span style={{ fontFamily: 'monospace' }}>{i.code}</span><span>→ {i.usedByName || 'used'}</span>
|
||||
</div>)}
|
||||
{!open.length && !used.length && <div className="dim small">No codes yet — generate one to invite someone.</div>}
|
||||
</div>
|
||||
}
|
||||
|
||||
export default function Admin() {
|
||||
const nav = useNavigate()
|
||||
const user = useStore(s => s.user)
|
||||
const toast = useUI(s => s.toast)
|
||||
const openSheet = useUI(s => s.openSheet)
|
||||
const [users, setUsers] = useState(null)
|
||||
const [invites, setInvites] = useState(null)
|
||||
const [inviteOnly, setInviteOnly] = useState(false)
|
||||
|
||||
const loadUsers = () => api('/api/admin/users').then(d => { setUsers(d.users); setInviteOnly(d.invite_only) }).catch(e => toast(e.message || 'Failed to load'))
|
||||
const loadInvites = () => api('/api/admin/invites').then(d => setInvites(d.invites)).catch(() => {})
|
||||
useEffect(() => { if (user?.admin) { loadUsers(); loadInvites() } }, [])
|
||||
if (!user?.admin) return null
|
||||
|
||||
const openUser = id => openSheet(close => <UserDetail id={id} onChanged={loadUsers} close={close} />)
|
||||
const activeCount = (users || []).filter(u => u.lastSync && Date.now() - u.lastSync < 7 * 86400000).length
|
||||
const disabledCount = (users || []).filter(u => u.disabled).length
|
||||
|
||||
return <div className="narrow">
|
||||
<div className="hdr">
|
||||
<button className="iconbtn" onClick={() => nav('/settings')}>‹</button>
|
||||
<div style={{ flex: 1, marginLeft: 8 }}><h1 style={{ margin: 0 }}>Admin</h1>
|
||||
<div className="sub">{users ? users.length + ' users · ' + activeCount + ' active this week' : 'Loading…'}</div></div>
|
||||
<button className="iconbtn" onClick={() => { loadUsers(); loadInvites() }} aria-label="refresh">↻</button>
|
||||
</div>
|
||||
|
||||
<div className="tiles" style={{ marginBottom: 12 }}>
|
||||
<div className="tile"><div className="l">Users</div><div className="v">{users ? users.length : '—'}</div></div>
|
||||
<div className="tile"><div className="l">Active 7d</div><div className="v">{users ? activeCount : '—'}</div></div>
|
||||
<div className="tile"><div className="l">Disabled</div><div className="v">{users ? disabledCount : '—'}</div></div>
|
||||
<div className="tile"><div className="l">Signup</div><div className="v" style={{ fontSize: '.95rem' }}>{inviteOnly ? 'invite' : 'open'}</div></div>
|
||||
</div>
|
||||
|
||||
<InvitesCard invites={invites} reload={loadInvites} />
|
||||
|
||||
<h4 className="sec">Users</h4>
|
||||
<div className="list">
|
||||
{(users || []).map(u => <div key={u.id} className="item" onClick={() => openUser(u.id)} style={u.disabled ? { opacity: .55 } : null}>
|
||||
<div className="grow"><div className="tt">{u.name} {u.admin && <span className="tag acc" style={{ marginLeft: 4 }}>admin</span>}{u.disabled && <span className="tag" style={{ marginLeft: 4, color: 'var(--red)' }}>off</span>}</div>
|
||||
<div className="ss">{u.workouts} workouts{u.lastWorkout ? ' · last ' + fmtDate(u.lastWorkout) : ''} · synced {rel(u.lastSync)}</div></div>
|
||||
{u.hasPush && <span title="push enabled">🔔</span>}<span className="chev">›</span>
|
||||
</div>)}
|
||||
{users && !users.length && <div className="empty">No users yet.</div>}
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useStore } from '../store/useStore.js'
|
||||
import { useUI } from '../store/useUI.js'
|
||||
import { webauthnOK, passkeyLogin, passkeyRegister, BIO } from '../lib/api.js'
|
||||
import { webauthnOK, passkeyLogin, passkeyRegister, api, BIO } from '../lib/api.js'
|
||||
import { hasData } from '../store/useStore.js'
|
||||
import { t } from '../lib/i18n.js'
|
||||
import { useState, useRef, useEffect } from 'react'
|
||||
@@ -8,13 +8,17 @@ import { useState, useRef, useEffect } from 'react'
|
||||
function RegisterSheet({ close }) {
|
||||
const { setUser, pushState, pullState } = useStore()
|
||||
const [name, setName] = useState('')
|
||||
const [code, setCode] = useState('')
|
||||
const [inviteOnly, setInviteOnly] = useState(false)
|
||||
const ref = useRef(null)
|
||||
useEffect(() => { setTimeout(() => ref.current?.focus(), 250) }, [])
|
||||
useEffect(() => { api('/api/config').then(c => setInviteOnly(!!c.invite_only)).catch(() => {}) }, [])
|
||||
const go = async () => {
|
||||
const n = name.trim()
|
||||
if (!n) { useUI.getState().toast(t('Enter a name')); return }
|
||||
if (inviteOnly && !code.trim()) { useUI.getState().toast(t('An invite code is required')); return }
|
||||
try {
|
||||
const u = await passkeyRegister(n)
|
||||
const u = await passkeyRegister(n, code.trim())
|
||||
setUser(u); close()
|
||||
if (hasData(useStore.getState().S)) { await pushState(); useUI.getState().toast(t('Profile created — data from this device moved into it ✓')) }
|
||||
else { await pullState(); useUI.getState().toast(t('Welcome, {0} 💪', u.name)) }
|
||||
@@ -24,6 +28,12 @@ function RegisterSheet({ close }) {
|
||||
<h3>{t('Create your profile ✨')}</h3>
|
||||
<div className="muted small" style={{ marginBottom: 14 }}>{t('Pick a name, then confirm with {0}. The passkey is saved in your device — no password needed.', BIO)}</div>
|
||||
<input ref={ref} className="input" placeholder={t('Your name')} maxLength={40} value={name} onChange={e => setName(e.target.value)} />
|
||||
{inviteOnly && <>
|
||||
<div style={{ height: 10 }} />
|
||||
<input className="input" placeholder={t('Invite code')} maxLength={40} value={code}
|
||||
onChange={e => setCode(e.target.value.toUpperCase())} style={{ letterSpacing: '.08em', fontWeight: 700 }} />
|
||||
<div className="dim small" style={{ marginTop: 6 }}>{t('This app is invite-only — enter the code you were given.')}</div>
|
||||
</>}
|
||||
<div style={{ height: 12 }} />
|
||||
<button className="btn primary" onClick={go}>{t('Create passkey')}</button>
|
||||
</>
|
||||
|
||||
@@ -44,10 +44,13 @@ export default function Settings() {
|
||||
|
||||
<div className="card">
|
||||
<h2>{t('Account')}</h2>
|
||||
{user ? <div className="row between">
|
||||
{user ? <>
|
||||
<div className="row between">
|
||||
<div><b>{user.name}</b><div className="small muted">{t('Signed in with passkey — data syncs to this profile.')}</div></div>
|
||||
<button className="btn sm danger" onClick={() => confirmSheet({ title: t('Sign out?'), message: t('Your data is synced to your profile first, then cleared from this device.'), confirmText: t('Sign out'), danger: true, onConfirm: () => { signOut(); nav('/home') } })}>{t('Sign out')}</button>
|
||||
</div> : <>
|
||||
</div>
|
||||
{user.admin && <><div style={{ height: 10 }} /><button className="btn sm" onClick={() => nav('/admin')}>🛠️ {t('Admin dashboard')}</button></>}
|
||||
</> : <>
|
||||
<div className="small muted" style={{ marginBottom: 10 }}>{t('Guest mode — data lives only in this browser. Create a passkey profile to keep it safe and separate per person.')}</div>
|
||||
{webauthnOK() ? <>
|
||||
<button className="btn primary" onClick={registerHere}>✨ {t('Create passkey profile')}</button>
|
||||
|
||||
Reference in new issue
Block a user