towards multi-user

This commit is contained in:
Davide Scaini
2026-04-08 19:37:10 +02:00
parent 36a91362d9
commit f76cc0ce7e
18 changed files with 1248 additions and 30 deletions
+26 -6
View File
@@ -9,18 +9,38 @@ export async function getStaticPaths() {
try {
const candidates = [
process.env.BINCIO_DATA_DIR,
resolve(process.cwd(), 'public', 'data'), // symlinked by `bincio render`
resolve(process.cwd(), 'public', 'data'),
resolve(process.cwd(), '..', 'bincio_data'),
].filter(Boolean) as string[];
const dataDir = candidates.find(d => { try { readFileSync(join(d, 'index.json')); return true; } catch { return false; } })!;
const raw = readFileSync(join(dataDir, 'index.json'), 'utf-8');
const index: BASIndex = JSON.parse(raw);
const dataDir = candidates.find(d => {
try { readFileSync(join(d, 'index.json')); return true; } catch { return false; }
})!;
return index.activities
const root: BASIndex = JSON.parse(readFileSync(join(dataDir, 'index.json'), 'utf-8'));
// Collect activities from root (single-user) or walk shards (multi-user)
function readActivities(indexPath: string): ActivitySummary[] {
try {
const idx: BASIndex = JSON.parse(readFileSync(indexPath, 'utf-8'));
const own = idx.activities ?? [];
const fromShards = (idx.shards ?? []).flatMap(s => {
const shardPath = join(dataDir, s.url);
return readActivities(shardPath);
});
return [...own, ...fromShards];
} catch {
return [];
}
}
const activities = readActivities(join(dataDir, 'index.json'));
const athlete = root.owner?.athlete ?? null;
return activities
.filter(a => a.privacy !== 'private' && a.id)
.map(a => ({
params: { id: a.id },
props: { activity: a, athlete: index.owner.athlete ?? null },
props: { activity: a, athlete },
}));
} catch {
return [];
+98
View File
@@ -0,0 +1,98 @@
---
import Base from '../../layouts/Base.astro';
---
<Base title="Invites — BincioActivity">
<div class="max-w-lg mx-auto mt-12 px-4">
<div class="flex items-center justify-between mb-6">
<h1 class="text-2xl font-bold text-white">Your invites</h1>
<button id="gen-btn"
class="px-4 py-2 rounded-lg bg-[--accent] hover:opacity-90 text-white text-sm font-medium transition-opacity">
Generate invite
</button>
</div>
<p id="invite-error" class="text-red-400 text-sm mb-4 hidden"></p>
<ul id="invite-list" class="space-y-3">
<li class="text-zinc-500 text-sm">Loading…</li>
</ul>
</div>
</Base>
<script>
const listEl = document.getElementById('invite-list')!;
const errEl = document.getElementById('invite-error')!;
function renderInvite(inv: { code: string; used: boolean; used_by: string | null; created_at: number }) {
const li = document.createElement('li');
li.className = 'flex items-center justify-between rounded-xl bg-zinc-900 border border-zinc-800 px-4 py-3';
const date = new Date(inv.created_at * 1000).toLocaleDateString('en-GB', { day: 'numeric', month: 'short', year: 'numeric' });
const registerUrl = `${window.location.origin}/register/?code=${inv.code}`;
li.innerHTML = `
<div>
<span class="font-mono text-lg tracking-widest ${inv.used ? 'text-zinc-600 line-through' : 'text-white'}">${inv.code}</span>
<p class="text-xs text-zinc-500 mt-0.5">
${inv.used ? `Used by @${inv.used_by}` : `Created ${date}`}
</p>
</div>
${!inv.used ? `
<button data-link="${registerUrl}"
class="copy-btn text-xs px-3 py-1.5 rounded-lg bg-zinc-800 hover:bg-zinc-700 text-zinc-300 transition-colors">
Copy link
</button>
` : ''}
`;
return li;
}
async function loadInvites() {
try {
const r = await fetch('/api/invites', { credentials: 'include' });
if (r.status === 401) {
window.location.href = `/login/?next=${encodeURIComponent(window.location.pathname)}`;
return;
}
if (!r.ok) throw new Error(`HTTP ${r.status}`);
const invites = await r.json();
listEl.innerHTML = '';
if (invites.length === 0) {
listEl.innerHTML = '<li class="text-zinc-500 text-sm">No invites yet.</li>';
return;
}
for (const inv of invites) listEl.appendChild(renderInvite(inv));
// Copy link buttons
listEl.querySelectorAll('.copy-btn').forEach(btn => {
btn.addEventListener('click', () => {
navigator.clipboard.writeText((btn as HTMLElement).dataset.link ?? '');
btn.textContent = 'Copied!';
setTimeout(() => { btn.textContent = 'Copy link'; }, 2000);
});
});
} catch (e: any) {
errEl.textContent = e.message;
errEl.classList.remove('hidden');
}
}
document.getElementById('gen-btn')?.addEventListener('click', async () => {
errEl.classList.add('hidden');
try {
const r = await fetch('/api/invites', { method: 'POST', credentials: 'include' });
if (!r.ok) {
const d = await r.json().catch(() => ({}));
errEl.textContent = d.detail ?? 'Could not generate invite';
errEl.classList.remove('hidden');
return;
}
await loadInvites();
} catch (e: any) {
errEl.textContent = e.message;
errEl.classList.remove('hidden');
}
});
loadInvites();
</script>
+68
View File
@@ -0,0 +1,68 @@
---
import Base from '../../layouts/Base.astro';
const editUrl = import.meta.env.PUBLIC_EDIT_URL ?? '';
---
<Base title="Login — BincioActivity" public={true}>
<div class="max-w-sm mx-auto mt-16 px-4">
<h1 class="text-2xl font-bold text-white mb-6 text-center">Sign in</h1>
<form id="login-form" class="space-y-4">
<div>
<label class="block text-sm text-zinc-400 mb-1" for="handle">Handle</label>
<input id="handle" name="handle" type="text" autocomplete="username"
class="w-full px-3 py-2 rounded-lg bg-zinc-900 border border-zinc-700 text-white placeholder-zinc-500 focus:outline-none focus:border-[--accent]"
placeholder="your handle" required />
</div>
<div>
<label class="block text-sm text-zinc-400 mb-1" for="password">Password</label>
<input id="password" name="password" type="password" autocomplete="current-password"
class="w-full px-3 py-2 rounded-lg bg-zinc-900 border border-zinc-700 text-white focus:outline-none focus:border-[--accent]"
required />
</div>
<p id="login-error" class="text-red-400 text-sm hidden"></p>
<button type="submit"
class="w-full py-2 rounded-lg bg-[--accent] hover:opacity-90 text-white font-medium transition-opacity">
Sign in
</button>
</form>
{editUrl && (
<p class="text-center text-zinc-500 text-sm mt-6">
Have an invite? <a href="/register/" class="text-[--accent] hover:underline">Create account</a>
</p>
)}
</div>
</Base>
<script>
const editUrl = import.meta.env.PUBLIC_EDIT_URL ?? (document.getElementById('login-form')?.dataset.editUrl ?? '');
document.getElementById('login-form')?.addEventListener('submit', async (e) => {
e.preventDefault();
const form = e.target as HTMLFormElement;
const handle = (form.querySelector('#handle') as HTMLInputElement).value.trim();
const password = (form.querySelector('#password') as HTMLInputElement).value;
const errEl = document.getElementById('login-error')!;
errEl.classList.add('hidden');
try {
const r = await fetch('/api/auth/login', {
method: 'POST',
credentials: 'include',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ handle, password }),
});
if (!r.ok) {
const d = await r.json().catch(() => ({}));
errEl.textContent = d.detail ?? 'Invalid credentials';
errEl.classList.remove('hidden');
return;
}
const next = new URLSearchParams(window.location.search).get('next') ?? '/';
window.location.href = next;
} catch {
errEl.textContent = 'Could not reach server';
errEl.classList.remove('hidden');
}
});
</script>
+87
View File
@@ -0,0 +1,87 @@
---
import Base from '../../layouts/Base.astro';
---
<Base title="Create account — BincioActivity" public={true}>
<div class="max-w-sm mx-auto mt-16 px-4">
<h1 class="text-2xl font-bold text-white mb-6 text-center">Create account</h1>
<form id="register-form" class="space-y-4">
<div>
<label class="block text-sm text-zinc-400 mb-1" for="code">Invite code</label>
<input id="code" name="code" type="text" autocomplete="off"
class="w-full px-3 py-2 rounded-lg bg-zinc-900 border border-zinc-700 text-white font-mono uppercase tracking-widest placeholder-zinc-500 focus:outline-none focus:border-[--accent]"
placeholder="XXXXXXXX" maxlength="8" required />
</div>
<div>
<label class="block text-sm text-zinc-400 mb-1" for="handle">Handle</label>
<input id="handle" name="handle" type="text" autocomplete="username"
class="w-full px-3 py-2 rounded-lg bg-zinc-900 border border-zinc-700 text-white placeholder-zinc-500 focus:outline-none focus:border-[--accent]"
placeholder="lowercase, letters and numbers" required />
</div>
<div>
<label class="block text-sm text-zinc-400 mb-1" for="display_name">Display name <span class="text-zinc-600">(optional)</span></label>
<input id="display_name" name="display_name" type="text"
class="w-full px-3 py-2 rounded-lg bg-zinc-900 border border-zinc-700 text-white placeholder-zinc-500 focus:outline-none focus:border-[--accent]"
placeholder="Your Name" />
</div>
<div>
<label class="block text-sm text-zinc-400 mb-1" for="password">Password</label>
<input id="password" name="password" type="password" autocomplete="new-password"
class="w-full px-3 py-2 rounded-lg bg-zinc-900 border border-zinc-700 text-white focus:outline-none focus:border-[--accent]"
minlength="8" required />
<p class="text-zinc-600 text-xs mt-1">At least 8 characters</p>
</div>
<p id="reg-error" class="text-red-400 text-sm hidden"></p>
<button type="submit"
class="w-full py-2 rounded-lg bg-[--accent] hover:opacity-90 text-white font-medium transition-opacity">
Create account
</button>
</form>
<p class="text-center text-zinc-500 text-sm mt-6">
Already have an account? <a href="/login/" class="text-[--accent] hover:underline">Sign in</a>
</p>
</div>
</Base>
<script>
// Pre-fill invite code from query param
const code = new URLSearchParams(window.location.search).get('code');
if (code) {
const input = document.getElementById('code') as HTMLInputElement;
if (input) input.value = code.toUpperCase();
}
document.getElementById('register-form')?.addEventListener('submit', async (e) => {
e.preventDefault();
const form = e.target as HTMLFormElement;
const errEl = document.getElementById('reg-error')!;
errEl.classList.add('hidden');
const body = {
code: (form.querySelector('#code') as HTMLInputElement).value.trim().toUpperCase(),
handle: (form.querySelector('#handle') as HTMLInputElement).value.trim().toLowerCase(),
display_name: (form.querySelector('#display_name') as HTMLInputElement).value.trim(),
password: (form.querySelector('#password') as HTMLInputElement).value,
};
try {
const r = await fetch('/api/register', {
method: 'POST',
credentials: 'include',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
});
if (!r.ok) {
const d = await r.json().catch(() => ({}));
errEl.textContent = d.detail ?? 'Registration failed';
errEl.classList.remove('hidden');
return;
}
window.location.href = '/';
} catch {
errEl.textContent = 'Could not reach server';
errEl.classList.remove('hidden');
}
});
</script>
+48
View File
@@ -0,0 +1,48 @@
---
/**
* Per-user profile page: /u/{handle}/
*
* In multi-user mode, getStaticPaths reads the root index.json shard manifest
* to discover all handles. In single-user mode this page is never generated.
*/
import { readFileSync } from 'node:fs';
import { join, resolve } from 'node:path';
import Base from '../../layouts/Base.astro';
import ActivityFeed from '../../components/ActivityFeed.svelte';
export async function getStaticPaths() {
try {
const candidates = [
process.env.BINCIO_DATA_DIR,
resolve(process.cwd(), 'public', 'data'),
resolve(process.cwd(), '..', 'bincio_data'),
].filter(Boolean) as string[];
const dataDir = candidates.find(d => {
try { readFileSync(join(d, 'index.json')); return true; } catch { return false; }
});
if (!dataDir) return [];
const root = JSON.parse(readFileSync(join(dataDir, 'index.json'), 'utf-8'));
const shards: Array<{ handle?: string; url: string }> = root.shards ?? [];
const handles = shards.map(s => s.handle).filter(Boolean) as string[];
return handles.map(handle => ({
params: { handle },
props: { handle, indexUrl: `${handle}/index.json` },
}));
} catch {
return [];
}
}
const { handle, indexUrl } = Astro.props as { handle: string; indexUrl: string };
const base = import.meta.env.BASE_URL;
---
<Base title={`@${handle} — BincioActivity`}>
<div class="max-w-5xl mx-auto px-4 pt-6 pb-2">
<h1 class="text-2xl font-bold text-white mb-1">@{handle}</h1>
<p class="text-zinc-500 text-sm">Activities by this user</p>
</div>
<ActivityFeed {base} filterHandle={handle} profileIndexUrl={indexUrl} client:only="svelte" />
</Base>