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:
Duarte Santos committed 2026-07-22 01:58:33 +02:00
1 parent dabffdebc0
commit 046217079c
18 files changed
+338 -23

No files matched your search

+15
View File
@@ -19,6 +19,21 @@ RP_NAME=openGym
#
# (Point your proxy at the web container's WEB_PORT. See docs/SELF_HOSTING.md.)
# ── Admin dashboard & invite-only signup (optional) ────────────────────────
# Both off by default — a fresh instance has open signup and no admin.
#
# Make yourself an admin: register your own passkey profile first, find your
# user id in ./data/db.json ("users"[].id), then list it here (comma-separated
# for several admins). Admins get an "Admin dashboard" link in Settings to see
# users, disable accounts, generate invite codes and view workout history.
#
# ADMIN_UIDS=youruserid,anotheradmin
#
# Require an invite code to create new profiles (existing accounts keep working;
# generate the codes from the admin dashboard):
#
# INVITE_ONLY=1
# ── Notifications (optional) ───────────────────────────────────────────────
# Push works out of the box — nothing to set. VAPID keys are generated on first
# run and saved to ./data/vapid.json. Each user's browser reports its own
+114 -6
View File
@@ -15,6 +15,10 @@ const DATA = process.env.DATA_DIR || '/data';
const RP_ID = process.env.RP_ID || 'localhost';
const ORIGIN = process.env.ORIGIN || 'http://localhost:8080';
const RP_NAME = process.env.RP_NAME || 'openGym';
// Admin dashboard (issue): admins are matched by uid; INVITE_ONLY gates new signups behind a
// code the admin generates. Both default off so a fresh self-hosted instance stays open.
const ADMIN_UIDS = (process.env.ADMIN_UIDS || '').split(',').map(s => s.trim()).filter(Boolean);
const INVITE_ONLY = /^(1|true|yes|on)$/i.test(process.env.INVITE_ONLY || '');
const SESSION_DAYS = 365;
const MAX_BODY = 5 * 1024 * 1024;
// Secure cookies require HTTPS; over plain http://localhost the flag would drop the cookie
@@ -28,9 +32,11 @@ if (!fs.existsSync(secretFile)) fs.writeFileSync(secretFile, crypto.randomBytes(
const SECRET = fs.readFileSync(secretFile, 'utf8').trim();
const dbFile = path.join(DATA, 'db.json');
let db = { users: [], creds: [], subs: [] };
let db = { users: [], creds: [], subs: [], invites: [] };
try { db = JSON.parse(fs.readFileSync(dbFile, 'utf8')); } catch {}
db.subs = db.subs || [];
db.invites = db.invites || [];
const isAdmin = user => !!user && (user.admin === true || ADMIN_UIDS.includes(user.id));
function saveDb() { atomicWrite(dbFile, JSON.stringify(db, null, 2)); }
function atomicWrite(file, content) {
const tmp = file + '.tmp';
@@ -163,7 +169,16 @@ function readSession(req) {
if (!payload) return null;
const [uid, exp] = payload.split(':');
if (!uid || +exp < Date.now()) return null;
return db.users.find(u => u.id === uid) || null;
const user = db.users.find(u => u.id === uid) || null;
if (user && user.disabled) return null; // disabled accounts are locked out everywhere
return user;
}
// Guard for /api/admin/* — resolves the caller and 401/403s if they aren't an admin.
function requireAdmin(req, res) {
const user = readSession(req);
if (!user) { json(res, 401, { error: 'not signed in' }); return null; }
if (!isAdmin(user)) { json(res, 403, { error: 'forbidden' }); return null; }
return user;
}
function sessionCookie(uid) {
return `gymsid=${makeSession(uid)}; Path=/; Max-Age=${SESSION_DAYS * 86400}; HttpOnly;${SECURE} SameSite=Lax`;
@@ -212,16 +227,22 @@ const b64uToBuf = s => Buffer.from(s, 'base64url');
const routes = {
'GET /api/health': async (req, res) => json(res, 200, { ok: true, users: db.users.length }),
// Public config the login screen needs before anyone is signed in.
'GET /api/config': async (req, res) => json(res, 200, { invite_only: INVITE_ONLY }),
'GET /api/me': async (req, res) => {
const user = readSession(req);
if (!user) return json(res, 401, { error: 'not signed in' });
json(res, 200, { user: { id: user.id, name: user.name } });
json(res, 200, { user: { id: user.id, name: user.name, admin: isAdmin(user) } });
},
'POST /api/register/options': async (req, res) => {
const body = await readBody(req);
const name = String(body.name || '').trim().slice(0, 40);
if (!name) return json(res, 400, { error: 'name required' });
const code = String(body.code || '').trim().toUpperCase();
if (INVITE_ONLY && !db.invites.some(i => i.code === code && !i.usedBy && !i.revoked))
return json(res, 403, { error: 'a valid invite code is required' });
const uid = crypto.randomBytes(12).toString('base64url');
const options = await generateRegistrationOptions({
rpName: RP_NAME, rpID: RP_ID,
@@ -230,7 +251,7 @@ const routes = {
authenticatorSelection: { residentKey: 'required', userVerification: 'preferred' },
excludeCredentials: []
});
const cid = putChallenge({ challenge: options.challenge, name, uid });
const cid = putChallenge({ challenge: options.challenge, name, uid, code });
json(res, 200, { cid, options });
},
@@ -251,7 +272,14 @@ const routes = {
if (!verification.verified) return json(res, 400, { error: 'not verified' });
const { credential } = verification.registrationInfo;
if (db.creds.find(x => x.id === credential.id)) return json(res, 409, { error: 'credential already registered' });
// Re-check the invite at the last moment (it may have been used/revoked since options), then burn it.
let invite = null;
if (INVITE_ONLY) {
invite = db.invites.find(i => i.code === c.code && !i.usedBy && !i.revoked);
if (!invite) return json(res, 403, { error: 'invite code is no longer valid — ask for a new one' });
}
const user = { id: c.uid, name: c.name, created: new Date().toISOString() };
if (invite) { user.invitedBy = invite.code; invite.usedBy = user.id; invite.usedAt = user.created; }
db.users.push(user);
db.creds.push({
id: credential.id, userId: user.id,
@@ -260,7 +288,7 @@ const routes = {
transports: body.credential?.response?.transports || []
});
saveDb();
json(res, 200, { user: { id: user.id, name: user.name } }, { 'Set-Cookie': sessionCookie(user.id) });
json(res, 200, { user: { id: user.id, name: user.name, admin: isAdmin(user) } }, { 'Set-Cookie': sessionCookie(user.id) });
},
'POST /api/login/options': async (req, res) => {
@@ -298,7 +326,8 @@ const routes = {
saveDb();
const user = db.users.find(u => u.id === cred.userId);
if (!user) return json(res, 500, { error: 'user missing' });
json(res, 200, { user: { id: user.id, name: user.name } }, { 'Set-Cookie': sessionCookie(user.id) });
if (user.disabled) return json(res, 403, { error: 'this account has been disabled' });
json(res, 200, { user: { id: user.id, name: user.name, admin: isAdmin(user) } }, { 'Set-Cookie': sessionCookie(user.id) });
},
'POST /api/logout': async (req, res) => json(res, 200, { ok: true }, { 'Set-Cookie': clearCookie }),
@@ -367,6 +396,85 @@ const routes = {
if (!user) return json(res, 401, { error: 'not signed in' });
cancelRestTimer(user.id);
json(res, 200, { ok: true });
},
/* ---------- admin dashboard ---------- */
// One row per user, cheap enough for a personal instance (reads each state file once).
'GET /api/admin/users': async (req, res) => {
if (!requireAdmin(req, res)) return;
const users = db.users.map(u => {
const S = readState(u.id) || {};
const workouts = S.workouts || [];
const last = workouts[workouts.length - 1];
return {
id: u.id, name: u.name, created: u.created || null,
disabled: !!u.disabled, admin: isAdmin(u), invitedBy: u.invitedBy || null,
workouts: workouts.length,
lastWorkout: last ? last.d : null,
lastSync: S._ts || null,
hasPush: db.subs.some(s => s.userId === u.id)
};
});
json(res, 200, { users, invite_only: INVITE_ONLY });
},
// Drill-down: full workout history + body-weight log for one user.
'GET /api/admin/user': async (req, res) => {
if (!requireAdmin(req, res)) return;
const id = new URL(req.url, 'http://x').searchParams.get('id');
const u = db.users.find(x => x.id === id);
if (!u) return json(res, 404, { error: 'no such user' });
const S = readState(u.id) || {};
json(res, 200, {
user: { id: u.id, name: u.name, created: u.created || null, disabled: !!u.disabled, admin: isAdmin(u), invitedBy: u.invitedBy || null },
unit: S.unit || 'kg',
lastSync: S._ts || null,
routines: (S.routines || []).map(r => ({ id: r.id, name: r.name, emoji: r.emoji, count: (r.ex || []).length })),
bodyweight: S.bodyweight || [],
workouts: (S.workouts || []).slice().reverse() // newest first for display
});
},
'POST /api/admin/user/disable': async (req, res) => {
if (!requireAdmin(req, res)) return;
const body = await readBody(req);
const u = db.users.find(x => x.id === body.id);
if (!u) return json(res, 404, { error: 'no such user' });
if (isAdmin(u)) return json(res, 400, { error: 'cannot disable an admin' });
u.disabled = !!body.disabled;
saveDb();
json(res, 200, { ok: true, id: u.id, disabled: u.disabled });
},
'GET /api/admin/invites': async (req, res) => {
if (!requireAdmin(req, res)) return;
// resolve usedBy uid → name for display
const invites = db.invites.map(i => ({
...i, usedByName: i.usedBy ? (db.users.find(u => u.id === i.usedBy) || {}).name || null : null
}));
json(res, 200, { invites, invite_only: INVITE_ONLY });
},
'POST /api/admin/invites/new': async (req, res) => {
const admin = requireAdmin(req, res); if (!admin) return;
const body = await readBody(req);
let code;
do { code = crypto.randomBytes(4).toString('hex').toUpperCase(); } while (db.invites.some(i => i.code === code));
const invite = { code, note: String(body.note || '').slice(0, 60), createdBy: admin.id, created: new Date().toISOString() };
db.invites.push(invite);
saveDb();
json(res, 200, { invite });
},
'POST /api/admin/invites/revoke': async (req, res) => {
if (!requireAdmin(req, res)) return;
const body = await readBody(req);
const inv = db.invites.find(i => i.code === String(body.code || '').toUpperCase());
if (!inv) return json(res, 404, { error: 'no such code' });
if (inv.usedBy) return json(res, 400, { error: 'already used — cannot revoke' });
db.invites = db.invites.filter(i => i.code !== inv.code);
saveDb();
json(res, 200, { ok: true });
}
};
+2
View File
@@ -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>
)}
+2 -2
View File
@@ -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
+5 -1
View File
@@ -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'
}
+5 -1
View File
@@ -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'
}
+5 -1
View File
@@ -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'
}
+5 -1
View File
@@ -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': 'एडमिन डैशबोर्ड'
}
+5 -1
View File
@@ -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'
}
+5 -1
View File
@@ -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': '관리자 대시보드'
}
+5 -1
View File
@@ -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'
}
+5 -1
View File
@@ -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'
}
+5 -1
View File
@@ -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': 'Панель администратора'
}
+5 -1
View File
@@ -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'
}
+5 -1
View File
@@ -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': '管理后台'
}
+133
View File
@@ -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>
}
+12 -2
View File
@@ -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>
</>
+5 -2
View File
@@ -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>