feat: finalize ticket merging and speaker-aware imports
This commit is contained in:
1 parent
648daa0794
commit
4e71e9b797
35 files changed
+1772
-348
No files matched your search
@@ -2,6 +2,7 @@
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="referrer" content="no-referrer" />
|
||||
<link rel="icon" type="image/png" href="/favicon.png" />
|
||||
<link rel="apple-touch-icon" href="/apple-touch-icon.png" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />
|
||||
|
||||
@@ -35,6 +35,13 @@ server {
|
||||
try_files $uri =404;
|
||||
}
|
||||
|
||||
location = /auth/callback {
|
||||
access_log off;
|
||||
add_header Cache-Control "no-store";
|
||||
add_header Referrer-Policy "no-referrer";
|
||||
try_files /index.html =404;
|
||||
}
|
||||
|
||||
# ---- Supabase same-origin proxy -------------------------------------
|
||||
# No trailing slash on proxy_pass => the original URI is passed through
|
||||
# unchanged (e.g. /auth/v1/token -> http://<target>/auth/v1/token).
|
||||
|
||||
@@ -85,7 +85,7 @@ export function QrImage({ value, size = 180 }: { value: string; size?: number })
|
||||
* decoded text. The camera only works on a secure context (https or localhost);
|
||||
* the manual field always works.
|
||||
*/
|
||||
export function Scanner({ onResult, label = 'Scan a lanyard QR' }: { onResult: (text: string) => void; label?: string }) {
|
||||
export function Scanner({ onResult, label = 'Scan a lanyard QR', entryLabel = 'QR code', placeholder = '…or type the code (e.g. CVV-XXX-NNNN)', submitLabel = 'Go', disabled = false, submitDisabled = false, onEntryChange }: { onResult: (text: string) => void; label?: string; entryLabel?: string; placeholder?: string; submitLabel?: string; disabled?: boolean; submitDisabled?: boolean; onEntryChange?: (text: string) => void }) {
|
||||
const [manual, setManual] = useState('');
|
||||
const [camError, setCamError] = useState<string | null>(null);
|
||||
const scannerRef = useRef<Html5Qrcode | null>(null);
|
||||
@@ -162,13 +162,17 @@ export function Scanner({ onResult, label = 'Scan a lanyard QR' }: { onResult: (
|
||||
<div className="row" style={{ gap: 8 }}>
|
||||
<input
|
||||
className="input mono"
|
||||
type="text"
|
||||
data-testid="scanner-manual-code"
|
||||
placeholder="…or type the code (e.g. CVV-XXX-NNNN)"
|
||||
aria-label={entryLabel}
|
||||
placeholder={placeholder}
|
||||
disabled={disabled}
|
||||
value={manual}
|
||||
onChange={(e) => setManual(e.target.value)}
|
||||
onChange={(e) => { setManual(e.target.value); onEntryChange?.(e.target.value); }}
|
||||
onKeyDown={(e) => { if (e.key === 'Enter' && manual.trim() && !disabled && !submitDisabled) onResult(manual.trim()); }}
|
||||
/>
|
||||
<button className="btn primary small" data-testid="scanner-manual-go" disabled={!manual.trim()} onClick={() => onResult(manual.trim())}>
|
||||
Go
|
||||
<button className="btn primary small" data-testid="scanner-manual-go" disabled={disabled || submitDisabled || !manual.trim()} onClick={() => onResult(manual.trim())}>
|
||||
{submitLabel}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { createContext, useCallback, useContext, useEffect, useMemo, useState, type ReactNode } from 'react';
|
||||
import type { Session as SbSession, User } from '@supabase/supabase-js';
|
||||
import { supabase } from '../lib/supabase';
|
||||
import { getMyContact, getMyRegistration } from '../lib/api';
|
||||
import { adminCallbackPending, consumeAdminCallback, hasAdminCallback, invalidAdminLink, loadEntryProfile, type EntryProfile } from '../lib/adminEntry';
|
||||
import type { Contact, Registration } from '../lib/types';
|
||||
|
||||
interface AuthContextValue {
|
||||
@@ -10,6 +10,7 @@ interface AuthContextValue {
|
||||
contact: Contact | null;
|
||||
registration: Registration | null;
|
||||
loading: boolean;
|
||||
authError: string | null;
|
||||
refresh: () => Promise<void>;
|
||||
signOut: () => Promise<void>;
|
||||
}
|
||||
@@ -21,42 +22,66 @@ export function AuthProvider({ children }: { children: ReactNode }) {
|
||||
const [contact, setContact] = useState<Contact | null>(null);
|
||||
const [registration, setRegistration] = useState<Registration | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [authError, setAuthError] = useState<string | null>(null);
|
||||
|
||||
const load = useCallback(async (email: string) => {
|
||||
try {
|
||||
const [c, r] = await Promise.all([getMyContact(email), getMyRegistration(email)]);
|
||||
setContact(c);
|
||||
setRegistration(r);
|
||||
} catch (e) {
|
||||
console.error('Failed to load contact', e);
|
||||
}
|
||||
const applyProfile = useCallback((profile: EntryProfile) => {
|
||||
setSession(profile.session);
|
||||
setContact(profile.contact);
|
||||
setRegistration(profile.registration);
|
||||
setAuthError(profile.error);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
let active = true;
|
||||
supabase.auth.getSession().then(({ data }) => {
|
||||
if (!active) return;
|
||||
setSession(data.session);
|
||||
if (data.session?.user?.email) void load(data.session.user.email);
|
||||
setLoading(false);
|
||||
});
|
||||
const { data: sub } = supabase.auth.onAuthStateChange((_event, newSession) => {
|
||||
setSession(newSession);
|
||||
if (newSession?.user?.email) void load(newSession.user.email);
|
||||
else {
|
||||
setContact(null);
|
||||
setRegistration(null);
|
||||
let revision = 0;
|
||||
const emptyProfile: EntryProfile = { session: null, contact: null, registration: null, error: null };
|
||||
|
||||
async function restore(next: SbSession | null, currentRevision: number) {
|
||||
try {
|
||||
const profile = next ? await loadEntryProfile(next) : emptyProfile;
|
||||
if (active && revision === currentRevision) applyProfile(profile);
|
||||
} catch {
|
||||
if (!active || revision !== currentRevision) return;
|
||||
applyProfile({ ...emptyProfile, error: invalidAdminLink });
|
||||
await supabase.auth.signOut({ scope: 'local' });
|
||||
} finally {
|
||||
if (active && revision === currentRevision) setLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function init() {
|
||||
if (hasAdminCallback) {
|
||||
const profile = await consumeAdminCallback();
|
||||
if (active) { applyProfile(profile); setLoading(false); }
|
||||
return;
|
||||
}
|
||||
const currentRevision = revision;
|
||||
const { data } = await supabase.auth.getSession();
|
||||
if (active && revision === currentRevision) await restore(data.session, currentRevision);
|
||||
}
|
||||
void init().catch(() => { if (active) { setAuthError(invalidAdminLink); setLoading(false); } });
|
||||
const { data: sub } = supabase.auth.onAuthStateChange((event, newSession) => {
|
||||
if (!active || adminCallbackPending || event === 'INITIAL_SESSION') return;
|
||||
const currentRevision = ++revision;
|
||||
if (!newSession) {
|
||||
applyProfile(emptyProfile);
|
||||
setLoading(false);
|
||||
return;
|
||||
}
|
||||
setLoading(true);
|
||||
window.setTimeout(() => {
|
||||
if (active && revision === currentRevision) void restore(newSession, currentRevision);
|
||||
}, 0);
|
||||
});
|
||||
return () => {
|
||||
active = false;
|
||||
sub.subscription.unsubscribe();
|
||||
};
|
||||
}, [load]);
|
||||
}, [applyProfile]);
|
||||
|
||||
const refresh = useCallback(async () => {
|
||||
if (session?.user?.email) await load(session.user.email);
|
||||
}, [session, load]);
|
||||
if (session) applyProfile(await loadEntryProfile(session));
|
||||
}, [session, applyProfile]);
|
||||
|
||||
const signOut = useCallback(async () => {
|
||||
await supabase.auth.signOut();
|
||||
@@ -65,8 +90,8 @@ export function AuthProvider({ children }: { children: ReactNode }) {
|
||||
}, []);
|
||||
|
||||
const value = useMemo<AuthContextValue>(
|
||||
() => ({ session, user: session?.user ?? null, contact, registration, loading, refresh, signOut }),
|
||||
[session, contact, registration, loading, refresh, signOut],
|
||||
() => ({ session, user: session?.user ?? null, contact, registration, loading, authError, refresh, signOut }),
|
||||
[session, contact, registration, loading, authError, refresh, signOut],
|
||||
);
|
||||
|
||||
return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
import type { Session } from '@supabase/supabase-js';
|
||||
import { supabase } from './supabase';
|
||||
import { getMyContact, getMyRegistration } from './api';
|
||||
import type { Contact, Registration } from './types';
|
||||
|
||||
export const invalidAdminLink = 'This sign-in link is invalid or expired. Please request a new link.';
|
||||
export const adminLinkNotice = 'If this email belongs to an eligible admin account, a sign-in link has been sent.';
|
||||
export const adminLinkFailure = 'Unable to send a sign-in link right now. Please try again later.';
|
||||
|
||||
export function isEmailEntry(value: string): boolean {
|
||||
return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value.trim());
|
||||
}
|
||||
|
||||
export async function requestAdminLink(email: string): Promise<void> {
|
||||
const normalizedEmail = email.trim().toLowerCase();
|
||||
const { data: eligible, error: eligibilityError } = await supabase.rpc('can_request_admin_magic_link', { p_email: normalizedEmail });
|
||||
if (eligibilityError) throw new Error(adminLinkFailure);
|
||||
if (eligible !== true) return;
|
||||
const { error } = await supabase.auth.signInWithOtp({
|
||||
email: normalizedEmail,
|
||||
options: { shouldCreateUser: false, emailRedirectTo: `${window.location.origin}/auth/callback` },
|
||||
});
|
||||
if (error && error.status !== 400 && error.status !== 422) throw new Error(adminLinkFailure);
|
||||
}
|
||||
|
||||
const entryUrl = new URL(window.location.href);
|
||||
const entryHash = new URLSearchParams(entryUrl.hash.slice(1));
|
||||
export const hasAdminCallback = entryUrl.pathname === '/auth/callback' ||
|
||||
(entryUrl.pathname === '/' && ['access_token', 'refresh_token', 'error', 'error_code'].some((key) => entryHash.has(key))) ||
|
||||
(entryUrl.pathname === '/' && ['code', 'error', 'error_code'].some((key) => entryUrl.searchParams.has(key)));
|
||||
if (hasAdminCallback) window.history.replaceState(null, '', '/');
|
||||
export let adminCallbackPending = hasAdminCallback;
|
||||
|
||||
export interface EntryProfile {
|
||||
session: Session | null;
|
||||
contact: Contact | null;
|
||||
registration: Registration | null;
|
||||
error: string | null;
|
||||
}
|
||||
|
||||
export async function loadEntryProfile(session: Session, adminOnly = false): Promise<EntryProfile> {
|
||||
const { data: verified, error: userError } = await supabase.auth.getUser(session.access_token);
|
||||
if (userError || !verified.user?.email || verified.user.id !== session.user.id) throw new Error(invalidAdminLink);
|
||||
const { data: isAdmin, error: adminError } = await supabase.rpc('is_admin');
|
||||
if (adminError) throw new Error(invalidAdminLink);
|
||||
if (adminOnly && isAdmin !== true) throw new Error('This account is not an admin.');
|
||||
const [contact, registration] = await Promise.all([
|
||||
getMyContact(verified.user.email), getMyRegistration(verified.user.email),
|
||||
]);
|
||||
if (!contact) throw new Error(invalidAdminLink);
|
||||
return { session: { ...session, user: verified.user }, contact: { ...contact, is_admin: isAdmin === true }, registration, error: null };
|
||||
}
|
||||
|
||||
let callbackResult: Promise<EntryProfile> | null = null;
|
||||
|
||||
export function consumeAdminCallback(): Promise<EntryProfile> {
|
||||
if (!callbackResult) callbackResult = (async () => {
|
||||
try {
|
||||
if (['error', 'error_code'].some((key) => entryHash.has(key) || entryUrl.searchParams.has(key))) throw new Error(invalidAdminLink);
|
||||
const accessToken = entryHash.get('access_token');
|
||||
const refreshToken = entryHash.get('refresh_token');
|
||||
const code = entryUrl.searchParams.get('code');
|
||||
const result = accessToken && refreshToken
|
||||
? await supabase.auth.setSession({ access_token: accessToken, refresh_token: refreshToken })
|
||||
: code && !accessToken && !refreshToken ? await supabase.auth.exchangeCodeForSession(code) : null;
|
||||
if (!result || result.error || !result.data.session) throw new Error(invalidAdminLink);
|
||||
return await loadEntryProfile(result.data.session, true);
|
||||
} catch (failure) {
|
||||
await supabase.auth.signOut({ scope: 'local' }).catch(() => {});
|
||||
return { session: null, contact: null, registration: null, error: failure instanceof Error && failure.message === 'This account is not an admin.' ? failure.message : invalidAdminLink };
|
||||
} finally {
|
||||
adminCallbackPending = false;
|
||||
}
|
||||
})();
|
||||
return callbackResult;
|
||||
}
|
||||
@@ -106,7 +106,9 @@ export async function getMyContact(email: string): Promise<Contact | null> {
|
||||
|
||||
/** The signed-in contact's registration for the active event. */
|
||||
export async function getMyRegistration(email: string): Promise<Registration | null> {
|
||||
const { data, error } = await supabase.from('registrations').select('*').eq('contact_email', email).maybeSingle();
|
||||
const event = await getActiveEvent();
|
||||
if (!event) return null;
|
||||
const { data, error } = await supabase.from('registrations').select('*').eq('contact_email', email).eq('event_id', event.id).maybeSingle();
|
||||
if (error) throw new ApiError(error.message);
|
||||
return (data as Registration) ?? null;
|
||||
}
|
||||
|
||||
@@ -1,29 +1,64 @@
|
||||
import { useState } from 'react';
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { supabase } from '../lib/supabase';
|
||||
import { lanyardLookup } from '../lib/api';
|
||||
import { capWords } from '../lib/time';
|
||||
import type { PublicContact } from '../lib/types';
|
||||
import { Avatar, Scanner } from '../components/ui';
|
||||
import { useToast } from '../context/ToastContext';
|
||||
import { useAuth } from '../context/AuthContext';
|
||||
import { adminLinkFailure, adminLinkNotice, isEmailEntry, requestAdminLink } from '../lib/adminEntry';
|
||||
|
||||
type Step = 'splash' | 'scan' | 'confirm';
|
||||
|
||||
export function Login() {
|
||||
const [step, setStep] = useState<Step>('splash');
|
||||
const { authError } = useAuth();
|
||||
const [step, setStep] = useState<Step>(authError ? 'scan' : 'splash');
|
||||
const [qrToken, setQrToken] = useState('');
|
||||
const [found, setFound] = useState<PublicContact | null>(null);
|
||||
const [email, setEmail] = useState('');
|
||||
const [staffPassword, setStaffPassword] = useState('');
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [error, setError] = useState<string | null>(authError);
|
||||
const [entry, setEntry] = useState('');
|
||||
const [sent, setSent] = useState(false);
|
||||
const [cooldown, setCooldown] = useState(0);
|
||||
const requestPending = useRef(false);
|
||||
const { toast } = useToast();
|
||||
|
||||
useEffect(() => {
|
||||
if (!cooldown) return;
|
||||
const timer = window.setTimeout(() => setCooldown((remaining) => remaining - 1), 1000);
|
||||
return () => window.clearTimeout(timer);
|
||||
}, [cooldown]);
|
||||
|
||||
// Staff log in with QR + their admin password; everyone else with QR + email.
|
||||
const isStaff = found?.registration_type === 'staff';
|
||||
|
||||
async function handleScan(text: string) {
|
||||
const token = text.trim();
|
||||
if (!token) return;
|
||||
if (!token || requestPending.current) return;
|
||||
if (isEmailEntry(token)) {
|
||||
if (cooldown) return;
|
||||
requestPending.current = true;
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
setSent(false);
|
||||
try {
|
||||
await requestAdminLink(token);
|
||||
setSent(true);
|
||||
setCooldown(60);
|
||||
} catch {
|
||||
setError(adminLinkFailure);
|
||||
} finally {
|
||||
requestPending.current = false;
|
||||
setBusy(false);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (token.includes('@')) {
|
||||
setError('Enter a valid email address.');
|
||||
return;
|
||||
}
|
||||
setQrToken(token);
|
||||
setError(null);
|
||||
try {
|
||||
@@ -41,7 +76,7 @@ export function Login() {
|
||||
// Attendees: QR + the ticket email (the QR token is the auth password).
|
||||
const loginEmail = isStaff ? found?.email : email.trim();
|
||||
const loginPassword = isStaff ? staffPassword : qrToken;
|
||||
if (!loginEmail || !loginPassword) return;
|
||||
if (!loginEmail || !loginPassword || busy) return;
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
try {
|
||||
@@ -81,8 +116,18 @@ export function Login() {
|
||||
return (
|
||||
<section className="screen no-tab">
|
||||
<div className="h1">Welcome back 👋</div>
|
||||
<div className="muted small">Scan the QR code on your lanyard to log in.</div>
|
||||
<Scanner onResult={handleScan} label="Point your camera at your lanyard QR" />
|
||||
<Scanner
|
||||
onResult={handleScan}
|
||||
label="Point your camera at your lanyard QR"
|
||||
entryLabel="QR code or admin email"
|
||||
placeholder="QR code or admin email"
|
||||
disabled={busy}
|
||||
submitDisabled={isEmailEntry(entry) && cooldown > 0}
|
||||
submitLabel={busy ? 'Sending...' : isEmailEntry(entry) ? cooldown ? `Resend in ${cooldown}s` : sent ? 'Resend magic link' : 'Send magic link' : 'Go'}
|
||||
onEntryChange={(value) => { setEntry(value); setSent(false); setError(null); }}
|
||||
/>
|
||||
{sent && <p role="status">{adminLinkNotice}</p>}
|
||||
{error && <p role="alert" data-testid="login-error">{error}</p>}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -139,7 +184,7 @@ export function Login() {
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
{error && <div className="muted small" data-testid="login-error" style={{ color: 'var(--red)' }}>{error}</div>}
|
||||
{error && <div role="alert" className="muted small" data-testid="login-error" style={{ color: 'var(--red)' }}>{error}</div>}
|
||||
<button
|
||||
className="btn primary"
|
||||
data-testid="login-confirm"
|
||||
|
||||
@@ -11,7 +11,7 @@ export default defineConfig({
|
||||
host: true,
|
||||
port: 3000,
|
||||
proxy: {
|
||||
'/auth': { target: SUPABASE_TARGET, changeOrigin: true },
|
||||
'/auth/v1': { target: SUPABASE_TARGET, changeOrigin: true },
|
||||
'/rest': { target: SUPABASE_TARGET, changeOrigin: true },
|
||||
'/realtime': { target: SUPABASE_TARGET, changeOrigin: true, ws: true },
|
||||
'/storage': { target: SUPABASE_TARGET, changeOrigin: true },
|
||||
|
||||
Reference in new issue
Block a user