feat: add magic-link admin login and speaker materials portal
This commit is contained in:
1 parent
3adc0fd58f
commit
8d8d3ae4b8
28 files changed
+1623
-232
No files matched your search
@@ -25,6 +25,12 @@ server {
|
||||
try_files $uri $uri/ /index.html;
|
||||
}
|
||||
|
||||
location = /auth/callback {
|
||||
add_header Cache-Control "no-store";
|
||||
add_header Referrer-Policy "no-referrer";
|
||||
try_files /index.html =404;
|
||||
}
|
||||
|
||||
# Long-cache immutable build assets.
|
||||
location /assets/ {
|
||||
expires 30d;
|
||||
|
||||
+3
-96
@@ -1,6 +1,6 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useState } from 'react';
|
||||
import { AuthProvider, useAuth } from './context/AuthContext';
|
||||
import { ToastProvider, useToast } from './context/ToastContext';
|
||||
import { ToastProvider } from './context/ToastContext';
|
||||
import { Login } from './screens/Login';
|
||||
import { Dashboard } from './views/Dashboard';
|
||||
import { Contacts } from './views/Contacts';
|
||||
@@ -11,8 +11,7 @@ import { Activity } from './views/Activity';
|
||||
import { Events } from './views/Events';
|
||||
import { Interfaces } from './views/Interfaces';
|
||||
import { Reports } from './views/Reports';
|
||||
import { Spinner, Modal } from './components/ui';
|
||||
import { DEFAULT_ADMIN_PASSWORD } from './lib/api';
|
||||
import { Spinner } from './components/ui';
|
||||
|
||||
export type View =
|
||||
| 'dashboard'
|
||||
@@ -37,97 +36,6 @@ const NAV: { id: View; label: string; ico: string }[] = [
|
||||
{ id: 'reports', label: 'Reports', ico: '📤' },
|
||||
];
|
||||
|
||||
/**
|
||||
* Shown once per session when an admin signs in with the default password
|
||||
* (`appe-admin-2026`). Prompts them to set a personal password. Dismissable
|
||||
* ("Not now"); the prompt re-appears on the next sign-in while the default is
|
||||
* in use.
|
||||
*/
|
||||
function ChangePasswordPrompt() {
|
||||
const { contact, changePassword } = useAuth();
|
||||
const { push } = useToast();
|
||||
const [open, setOpen] = useState(false);
|
||||
const [newPassword, setNewPassword] = useState('');
|
||||
const [confirmPassword, setConfirmPassword] = useState('');
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
// Open the prompt when the signed-in admin is using the default password.
|
||||
useEffect(() => {
|
||||
if (contact && contact.password === DEFAULT_ADMIN_PASSWORD) setOpen(true);
|
||||
}, [contact]);
|
||||
|
||||
async function onSubmit() {
|
||||
if (newPassword.length < 6) {
|
||||
setError('Password must be at least 6 characters.');
|
||||
return;
|
||||
}
|
||||
if (newPassword !== confirmPassword) {
|
||||
setError('Passwords do not match.');
|
||||
return;
|
||||
}
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
try {
|
||||
await changePassword(newPassword);
|
||||
push('success', 'Password updated');
|
||||
setOpen(false);
|
||||
setNewPassword('');
|
||||
setConfirmPassword('');
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Failed to change password');
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Modal
|
||||
open={open}
|
||||
onClose={() => setOpen(false)}
|
||||
title="Change your password"
|
||||
footer={
|
||||
<>
|
||||
<button className="btn ghost" onClick={() => setOpen(false)}>
|
||||
Not now
|
||||
</button>
|
||||
<button className="btn primary" onClick={onSubmit} disabled={busy}>
|
||||
{busy ? 'Saving…' : 'Save password'}
|
||||
</button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<p style={{ margin: 0, fontSize: 13.5, color: 'var(--muted)' }}>
|
||||
You signed in with the default admin password. Set a personal password
|
||||
so only you can access this account.
|
||||
</p>
|
||||
<div className="field">
|
||||
<label>New password</label>
|
||||
<input
|
||||
className="input"
|
||||
type="password"
|
||||
placeholder="••••••••••"
|
||||
value={newPassword}
|
||||
onChange={(e) => setNewPassword(e.target.value)}
|
||||
autoComplete="new-password"
|
||||
/>
|
||||
</div>
|
||||
<div className="field">
|
||||
<label>Confirm new password</label>
|
||||
<input
|
||||
className="input"
|
||||
type="password"
|
||||
placeholder="••••••••••"
|
||||
value={confirmPassword}
|
||||
onChange={(e) => setConfirmPassword(e.target.value)}
|
||||
autoComplete="new-password"
|
||||
/>
|
||||
</div>
|
||||
{error && <div className="login-err">{error}</div>}
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
|
||||
function Shell() {
|
||||
const { contact, loading, signOut } = useAuth();
|
||||
const [view, setView] = useState<View>('dashboard');
|
||||
@@ -144,7 +52,6 @@ function Shell() {
|
||||
|
||||
return (
|
||||
<div className="app">
|
||||
<ChangePasswordPrompt />
|
||||
<aside className="sidebar">
|
||||
<div className="brand">
|
||||
<div className="logo"><img src="/icon-192.png" alt="APPE" /></div>
|
||||
|
||||
@@ -1,16 +1,12 @@
|
||||
import { createContext, useContext, useEffect, useState, type ReactNode } from 'react';
|
||||
import { supabase } from '../lib/supabase';
|
||||
import { changeMyPassword } from '../lib/api';
|
||||
import type { Contact } from '../lib/types';
|
||||
|
||||
interface AuthState {
|
||||
contact: Contact | null;
|
||||
loading: boolean;
|
||||
/** Sign in with the admin's email + password (event-independent). */
|
||||
signIn: (email: string, password: string) => Promise<void>;
|
||||
authError: string | null;
|
||||
signOut: () => Promise<void>;
|
||||
/** Change the current admin's own login password (re-authenticates). */
|
||||
changePassword: (newPassword: string) => Promise<void>;
|
||||
}
|
||||
|
||||
const AuthContext = createContext<AuthState | null>(null);
|
||||
@@ -33,24 +29,71 @@ async function loadAdminContact(email: string): Promise<Contact | null> {
|
||||
return isAdminContact(c) ? c : null;
|
||||
}
|
||||
|
||||
const callbackUrl = window.location.pathname === '/auth/callback' ? new URL(window.location.href) : null;
|
||||
if (callbackUrl) window.history.replaceState(null, '', '/');
|
||||
let callbackPending = !!callbackUrl;
|
||||
let callbackResult: Promise<{ contact: Contact | null; error: string | null }> | null = null;
|
||||
|
||||
function consumeCallback() {
|
||||
if (!callbackResult) callbackResult = (async () => {
|
||||
const invalidLink = 'This sign-in link is invalid or expired. Please request a new link.';
|
||||
try {
|
||||
const hash = new URLSearchParams(callbackUrl!.hash.slice(1));
|
||||
const query = callbackUrl!.searchParams;
|
||||
if (hash.has('error') || hash.has('error_code') || query.has('error') || query.has('error_code')) {
|
||||
throw new Error(invalidLink);
|
||||
}
|
||||
const accessToken = hash.get('access_token');
|
||||
const refreshToken = hash.get('refresh_token');
|
||||
const code = query.get('code');
|
||||
const result = accessToken && refreshToken
|
||||
? await supabase.auth.setSession({ access_token: accessToken, refresh_token: refreshToken })
|
||||
: code ? await supabase.auth.exchangeCodeForSession(code) : null;
|
||||
if (!result || result.error || !result.data.session?.user.email) throw new Error(invalidLink);
|
||||
const admin = await loadAdminContact(result.data.session.user.email);
|
||||
if (!admin) throw new Error('This account is not an admin.');
|
||||
return { contact: admin, error: null };
|
||||
} catch (error) {
|
||||
await supabase.auth.signOut({ scope: 'local' });
|
||||
return { contact: null, error: error instanceof Error && error.message === 'This account is not an admin.' ? error.message : invalidLink };
|
||||
} finally {
|
||||
callbackPending = false;
|
||||
}
|
||||
})();
|
||||
return callbackResult;
|
||||
}
|
||||
|
||||
export function AuthProvider({ children }: { children: ReactNode }) {
|
||||
const [contact, setContact] = useState<Contact | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [authError, setAuthError] = useState<string | null>(null);
|
||||
|
||||
// On mount: restore any existing session and load the contact. If the
|
||||
// session belongs to a non-admin, sign out immediately (admin-only app).
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
let revision = 0;
|
||||
|
||||
async function init() {
|
||||
if (callbackUrl) {
|
||||
const result = await consumeCallback();
|
||||
if (!cancelled) {
|
||||
setContact(result.contact);
|
||||
setAuthError(result.error);
|
||||
setLoading(false);
|
||||
}
|
||||
return;
|
||||
}
|
||||
const currentRevision = revision;
|
||||
const { data } = await supabase.auth.getSession();
|
||||
if (cancelled || currentRevision !== revision) return;
|
||||
const session = data.session;
|
||||
if (!session) {
|
||||
if (!cancelled) setLoading(false);
|
||||
return;
|
||||
}
|
||||
const c = session.user.email ? await loadAdminContact(session.user.email) : null;
|
||||
if (cancelled) return;
|
||||
if (cancelled || currentRevision !== revision) return;
|
||||
if (c) {
|
||||
setContact(c);
|
||||
} else {
|
||||
@@ -62,18 +105,28 @@ export function AuthProvider({ children }: { children: ReactNode }) {
|
||||
|
||||
init();
|
||||
|
||||
const { data: sub } = supabase.auth.onAuthStateChange(async (_event, session) => {
|
||||
const { data: sub } = supabase.auth.onAuthStateChange((event, session) => {
|
||||
if (cancelled || callbackPending || event === 'INITIAL_SESSION') return;
|
||||
const currentRevision = ++revision;
|
||||
if (!session) {
|
||||
setContact(null);
|
||||
setLoading(false);
|
||||
return;
|
||||
}
|
||||
const c = session.user.email ? await loadAdminContact(session.user.email) : null;
|
||||
if (c) {
|
||||
setContact(c);
|
||||
} else {
|
||||
await supabase.auth.signOut();
|
||||
setContact(null);
|
||||
}
|
||||
window.setTimeout(() => {
|
||||
void (async () => {
|
||||
if (cancelled || currentRevision !== revision) return;
|
||||
const c = session.user.email ? await loadAdminContact(session.user.email) : null;
|
||||
if (cancelled || currentRevision !== revision) return;
|
||||
if (c) {
|
||||
setContact(c);
|
||||
} else {
|
||||
setContact(null);
|
||||
await supabase.auth.signOut();
|
||||
}
|
||||
if (!cancelled) setLoading(false);
|
||||
})();
|
||||
}, 0);
|
||||
});
|
||||
|
||||
return () => {
|
||||
@@ -82,37 +135,13 @@ export function AuthProvider({ children }: { children: ReactNode }) {
|
||||
};
|
||||
}, []);
|
||||
|
||||
async function signIn(email: string, password: string) {
|
||||
const { data, error } = await supabase.auth.signInWithPassword({
|
||||
email,
|
||||
password,
|
||||
});
|
||||
if (error) throw new Error(error.message);
|
||||
|
||||
const c = data.user.email ? await loadAdminContact(data.user.email) : null;
|
||||
if (!c) {
|
||||
// Signed in, but not an admin — reject and sign out.
|
||||
await supabase.auth.signOut();
|
||||
throw new Error('This account is not an admin.');
|
||||
}
|
||||
setContact(c);
|
||||
}
|
||||
|
||||
async function signOut() {
|
||||
await supabase.auth.signOut();
|
||||
setContact(null);
|
||||
}
|
||||
|
||||
async function changePassword(newPassword: string) {
|
||||
if (!contact) throw new Error('Not signed in');
|
||||
await changeMyPassword(contact.email, newPassword);
|
||||
// Re-load the contact so the (now changed) password is reflected.
|
||||
const c = await loadAdminContact(contact.email);
|
||||
if (c) setContact(c);
|
||||
}
|
||||
|
||||
return (
|
||||
<AuthContext.Provider value={{ contact, loading, signIn, signOut, changePassword }}>
|
||||
<AuthContext.Provider value={{ contact, loading, authError, signOut }}>
|
||||
{children}
|
||||
</AuthContext.Provider>
|
||||
);
|
||||
|
||||
@@ -1,23 +1,48 @@
|
||||
import { useState, type FormEvent } from 'react';
|
||||
import { useEffect, useState, type FormEvent } from 'react';
|
||||
import { useAuth } from '../context/AuthContext';
|
||||
import { useToast } from '../context/ToastContext';
|
||||
import { supabase } from '../lib/supabase';
|
||||
|
||||
export function Login() {
|
||||
const { signIn } = useAuth();
|
||||
const { authError } = useAuth();
|
||||
const { push } = useToast();
|
||||
const [email, setEmail] = useState('');
|
||||
const [password, setPassword] = useState('');
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [error, setError] = useState<string | null>(authError);
|
||||
const [sent, setSent] = useState(false);
|
||||
const [cooldown, setCooldown] = useState(0);
|
||||
const [resendAt, setResendAt] = useState(0);
|
||||
|
||||
useEffect(() => {
|
||||
if (!resendAt) return;
|
||||
const timer = window.setInterval(() => {
|
||||
const remaining = Math.max(0, Math.ceil((resendAt - Date.now()) / 1000));
|
||||
setCooldown(remaining);
|
||||
if (!remaining) window.clearInterval(timer);
|
||||
}, 1000);
|
||||
return () => window.clearInterval(timer);
|
||||
}, [resendAt]);
|
||||
|
||||
async function onSubmit(e: FormEvent) {
|
||||
e.preventDefault();
|
||||
if (!email.trim() || !password.trim()) return;
|
||||
if (busy || !email.trim() || cooldown) return;
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
try {
|
||||
await signIn(email.trim(), password);
|
||||
push('success', 'Welcome back');
|
||||
setSent(false);
|
||||
const { error: sendError } = await supabase.auth.signInWithOtp({
|
||||
email: email.trim(),
|
||||
options: {
|
||||
shouldCreateUser: false,
|
||||
emailRedirectTo: new URL('/auth/callback', window.location.origin).href,
|
||||
},
|
||||
});
|
||||
if (sendError && (sendError.status === 429 || !sendError.status || sendError.status >= 500)) {
|
||||
throw new Error('Unable to send a sign-in link right now. Please try again later.');
|
||||
}
|
||||
setSent(true);
|
||||
setCooldown(60);
|
||||
setResendAt(Date.now() + 60_000);
|
||||
} catch (err) {
|
||||
const msg = err instanceof Error ? err.message : 'Sign in failed';
|
||||
setError(msg);
|
||||
@@ -34,37 +59,28 @@ export function Login() {
|
||||
<div className="logo"><img src="/icon-192.png" alt="APPE" /></div>
|
||||
<div>
|
||||
<h1>APPE Admin</h1>
|
||||
<p>Sign in with your admin email and password.</p>
|
||||
<p>Sign in to your admin account.</p>
|
||||
</div>
|
||||
</div>
|
||||
<form className="login-form" onSubmit={onSubmit}>
|
||||
<div className="field">
|
||||
<label>Email</label>
|
||||
<label htmlFor="login-email">Email</label>
|
||||
<input
|
||||
id="login-email"
|
||||
className="input"
|
||||
type="email"
|
||||
placeholder="[email protected]"
|
||||
value={email}
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
onChange={(e) => { setEmail(e.target.value); setSent(false); }}
|
||||
autoComplete="username"
|
||||
disabled={busy}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div className="field">
|
||||
<label>Password</label>
|
||||
<input
|
||||
className="input"
|
||||
type="password"
|
||||
placeholder="••••••••••"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
autoComplete="current-password"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
{error && <div className="login-err">{error}</div>}
|
||||
<button className="btn primary" type="submit" disabled={busy}>
|
||||
{busy ? 'Signing in…' : 'Sign in'}
|
||||
{sent && <div role="status">If this email belongs to an eligible account, a sign-in link has been sent.</div>}
|
||||
{error && <div className="login-err" role="alert">{error}</div>}
|
||||
<button className="btn primary" type="submit" disabled={busy || cooldown > 0}>
|
||||
{busy ? 'Sending...' : cooldown ? `Resend in ${cooldown}s` : sent ? 'Resend magic link' : 'Send magic link'}
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
@@ -11,7 +11,7 @@ export default defineConfig({
|
||||
host: true,
|
||||
port: 3001,
|
||||
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 },
|
||||
|
||||
@@ -13,6 +13,8 @@ import { EventFeedback } from './screens/EventFeedback';
|
||||
import { QrImage, Spinner } from './components/ui';
|
||||
import { getMyConnections } from './lib/api';
|
||||
import { usePolling } from './lib/usePolling';
|
||||
import { isSpeakerPortal } from './lib/speakerPortal';
|
||||
import { SpeakerPortal } from './screens/SpeakerPortal';
|
||||
|
||||
type Tab = 'home' | 'agenda' | 'scan' | 'connections' | 'profile' | 'leaderboard';
|
||||
const TABS: { id: Tab; ico: string; label: string }[] = [
|
||||
@@ -186,6 +188,7 @@ function Shell() {
|
||||
}
|
||||
|
||||
export default function App() {
|
||||
if (isSpeakerPortal) return <SpeakerPortal />;
|
||||
return (
|
||||
<ToastProvider>
|
||||
<AuthProvider>
|
||||
|
||||
@@ -232,14 +232,23 @@ export async function getMySpeakerSessions(email: string): Promise<string[]> {
|
||||
* The path is persisted via the `set_session_material` RPC (the sessions table
|
||||
* is admin-write only, so speakers need the security-definer RPC). */
|
||||
export async function uploadSessionMaterial(sessionId: string, file: File): Promise<string> {
|
||||
const path = `sessions/${sessionId}/${Date.now()}-${file.name.replace(/[^a-zA-Z0-9._-]/g, '_')}`;
|
||||
const { error: upErr } = await supabase.storage.from('materials').upload(path, file, { upsert: true });
|
||||
const { data: previous, error: readError } = await supabase.from('sessions').select('material_path').eq('id', sessionId).single();
|
||||
if (readError) throw new ApiError(readError.message);
|
||||
const path = `sessions/${sessionId}/${crypto.randomUUID()}-${file.name.replace(/[^a-zA-Z0-9._-]/g, '_')}`;
|
||||
const { error: upErr } = await supabase.storage.from('materials').upload(path, file, { upsert: false });
|
||||
if (upErr) throw new ApiError(upErr.message);
|
||||
const { error: dbErr } = await supabase.rpc('set_session_material', {
|
||||
p_session_id: sessionId,
|
||||
p_material_path: path,
|
||||
});
|
||||
if (dbErr) throw new ApiError(dbErr.message);
|
||||
if (dbErr) {
|
||||
const { error: cleanupError } = await supabase.storage.from('materials').remove([path]);
|
||||
throw new ApiError(`${dbErr.message}${cleanupError ? ' The unattached upload could not be cleaned up.' : ''}`);
|
||||
}
|
||||
if (previous.material_path && previous.material_path !== path) {
|
||||
const { error: cleanupError } = await supabase.storage.from('materials').remove([previous.material_path]);
|
||||
if (cleanupError) throw new ApiError('Material saved, but the previous file could not be removed. Refresh to see the saved material.');
|
||||
}
|
||||
return path;
|
||||
}
|
||||
|
||||
@@ -247,15 +256,16 @@ export async function uploadSessionMaterial(sessionId: string, file: File): Prom
|
||||
* can delete their own material to re-upload; the path is cleared via the
|
||||
* `set_session_material` RPC (sessions is admin-write only). */
|
||||
export async function removeSessionMaterial(sessionId: string): Promise<void> {
|
||||
const { data } = await supabase.from('sessions').select('material_path').eq('id', sessionId).maybeSingle();
|
||||
const { data, error: readError } = await supabase.from('sessions').select('material_path').eq('id', sessionId).single();
|
||||
if (readError) throw new ApiError(readError.message);
|
||||
const path = (data as Session | null)?.material_path;
|
||||
if (path) {
|
||||
const { error: rmErr } = await supabase.storage.from('materials').remove([path]);
|
||||
if (rmErr) throw new ApiError(rmErr.message);
|
||||
}
|
||||
const { error: dbErr } = await supabase.rpc('set_session_material', {
|
||||
p_session_id: sessionId,
|
||||
p_material_path: null,
|
||||
});
|
||||
if (dbErr) throw new ApiError(dbErr.message);
|
||||
if (path) {
|
||||
const { error: rmErr } = await supabase.storage.from('materials').remove([path]);
|
||||
if (rmErr) throw new ApiError('Material detached, but the file could not be removed from storage.');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
import type { Session } from '@supabase/supabase-js';
|
||||
import { supabase } from './supabase';
|
||||
|
||||
export const isSpeakerPortal = /^\/speaker(?:\/secret)?\/?$/.test(window.location.pathname);
|
||||
|
||||
export interface SpeakerSession {
|
||||
session_id: string;
|
||||
title: string;
|
||||
description: string | null;
|
||||
room: string | null;
|
||||
material_path: string | null;
|
||||
event_id: string;
|
||||
event_name: string;
|
||||
event_start_date: string;
|
||||
event_end_date: string;
|
||||
is_active: boolean;
|
||||
slot_date: string;
|
||||
start_time: string;
|
||||
end_time: string;
|
||||
}
|
||||
|
||||
async function consumeCallback(): Promise<Session | null> {
|
||||
const url = new URL(window.location.href);
|
||||
const hash = new URLSearchParams(url.hash.slice(1));
|
||||
const accessToken = hash.get('access_token');
|
||||
const refreshToken = hash.get('refresh_token');
|
||||
const code = url.searchParams.get('code');
|
||||
const callbackError = hash.get('error') || url.searchParams.get('error');
|
||||
const hasCallback = accessToken || refreshToken || code || callbackError;
|
||||
if (hasCallback) window.history.replaceState(null, '', window.location.pathname);
|
||||
if (callbackError) throw new Error('This sign-in link has expired or is invalid. Request a new link.');
|
||||
if (accessToken || refreshToken) {
|
||||
if (!accessToken || !refreshToken) throw new Error('Incomplete sign-in link. Request a new link.');
|
||||
const { data, error } = await supabase.auth.setSession({ access_token: accessToken, refresh_token: refreshToken });
|
||||
if (error) throw new Error('This sign-in link has expired or is invalid. Request a new link.');
|
||||
return data.session;
|
||||
}
|
||||
if (code) {
|
||||
const { data, error } = await supabase.auth.exchangeCodeForSession(code);
|
||||
if (error) throw new Error('This sign-in link could not be opened on this device. Request a new link.');
|
||||
return data.session;
|
||||
}
|
||||
const { data, error } = await supabase.auth.getSession();
|
||||
if (error) throw error;
|
||||
return data.session;
|
||||
}
|
||||
|
||||
export const speakerPortalSession = isSpeakerPortal
|
||||
? consumeCallback().then((session) => ({ session, error: null }), (error: Error) => ({ session: null, error }))
|
||||
: Promise.resolve({ session: null, error: null });
|
||||
|
||||
export async function getSpeakerPortalSessions(): Promise<SpeakerSession[]> {
|
||||
const { data, error } = await supabase.rpc('get_my_speaker_sessions');
|
||||
if (error) throw new Error(error.message);
|
||||
return data as SpeakerSession[];
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
import { useEffect, useState, type FormEvent } from 'react';
|
||||
import type { Session } from '@supabase/supabase-js';
|
||||
import { supabase } from '../lib/supabase';
|
||||
import { getSpeakerPortalSessions, speakerPortalSession, type SpeakerSession } from '../lib/speakerPortal';
|
||||
import { removeSessionMaterial, sessionMaterialUrl, uploadSessionMaterial } from '../lib/api';
|
||||
|
||||
const MAX_FILE_SIZE = 50 * 1024 * 1024;
|
||||
const FILE_TYPES = '.pdf,.ppt,.pptx,.odp,.zip,.txt';
|
||||
|
||||
function messageOf(error: unknown) {
|
||||
return error instanceof Error ? error.message : 'Something went wrong. Please try again.';
|
||||
}
|
||||
|
||||
export function SpeakerPortal() {
|
||||
const [session, setSession] = useState<Session | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [email, setEmail] = useState('');
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
const [notice, setNotice] = useState('');
|
||||
const [talks, setTalks] = useState<SpeakerSession[]>([]);
|
||||
const [talksLoading, setTalksLoading] = useState(false);
|
||||
const [talksError, setTalksError] = useState('');
|
||||
const [reload, setReload] = useState(0);
|
||||
const [workingTalk, setWorkingTalk] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
let active = true;
|
||||
setTalks([]);
|
||||
setTalksError('');
|
||||
if (!session) return;
|
||||
setTalksLoading(true);
|
||||
void getSpeakerPortalSessions().then((rows) => {
|
||||
if (active) setTalks(rows);
|
||||
}).catch((failure: unknown) => {
|
||||
if (active) setTalksError(messageOf(failure));
|
||||
}).finally(() => { if (active) setTalksLoading(false); });
|
||||
return () => { active = false; };
|
||||
}, [session?.user.id, reload]);
|
||||
|
||||
useEffect(() => {
|
||||
let active = true;
|
||||
void speakerPortalSession.then((result) => {
|
||||
if (!active) return;
|
||||
setSession(result.session);
|
||||
setError(result.error?.message || '');
|
||||
setLoading(false);
|
||||
});
|
||||
const { data } = supabase.auth.onAuthStateChange((_event, next) => {
|
||||
if (active) setSession(next);
|
||||
});
|
||||
return () => { active = false; data.subscription.unsubscribe(); };
|
||||
}, []);
|
||||
|
||||
async function sendLink(event: FormEvent) {
|
||||
event.preventDefault();
|
||||
setBusy(true);
|
||||
setError('');
|
||||
setNotice('');
|
||||
try {
|
||||
const { error: authError } = await supabase.auth.signInWithOtp({
|
||||
email: email.trim().toLowerCase(),
|
||||
options: { shouldCreateUser: false, emailRedirectTo: `${window.location.origin}/speaker/secret` },
|
||||
});
|
||||
if (authError) throw authError;
|
||||
setNotice('Sign-in link requested. Check your email.');
|
||||
} catch {
|
||||
setError('Unable to send a sign-in link. Check your registered email or try again later.');
|
||||
} finally { setBusy(false); }
|
||||
}
|
||||
|
||||
async function logout() {
|
||||
setBusy(true);
|
||||
const { error: authError } = await supabase.auth.signOut({ scope: 'local' });
|
||||
if (authError) setError(authError.message);
|
||||
else { setSession(null); setNotice(''); }
|
||||
setBusy(false);
|
||||
}
|
||||
|
||||
async function changeMaterial(talk: SpeakerSession, file?: File) {
|
||||
setError('');
|
||||
setNotice('');
|
||||
if (file && (!file.size || file.size > MAX_FILE_SIZE || !/\.(pdf|ppt|pptx|odp|zip|txt)$/i.test(file.name))) {
|
||||
setError('Choose a non-empty PDF, PowerPoint, ODP, ZIP or TXT file, up to 50 MB.');
|
||||
return;
|
||||
}
|
||||
if (!file && !window.confirm(`Remove materials for "${talk.title}"?`)) return;
|
||||
setWorkingTalk(talk.session_id);
|
||||
try {
|
||||
if (file) await uploadSessionMaterial(talk.session_id, file);
|
||||
else await removeSessionMaterial(talk.session_id);
|
||||
setNotice(file ? 'Material saved.' : 'Material removed.');
|
||||
} catch (failure) { setError(messageOf(failure)); }
|
||||
finally { setWorkingTalk(null); setReload((value) => value + 1); }
|
||||
}
|
||||
|
||||
return <div className="app speaker-app"><main className="screen no-tab speaker-portal" data-testid="speaker-portal">
|
||||
<header className="row between"><h1 className="h1">Speaker Portal</h1>
|
||||
{session && <button className="btn small ghost" onClick={() => void logout()} disabled={busy || !!workingTalk}>Sign out</button>}
|
||||
</header>
|
||||
{error && <p role="alert">{error}</p>}
|
||||
{notice && <p role="status">{notice}</p>}
|
||||
{loading ? <p role="status">Signing in...</p> : session ? <>
|
||||
<p className="small muted">{session.user.email}</p>
|
||||
<h2 className="h2">My Talk Materials</h2>
|
||||
{talksLoading ? <p role="status">Loading talks...</p> : talksError ? <>
|
||||
<p role="alert">{talksError}</p><button className="btn" onClick={() => setReload((value) => value + 1)}>Retry</button>
|
||||
</> : !talks.length ? <p role="status">No assigned talks for your speaker or staff registrations.</p> : talks.map((talk) => <article className="speaker-talk" key={talk.session_id} data-testid={`speaker-talk-${talk.session_id}`}>
|
||||
<p className="small muted">{talk.event_name} · {talk.is_active ? 'Active event' : 'Inactive event'}</p>
|
||||
<h3 className="h2">{talk.title}</h3>
|
||||
<p className="small">{talk.slot_date} · {talk.start_time.slice(0, 5)} - {talk.end_time.slice(0, 5)}{talk.room && ` · ${talk.room}`}</p>
|
||||
{talk.material_path ? <a className="speaker-download" href={sessionMaterialUrl(talk.material_path)} target="_blank" rel="noreferrer">Download material</a> : <p className="small muted">No material uploaded</p>}
|
||||
<label className="small" htmlFor={`material-${talk.session_id}`}>{talk.material_path ? 'Replace material' : 'Upload material'}</label>
|
||||
<input className="input" id={`material-${talk.session_id}`} aria-label={`${talk.material_path ? 'Replace' : 'Upload'} material for ${talk.title}`} type="file" accept={FILE_TYPES} disabled={!!workingTalk || busy} onChange={(event) => {
|
||||
const file = event.target.files?.[0];
|
||||
event.target.value = '';
|
||||
if (file) void changeMaterial(talk, file);
|
||||
}} />
|
||||
<p className="small muted">PDF, PowerPoint, ODP, ZIP, TXT · Max 50 MB</p>
|
||||
{workingTalk === talk.session_id && <><progress aria-label="Saving material" /><p role="status">Saving material...</p></>}
|
||||
{talk.material_path && <button className="btn small danger" disabled={!!workingTalk || busy} onClick={() => void changeMaterial(talk)}>Remove material</button>}
|
||||
</article>)}
|
||||
</> : <form onSubmit={(event) => void sendLink(event)}>
|
||||
<label htmlFor="speaker-email">Email</label>
|
||||
<input className="input" id="speaker-email" type="email" autoComplete="email" required value={email} onChange={(event) => setEmail(event.target.value)} />
|
||||
<button className="btn primary" type="submit" disabled={busy}>{busy ? 'Sending...' : 'Send sign-in link'}</button>
|
||||
</form>}
|
||||
</main></div>;
|
||||
}
|
||||
@@ -1,4 +1,14 @@
|
||||
* { margin: 0; padding: 0; box-sizing: border-box; -webkit-tap-highlight-color: transparent; }
|
||||
.speaker-portal { letter-spacing: 0; }
|
||||
.speaker-portal .h1 { letter-spacing: 0; }
|
||||
.speaker-portal header { flex-wrap: wrap; }
|
||||
.speaker-portal form { display: grid; gap: 14px; }
|
||||
.speaker-portal p, .speaker-portal h3, .speaker-download { overflow-wrap: anywhere; }
|
||||
.speaker-talk { display: grid; gap: 10px; padding: 18px 0; border-top: 1px solid var(--line); }
|
||||
.speaker-portal input { width: 100%; min-width: 0; }
|
||||
.speaker-portal input[type="file"] { font-size: 12px; padding: 10px; }
|
||||
.speaker-portal progress { width: 100%; accent-color: var(--accent-2); }
|
||||
.speaker-download { color: var(--accent-2); }
|
||||
:root {
|
||||
--bg: #f0f2f6; --phone-bg: #ffffff; --surface: #ffffff; --surface-2: #f4f5f9;
|
||||
--line: #e4e6ee; --text: #423c3c; --muted: #8a8484;
|
||||
|
||||
Reference in new issue
Block a user