diff --git a/.env.example b/.env.example index 8d30abe..831635f 100644 --- a/.env.example +++ b/.env.example @@ -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 diff --git a/api/server.js b/api/server.js index e4831e2..d8c6839 100644 --- a/api/server.js +++ b/api/server.js @@ -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 }); } }; diff --git a/frontend/src/App.jsx b/frontend/src/App.jsx index 22a8dd6..b1c0646 100644 --- a/frontend/src/App.jsx +++ b/frontend/src/App.jsx @@ -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() { } /> } /> } /> + : } /> } /> )} diff --git a/frontend/src/lib/api.js b/frontend/src/lib/api.js index e5f6a1f..6a7e620 100644 --- a/frontend/src/lib/api.js +++ b/frontend/src/lib/api.js @@ -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 diff --git a/frontend/src/locales/de.js b/frontend/src/locales/de.js index 1924b7f..b1c5475 100644 --- a/frontend/src/locales/de.js +++ b/frontend/src/locales/de.js @@ -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' } diff --git a/frontend/src/locales/es.js b/frontend/src/locales/es.js index e85d781..d70762f 100644 --- a/frontend/src/locales/es.js +++ b/frontend/src/locales/es.js @@ -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' } diff --git a/frontend/src/locales/fr.js b/frontend/src/locales/fr.js index 2849240..af8b843 100644 --- a/frontend/src/locales/fr.js +++ b/frontend/src/locales/fr.js @@ -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' } diff --git a/frontend/src/locales/hi.js b/frontend/src/locales/hi.js index 55e0738..0680a22 100644 --- a/frontend/src/locales/hi.js +++ b/frontend/src/locales/hi.js @@ -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': 'एडमिन डैशबोर्ड' } diff --git a/frontend/src/locales/it.js b/frontend/src/locales/it.js index 0537158..0c67f5e 100644 --- a/frontend/src/locales/it.js +++ b/frontend/src/locales/it.js @@ -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' } diff --git a/frontend/src/locales/ko.js b/frontend/src/locales/ko.js index 98ef273..89fc91e 100644 --- a/frontend/src/locales/ko.js +++ b/frontend/src/locales/ko.js @@ -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': '관리자 대시보드' } diff --git a/frontend/src/locales/pl.js b/frontend/src/locales/pl.js index 3c14456..6b9bb6e 100644 --- a/frontend/src/locales/pl.js +++ b/frontend/src/locales/pl.js @@ -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' } diff --git a/frontend/src/locales/pt.js b/frontend/src/locales/pt.js index 6b8cc5c..a6a993f 100644 --- a/frontend/src/locales/pt.js +++ b/frontend/src/locales/pt.js @@ -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' } diff --git a/frontend/src/locales/ru.js b/frontend/src/locales/ru.js index bddcac2..8ae0263 100644 --- a/frontend/src/locales/ru.js +++ b/frontend/src/locales/ru.js @@ -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': 'Панель администратора' } diff --git a/frontend/src/locales/tr.js b/frontend/src/locales/tr.js index b2fc5de..14b2759 100644 --- a/frontend/src/locales/tr.js +++ b/frontend/src/locales/tr.js @@ -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' } diff --git a/frontend/src/locales/zh.js b/frontend/src/locales/zh.js index 94c0913..cedf4bb 100644 --- a/frontend/src/locales/zh.js +++ b/frontend/src/locales/zh.js @@ -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': '管理后台' } diff --git a/frontend/src/views/Admin.jsx b/frontend/src/views/Admin.jsx new file mode 100644 index 0000000..7c72ad8 --- /dev/null +++ b/frontend/src/views/Admin.jsx @@ -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
Loading…
+ 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 <> +

{u.name}

+
+ {u.admin && admin} + {u.disabled && disabled} + {u.invitedBy && invite {u.invitedBy}} + joined {u.created ? fmtDate(u.created.slice(0, 10)) : '—'} +
+
+
Workouts
{d.workouts.length}
+
Weigh-ins
{d.bodyweight.length}
+
Routines
{d.routines.length}
+
Last sync
{rel(d.lastSync)}
+
+ {!u.admin && } +

Workout history

+ {d.workouts.length ?
+ {d.workouts.slice(0, 60).map(w =>
+
{w.name}
+
{fmtDate(w.d, true)} · {fmtDur((w.end || w.start) - w.start)} · {setsDone(w)} sets{w.prs?.length ? ' · 🏆 ' + w.prs.length : ''}
+ {fmtVol(w.vol ?? workoutVolume(w), d.unit)} +
)} +
:
No workouts logged.
} + +} + +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
+

Invite codes

+
+
{open.length} unused · {used.length} redeemed
+ {open.map(i =>
+ { navigator.clipboard?.writeText(i.code).catch(() => {}); toast('Copied ' + i.code) }}>{i.code} + +
)} + {used.map(i =>
+ {i.code}→ {i.usedByName || 'used'} +
)} + {!open.length && !used.length &&
No codes yet — generate one to invite someone.
} +
+} + +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 => ) + const activeCount = (users || []).filter(u => u.lastSync && Date.now() - u.lastSync < 7 * 86400000).length + const disabledCount = (users || []).filter(u => u.disabled).length + + return
+
+ +

Admin

+
{users ? users.length + ' users · ' + activeCount + ' active this week' : 'Loading…'}
+ +
+ +
+
Users
{users ? users.length : '—'}
+
Active 7d
{users ? activeCount : '—'}
+
Disabled
{users ? disabledCount : '—'}
+
Signup
{inviteOnly ? 'invite' : 'open'}
+
+ + + +

Users

+
+ {(users || []).map(u =>
openUser(u.id)} style={u.disabled ? { opacity: .55 } : null}> +
{u.name} {u.admin && admin}{u.disabled && off}
+
{u.workouts} workouts{u.lastWorkout ? ' · last ' + fmtDate(u.lastWorkout) : ''} · synced {rel(u.lastSync)}
+ {u.hasPush && 🔔}› +
)} + {users && !users.length &&
No users yet.
} +
+
+} diff --git a/frontend/src/views/Login.jsx b/frontend/src/views/Login.jsx index e9d3e5d..20b8b5c 100644 --- a/frontend/src/views/Login.jsx +++ b/frontend/src/views/Login.jsx @@ -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 }) {

{t('Create your profile ✨')}

{t('Pick a name, then confirm with {0}. The passkey is saved in your device — no password needed.', BIO)}
setName(e.target.value)} /> + {inviteOnly && <> +
+ setCode(e.target.value.toUpperCase())} style={{ letterSpacing: '.08em', fontWeight: 700 }} /> +
{t('This app is invite-only — enter the code you were given.')}
+ }
diff --git a/frontend/src/views/Settings.jsx b/frontend/src/views/Settings.jsx index 6148dc4..f61dd9c 100644 --- a/frontend/src/views/Settings.jsx +++ b/frontend/src/views/Settings.jsx @@ -44,10 +44,13 @@ export default function Settings() {

{t('Account')}

- {user ?
+ {user ? <> +
{user.name}
{t('Signed in with passkey — data syncs to this profile.')}
-
: <> +
+ {user.admin && <>
} + : <>
{t('Guest mode — data lives only in this browser. Create a passkey profile to keep it safe and separate per person.')}
{webauthnOK() ? <>