Branchwell

Lumen & Gesso / website · lumengesso.com / app / components / PasskeyPanel.tsx

Raw 2.2 KB on f4d070c0cd6547ed6432bda0f7f1dc2cb2181b18
1'use client';
2
3import { useCallback, useEffect, useState } from 'react';
4import { authClient } from '@/app/lib/auth-client';
5
6type Key = { id: string; name?: string | null; createdAt?: string | Date | null };
7
8// Shown to signed-in people: save a passkey (the only way to sign in), add a
9// second one on another device as a way back in, or remove one.
10export function PasskeyPanel({ compact = false }: { compact?: boolean }) {
11 const [keys, setKeys] = useState<Key[] | null>(null);
12 const [busy, setBusy] = useState(false);
13 const [msg, setMsg] = useState<string | null>(null);
14
15 const load = useCallback(async () => {
16 const res = await authClient.passkey.listUserPasskeys();
17 setKeys((res.data as Key[] | null) ?? []);
18 }, []);
19 useEffect(() => { load().catch(() => setKeys([])); }, [load]);
20
21 async function add() {
22 setBusy(true);
23 setMsg(null);
24 try {
25 const res = await authClient.passkey.addPasskey({ name: navigator.platform || 'Passkey' });
26 if (res?.error) setMsg('The passkey wasn’t saved. Try again.');
27 else { setMsg('Passkey saved. Next time, just tap Sign in with passkey.'); await load(); }
28 } finally {
29 setBusy(false);
30 }
31 }
32
33 async function remove(id: string) {
34 await authClient.passkey.deletePasskey({ id });
35 await load();
36 }
37
38 if (keys === null) return null;
39 if (compact && keys.length > 0) return null;
40 return (
41 <section className="auth__card" style={{ margin: '24px auto' }}>
42 <h2 className="auth__title">Passkeys</h2>
43 <p className="auth__body">
44 {keys.length === 0
45 ? 'Save a passkey so you can get back here any time with Face ID, Touch ID or your phone.'
46 : 'Add a second passkey on another device so you always have a way back in.'}
47 </p>
48 {keys.map((k) => (
49 <p key={k.id} className="auth__body">
50 {k.name || 'Passkey'}{' '}
51 <button type="button" className="btn" onClick={() => remove(k.id)}>Remove</button>
52 </p>
53 ))}
54 <button type="button" className="btn btn--rose btn--block" onClick={add} disabled={busy}>
55 {busy ? 'Waiting for your device…' : keys.length === 0 ? 'Save a passkey' : 'Add another passkey'}
56 </button>
57 {msg && <p className="auth__body">{msg}</p>}
58 </section>
59 );
60}