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;
|
||||
|
||||
@@ -141,14 +141,15 @@ the work atomically, and the `leaderboard` table change fans out over Realtime.
|
||||
(Staff can also still log in with their email + QR token, their seeded Auth
|
||||
password.)
|
||||
- **`@appe.at` admins:** any contact on the `@appe.at` domain is an admin
|
||||
(`is_admin()` is domain-aware) and logs in with the **default admin password
|
||||
`appe-admin-2026`** out of the box. The `trg_contacts_appe_at_admin` trigger
|
||||
(`is_admin()` is domain-aware). The Admin console uses only
|
||||
[email magic links](frontend/admin-app.md#auth-guard), without password login
|
||||
or a password-change prompt. The `trg_contacts_appe_at_admin` trigger
|
||||
sets `contacts.password` to the default (when null) and the auth-user
|
||||
creation helpers hash it into `auth.users.encrypted_password`, so a
|
||||
freshly-created `@appe.at` admin can sign in immediately. A custom password
|
||||
set on the contact row is always respected.
|
||||
- `enable_confirmations = false`, so **no email is sent** — the email is only a
|
||||
"confirm it's you" check against the ticket purchase.
|
||||
creation helpers hash it into `auth.users.encrypted_password`; these existing
|
||||
passwords and shared password operations remain available for Convivo staff
|
||||
login. A custom password set on the contact row is always respected.
|
||||
- Normal attendee/staff QR login sends no email. `enable_confirmations = false`
|
||||
disables signup confirmation, not explicit Admin/speaker magic-link requests.
|
||||
- After login, the app holds a **session JWT** (in `localStorage`) that lasts
|
||||
**24 hours** (`jwt_expiry = 86400`). Every request sends the **anon key**
|
||||
(public) + the **session JWT** (identity).
|
||||
|
||||
+37
-4
@@ -130,18 +130,51 @@ The `materials` bucket (public read) stores session material. Policies on
|
||||
create policy "materials_read" on storage.objects for select to authenticated
|
||||
using (bucket_id = 'materials');
|
||||
create policy "materials_write" on storage.objects for insert to authenticated
|
||||
with check (bucket_id = 'materials' and public.is_speaker_or_admin());
|
||||
with check (bucket_id = 'materials' and public.can_write_session_material(name));
|
||||
create policy "materials_update" on storage.objects for update to authenticated
|
||||
using (bucket_id = 'materials' and public.is_speaker_or_admin());
|
||||
using (bucket_id = 'materials' and public.can_write_session_material(name))
|
||||
with check (bucket_id = 'materials' and public.can_write_session_material(name));
|
||||
create policy "materials_delete" on storage.objects for delete to authenticated
|
||||
using (bucket_id = 'materials' and public.is_speaker_or_admin());
|
||||
using (bucket_id = 'materials' and public.can_write_session_material(name));
|
||||
```
|
||||
|
||||
Speakers + admins can write; any authenticated attendee can read (download).
|
||||
Registered speakers can write only their own non-service session paths; admins
|
||||
retain material management access. Any authenticated attendee can read (download).
|
||||
Because the `sessions` table is admin-write only, a speaker attaches their
|
||||
uploaded file via the `set_session_material` RPC (see
|
||||
[rpcs.md](./rpcs.md#set_session_materialp_session_id-p_material_path--sessions)).
|
||||
|
||||
## Speaker Portal Authorization
|
||||
|
||||
Source: [speaker portal migration](../../supabase/migrations/20261006175631_speaker_portal.sql),
|
||||
with [staff overlap](../../supabase/migrations/20261007153957_speaker_portal_staff_overlap.sql).
|
||||
`owns_speaker_session(session_id)` requires the JWT's `current_email()` to have
|
||||
both a `session_speakers` assignment and a `registrations.type` of `speaker` or `staff`
|
||||
for that session's event. The slot must belong to the same event and be type
|
||||
`session`, not `service_session`. Assignment alone, registration alone,
|
||||
attendee/sponsor assignments, or another speaker's registration is insufficient.
|
||||
Admin/organizer staff can also speak without changing category or losing staff
|
||||
points/check-in exclusions. There is no separate `organizer` enum value.
|
||||
Automatic staff links to service slots do not grant portal ownership.
|
||||
Admins retain global material management access, but the portal lists only their own talks.
|
||||
|
||||
Neither event activation, event date nor `checked_in` enters this predicate.
|
||||
`can_write_session_material(path)` accepts speaker paths only in the form
|
||||
`sessions/<UUID>/<non-empty filename>` and checks the referenced session's
|
||||
ownership. UPDATE checks both old and new names, preventing reassignment to
|
||||
foreign paths. Public material reads are intentionally unchanged.
|
||||
|
||||
The portal read and material setter are security-definer functions with an empty
|
||||
search path and qualified object names. EXECUTE is revoked from PUBLIC/anon and
|
||||
granted to authenticated/service_role; role membership alone does not grant
|
||||
speaker access. The setter checks ownership again, locks the session row and
|
||||
verifies a non-null object exists in `materials` under the exact session path.
|
||||
It cannot update registrations, points logs, check-ins or leaderboard rows.
|
||||
|
||||
See [RPCs](./rpcs.md#speaker-portal-rpcs), [transactional tests](./tests.md#speaker-portal)
|
||||
and [frontend entry points](../frontend/screens.md#speaker-portal). The normal
|
||||
app's physical check-in gate remains separate and unchanged.
|
||||
|
||||
## GRANTs
|
||||
|
||||
The new Supabase CLI does **not** auto-expose new tables to the Data API roles, so
|
||||
|
||||
+35
-6
@@ -18,8 +18,9 @@ Source of truth:
|
||||
re-sync the leaderboard* in **one transaction**. Either all happen or none do.
|
||||
- **Idempotent where it matters** → re-check-in and re-feedback are detected and
|
||||
never double-award.
|
||||
- **Event-scoped** → every RPC resolves the **active event** first and scopes all
|
||||
reads/writes to it.
|
||||
- **Event-scoped** → points RPCs resolve the **active event** first. Speaker
|
||||
portal material RPCs instead authorize against the session's own event,
|
||||
including inactive events.
|
||||
|
||||
## Points rules
|
||||
|
||||
@@ -201,10 +202,38 @@ placeholder string ("AI evaluation stub: N comment(s) received. (LLM integration
|
||||
pending.)"). Real LLM integration is a later phase.
|
||||
|
||||
### `set_session_material(p_session_id, p_material_path)` → `sessions`
|
||||
Sets a session's `material_path`. Allowed for **admins and for any speaker of the
|
||||
session** (the `sessions` table is admin-write only, so speakers need this
|
||||
security-definer RPC to attach their uploaded material). The attendee app calls
|
||||
this after uploading a file to the `materials` bucket.
|
||||
Sets only a session's `material_path`, with a row lock. Requires authentication
|
||||
and either admin access or an own assignment plus `speaker` or `staff` registration for the
|
||||
session's event and a non-service slot. For non-admins, non-null paths must be an
|
||||
existing uploaded `materials` object under `sessions/<this session UUID>/<filename>`.
|
||||
`NULL` detaches material. Ownership/path failures use SQLSTATE `42501`.
|
||||
There is no active-event, date, check-in or points condition. Shared by Agenda and
|
||||
the [speaker portal](../frontend/screens.md#speaker-portal).
|
||||
|
||||
## Speaker Portal RPCs
|
||||
|
||||
Source: [20261006175631_speaker_portal.sql](../../supabase/migrations/20261006175631_speaker_portal.sql),
|
||||
with [staff overlap](../../supabase/migrations/20261007153957_speaker_portal_staff_overlap.sql).
|
||||
|
||||
- `get_my_speaker_sessions()` returns own registered non-service talks across
|
||||
all events, ordered by slot date/time, event name, title and session ID. Rows
|
||||
contain `session_id`, `title`, `description`, `room`, `material_path`,
|
||||
`event_id`, `event_name`, `event_start_date`, `event_end_date`, `is_active`,
|
||||
`slot_date`, `start_time`, `end_time`. Ineligible authenticated users get `[]`.
|
||||
- `owns_speaker_session(uuid)` requires an explicit own talk assignment and a
|
||||
same-event `speaker` or `staff` registration, including registered Admin staff.
|
||||
Registration category remains unchanged; staff points/check-in exclusions remain intact.
|
||||
- `can_write_session_material(text)` validates session object paths for Storage
|
||||
INSERT/UPDATE/DELETE; admins retain their existing management access.
|
||||
- `set_session_material(uuid, text)` follows the mutation contract above and
|
||||
does not mark physical attendance or award points.
|
||||
|
||||
All four functions revoke PUBLIC/anon execution and grant authenticated/service_role
|
||||
execution. See [RLS details](./rls.md#speaker-portal-authorization),
|
||||
[client lifecycle](../frontend/api-client.md#speaker-portal) and
|
||||
[regression tests](./tests.md#speaker-portal).
|
||||
|
||||
## Other RPCs
|
||||
|
||||
### `update_my_profile(p_linkedin_url, p_show_email, p_show_linkedin)` → `contacts`
|
||||
**Self-service (any authenticated attendee).** Lets a contact edit their own
|
||||
|
||||
@@ -65,21 +65,22 @@ Bootcamp (Austria)** — instead of random demo data:
|
||||
|
||||
**Attendees** log in with **QR code** (typed or scanned) + **email** — the QR
|
||||
token is the Auth password. **Staff** log in with **QR code + their staff
|
||||
password** in the Convivo app, or **email + password** in the admin app. All four
|
||||
password** in the Convivo app. The Admin console uses only
|
||||
[email magic links](../frontend/admin-app.md#auth-guard). All four
|
||||
staff share the password **`appe-admin-2026`** (stored in `contacts.password`,
|
||||
auto-synced to `auth.users.encrypted_password` by the `trg_contact_password_sync`
|
||||
trigger).
|
||||
|
||||
> **Default admin password:** any `@appe.at` contact is an admin and logs in
|
||||
> with **`appe-admin-2026`** out of the box. The `trg_contacts_appe_at_admin`
|
||||
> **Existing default password:** any `@appe.at` contact is an admin and retains
|
||||
> **`appe-admin-2026`** for Convivo staff password login. The `trg_contacts_appe_at_admin`
|
||||
> trigger sets `contacts.password = 'appe-admin-2026'` (when null) on
|
||||
> insert/update, and the auth-user-creation helpers hash it into
|
||||
> `auth.users.encrypted_password` so a freshly-created `@appe.at` admin can log
|
||||
> in immediately. A custom password set on the contact row is always respected
|
||||
> `auth.users.encrypted_password`. Admin magic-link login neither uses nor changes
|
||||
> these passwords. A custom password set on the contact row is always respected
|
||||
> (never overwritten). See migration
|
||||
> [`20260910000000_admin_default_password.sql`](../../supabase/migrations/20260910000000_admin_default_password.sql).
|
||||
|
||||
| Person | Type | Email | Login |
|
||||
| Person | Type | Email | Convivo Login |
|
||||
|---|---|---|---|
|
||||
| **Amelia Hernandez** | staff (admin) | amelia@appe.at | `appe-admin-2026` |
|
||||
| **Sabrina Hota** | staff (admin) | sabrina@appe.at | `appe-admin-2026` |
|
||||
|
||||
@@ -17,7 +17,7 @@ the "main docker" of the project.
|
||||
| `supabase_storage_Convivo` | `supabase/storage-api` | Storage — the `materials` bucket (session material) |
|
||||
| `supabase_kong_Convivo` | `supabase/kong` | **API gateway** — fronts everything on one port |
|
||||
| `supabase_studio_Convivo` | `supabase/studio` | Web UI (Studio) |
|
||||
| `supabase_inbucket_Convivo` | `supabase/mailpit` | Captures emails (none sent in this flow) |
|
||||
| `supabase_inbucket_Convivo` | `supabase/mailpit` | Local capture service; Auth bypasses it while custom SMTP is enabled |
|
||||
| `supabase_pg_meta_Convivo` | `supabase/postgres-meta` | Metadata API (used by Studio) |
|
||||
| `supabase_edge_runtime_Convivo` | `supabase/edge-runtime` | Edge functions (unused in v1) |
|
||||
| `supabase_vector_Convivo` | `supabase/vector` | Log shipping |
|
||||
@@ -34,7 +34,7 @@ All containers share the external Docker network **`supabase_network_Convivo`**
|
||||
| **API (Kong)** | **54321** | 8000 | The single gateway the app proxies to. **Inside the network, Kong is on 8000** — the `54321→8000` mapping is host-only. |
|
||||
| Studio | 54323 | 3000 | UI — login `postgres` / `postgres` |
|
||||
| Postgres | 54322 | 5432 | Direct DB — `postgres` / `postgres` |
|
||||
| SMTP (Mailpit) | 54324 | 8025 | Captures emails |
|
||||
| Mailpit UI | 54324 | 8025 | Capture-only testing when custom SMTP is disabled; currently bypassed by Auth |
|
||||
| Analytics | 54327 | 4000 | Logflare |
|
||||
|
||||
> **Gotcha:** from *inside* the shared network (e.g. the app container), reach
|
||||
@@ -75,11 +75,144 @@ npx supabase status
|
||||
| `[api] port` | `54321` | Kong gateway port |
|
||||
| `[db] port` | `54322` | Postgres port |
|
||||
| `[studio] port` | `54323` | Studio port |
|
||||
| `[auth.email] enable_confirmations` | `false` | **No email is sent** — the QR+email login never emails the user |
|
||||
| `[auth.email] enable_confirmations` | `false` | Signup confirmation is disabled locally; explicit magic-link requests still send email |
|
||||
| `[auth] jwt_expiry` | `86400` | **24-hour login** — the session JWT lives a full day |
|
||||
| `[auth] site_url` | `http://127.0.0.1:3000` | The app origin |
|
||||
| `[auth] additional_redirect_urls` | Exact local attendee, speaker and Admin URLs | Allows magic links to return to the requested app route |
|
||||
| `[auth.rate_limit] email_sent` | `100` | Project-wide hourly budget when using custom SMTP; not an entitlement to provider capacity |
|
||||
| `[auth.email] max_frequency` | `60s` | Minimum resend interval, matching the Admin UI cooldown |
|
||||
| `[auth.email] otp_expiry` | `3600` | Magic links expire after one hour and are single-use |
|
||||
| `[auth.email.smtp] enabled` | `true` | Explicit local opt-in to real outbound MXroute email, not Mailpit capture |
|
||||
| `[auth.email.smtp] pass` | `env(CONVIVO_SMTP_PASSWORD)` | Password loaded from a private runtime environment, never committed |
|
||||
| `[db.seed] sql_paths` | `["./seed.sql"]` | Seed runs on reset |
|
||||
|
||||
## Magic-link configuration
|
||||
|
||||
### Local development
|
||||
|
||||
The committed [config](../../supabase/config.toml) keeps `site_url` on
|
||||
`http://127.0.0.1:3000` and retains the existing HTTPS localhost entry. It adds
|
||||
these exact HTTP redirect destinations for **both** `localhost` and `127.0.0.1`:
|
||||
|
||||
- Port 3000: the app origin, `/speaker`, and `/speaker/secret`.
|
||||
- Port 3001: `/auth/callback` for [Admin magic links](../frontend/admin-app.md#magic-links).
|
||||
|
||||
Hosts, schemes, ports and paths must match; there are no wildcard redirects.
|
||||
For an alternate dev port, explicitly allow its callback URL before testing
|
||||
real email links. Mocked browser tests do not exercise the Auth allowlist.
|
||||
|
||||
Local Auth explicitly opts into **real outbound email** through MXroute:
|
||||
`heracles.mxrouting.net:465`, SMTP user and From address `[email protected]`,
|
||||
sender name `Convivo APP`. GoTrue's mail transport selects implicit TLS for
|
||||
port 465 and verifies the server certificate; no insecure TLS override is used.
|
||||
Mailpit remains available but does not capture these externally delivered emails.
|
||||
|
||||
The password is referenced only as `env(CONVIVO_SMTP_PASSWORD)`. On this machine,
|
||||
it is provisioned in the git-ignored `supabase/.env`, with owner-only permissions
|
||||
(`0600`). Supabase CLI **2.115.0** loads dotenv files starting in `supabase/`
|
||||
and then the project root, so ordinary `npm run db:start` retains SMTP delivery
|
||||
without a shell export or helper. Existing process environment variables and
|
||||
higher-priority dotenv files can override this value. For another checkout,
|
||||
provision the same variable through a private secret store or ignored dotenv
|
||||
file before starting; do not put the password in commands, tracked files,
|
||||
frontend variables, screenshots, or diagnostic output.
|
||||
|
||||
Apply configuration changes with a local-only, volume-preserving restart:
|
||||
|
||||
```bash
|
||||
npx supabase stop --project-id Convivo
|
||||
npx supabase start
|
||||
```
|
||||
|
||||
Expect a brief interruption of local services. Do **not** use `--no-backup`,
|
||||
`--all`, or `db:reset`: no database reset, seed, or user creation is needed.
|
||||
Configuration edits alone do not reconfigure a running Auth container.
|
||||
For capture-only tests, set `[auth.email.smtp] enabled = false` and restart;
|
||||
then inspect Mailpit at `http://127.0.0.1:54324`. Restore `enabled = true` and
|
||||
restart when deliberately returning to real delivery.
|
||||
|
||||
Local activation was checked on 2026-10-07: normal stop/start restored the
|
||||
database from backup, Auth became healthy, and its runtime SMTP host, port,
|
||||
user, sender and password matched the intended configuration. The password
|
||||
comparison was performed without displaying it and with no shell export,
|
||||
confirming dotenv persistence. This activation check sent **no email** and does
|
||||
not prove inbox delivery. The separately authorized frontend/Auth delivery check
|
||||
must use an existing eligible account, verify the received link and exact
|
||||
`redirect_to`, and respect the 60-second resend interval.
|
||||
|
||||
### Production activation (2026-10-07)
|
||||
|
||||
The CLI-managed VM deployment at `/home/APPE/convivo` now has verified DNS,
|
||||
TLS and public routing for `convivo.appe.at` and `admin.appe.at`. Both app
|
||||
origins and the exact speaker/Admin callback routes return HTTP 200; public
|
||||
Auth health returns 200. `db.appe.at` has no DNS record and is not used.
|
||||
See [deployment evidence and backups](../deployment.md#production-status-2026-10-07).
|
||||
|
||||
Production-specific changes were made only to the remote config, retaining
|
||||
other settings rather than copying the local config wholesale:
|
||||
|
||||
- `[auth] site_url = "https://convivo.appe.at"`.
|
||||
- `[auth] external_url = "https://convivo.appe.at/auth/v1"`, verified through
|
||||
the attendee app's same-origin Auth proxy.
|
||||
- Exact redirect additions: `https://convivo.appe.at`,
|
||||
`https://admin.appe.at`, `https://convivo.appe.at/speaker`,
|
||||
`https://convivo.appe.at/speaker/secret`, and
|
||||
`https://admin.appe.at/auth/callback`. The pre-existing exact
|
||||
`https://127.0.0.1:3000` entry was preserved; no wildcard was added.
|
||||
- `[auth] jwt_issuer` explicitly retains
|
||||
`http://127.0.0.1:54321/auth/v1`. This is token issuer identity, not the
|
||||
public verification link. Both issuer and signing secret matched the
|
||||
pre-restart Auth runtime, preserving existing session semantics.
|
||||
- Custom SMTP is enabled at `heracles.mxrouting.net:465`, using implicit TLS
|
||||
with verified certificates, SMTP user/From `[email protected]`, and sender
|
||||
`Convivo APP`. Runtime password equality was checked without disclosure.
|
||||
- `pass = "env(CONVIVO_SMTP_PASSWORD)"` loads from the private remote
|
||||
`supabase/.env` (0600). Only this approved variable was provisioned over
|
||||
encrypted SSH stdin; existing dotenv variables and root environment files
|
||||
were preserved. No secret or local fixture dotenv was synced.
|
||||
- The hourly email budget is 100, resend interval 60 seconds, and OTP expiry
|
||||
3600 seconds. The standard verification-link template was retained.
|
||||
|
||||
The remote config passed CLI validation, then normal CLI **2.115.0** stop/start
|
||||
activated it without reset, seed, data-volume deletion, or core image changes.
|
||||
Both frontends were replaced from prebuilt images; the existing sidecar was
|
||||
left running. Speaker RPC privileges and material write policies passed
|
||||
post-restart checks, including assigned speakers registered as `staff` and
|
||||
exclusion of non-session slots.
|
||||
|
||||
One authorized Admin magic-link request for the existing `[email protected]` account
|
||||
returned HTTP 200 with account creation disabled. This verifies API acceptance
|
||||
of the SMTP-backed request, not inbox receipt or full browser sign-in.
|
||||
SPF/DKIM/DMARC, received-link contents, expiry/reuse rejection, and browser
|
||||
screenshots remain separate verification work. Do not send additional test
|
||||
emails or create production fixtures without explicit authorization.
|
||||
|
||||
### Rate limits and abuse boundary
|
||||
|
||||
The local policy is 100 Auth emails per project per hour and a 60-second resend
|
||||
interval. The committed SMTP block is enabled for explicitly requested local
|
||||
real delivery. Hosted Supabase's built-in
|
||||
email provider has its own restrictions (currently two emails/hour and delivery
|
||||
only to authorized team addresses); changing this file does not raise those
|
||||
limits. Production needs custom SMTP and an explicitly configured hourly limit
|
||||
that fits both provider capacity and the expected audience.
|
||||
|
||||
The browser cooldown and generic confirmation are UX/privacy controls, **not**
|
||||
abuse enforcement. `shouldCreateUser: false` prevents this client from creating
|
||||
accounts but does not prevent direct requests to public Auth endpoints, or
|
||||
emailing existing non-admin users. The admin gate and database RLS control
|
||||
access, not outbound mail. Enforce Auth's server-side per-user/IP/project limits,
|
||||
monitor delivery failures and quota exhaustion, and evaluate CAPTCHA or a
|
||||
server-side send-email policy before public rollout. Raising the hourly budget
|
||||
increases spam and quota-exhaustion exposure; do not remove the resend limit.
|
||||
Account-neutral UI messages do not guarantee that the underlying Auth API is
|
||||
resistant to enumeration.
|
||||
|
||||
Current references: [passwordless email](https://supabase.com/docs/guides/auth/auth-email-passwordless),
|
||||
[redirect URLs](https://supabase.com/docs/guides/auth/redirect-urls),
|
||||
[custom SMTP](https://supabase.com/docs/guides/auth/auth-smtp), and
|
||||
[rate limits](https://supabase.com/docs/guides/auth/rate-limits).
|
||||
|
||||
## Keys
|
||||
|
||||
| Key | Value | Where it's used |
|
||||
|
||||
@@ -42,6 +42,52 @@ docker exec -i supabase_db_Convivo psql -U postgres < supabase/tests/rpc_tests.s
|
||||
| Speaker auto-promote trigger | attendee → speaker, never overrides staff |
|
||||
| Leaderboard | excludes staff |
|
||||
|
||||
## Speaker Portal
|
||||
|
||||
[speaker_portal_tests.sql](../../supabase/tests/speaker_portal_tests.sql) is an
|
||||
independent fail-fast suite (`ON_ERROR_STOP`) with generated contacts/events/talks,
|
||||
temporary snapshots and a single transaction ending in `ROLLBACK`. It needs the
|
||||
[speaker portal migration](../../supabase/migrations/20261006175631_speaker_portal.sql)
|
||||
and [staff overlap migration](../../supabase/migrations/20261007153957_speaker_portal_staff_overlap.sql)
|
||||
on the **local** database. Apply without resetting existing data:
|
||||
|
||||
```bash
|
||||
docker exec -i supabase_db_Convivo psql -U postgres -d postgres -v ON_ERROR_STOP=1 --single-transaction < supabase/migrations/20261006175631_speaker_portal.sql
|
||||
docker exec -i supabase_db_Convivo psql -U postgres -d postgres -v ON_ERROR_STOP=1 --single-transaction < supabase/migrations/20261007153957_speaker_portal_staff_overlap.sql
|
||||
docker exec -i supabase_db_Convivo psql -U postgres -d postgres -v ON_ERROR_STOP=1 < supabase/tests/speaker_portal_tests.sql
|
||||
```
|
||||
|
||||
This direct migration application reloads the local API schema but does not
|
||||
write CLI migration history. It is not a production deployment command. No
|
||||
database reset is needed; fixture sequence state is not advanced.
|
||||
|
||||
The suite checks assigned speaker, non-admin staff and Admin staff access,
|
||||
unassigned staff, mismatched same-event registrations, attendee assignments,
|
||||
unregistered assignments, automatic service-session exclusion, active/inactive past/future
|
||||
events, malformed and cross-session paths, required uploaded objects, Storage
|
||||
INSERT/UPDATE/DELETE (including UPDATE WITH CHECK) and unchanged registration,
|
||||
points-log, check-in and leaderboard state. Storage policy checks use the
|
||||
`authenticated` database role, not a superuser that bypasses RLS. A failed
|
||||
assertion exits non-zero and connection closure rolls back the transaction.
|
||||
|
||||
[speaker-portal.spec.ts](../../e2e/tests/speaker-portal.spec.ts) uses mocked Auth,
|
||||
REST and Storage responses, without real credentials or mail delivery:
|
||||
|
||||
```bash
|
||||
cd e2e
|
||||
CONVIVO_BASE_URL=http://127.0.0.1:3000 npx playwright test tests/speaker-portal.spec.ts --project=chromium --reporter=list --output=/tmp/convivo-speaker-results
|
||||
```
|
||||
|
||||
Start Convivo's dev server first. Coverage includes both routes, existing-users-only
|
||||
link requests, URL scrubbing, callback errors/rejections, StrictMode single-use
|
||||
implicit/PKCE callbacks, local logout, empty access, upload/replace/remove across
|
||||
desktop/mobile, failed attachment cleanup and the normal app's check-in gate
|
||||
after portal login. Mocked tests do not validate live mail delivery, deployment
|
||||
redirect allowlists or real Storage behavior; the SQL suite validates database
|
||||
authorization separately. See [screen contract](../frontend/screens.md#speaker-portal),
|
||||
[API client](../frontend/api-client.md#speaker-portal), [RLS](./rls.md#speaker-portal-authorization)
|
||||
and [RPCs](./rpcs.md#speaker-portal-rpcs).
|
||||
|
||||
## Files
|
||||
|
||||
- [`supabase/tests/rpc_tests.sql`](../../supabase/tests/rpc_tests.sql) — the test
|
||||
|
||||
+56
-9
@@ -1,16 +1,63 @@
|
||||
# Deployment — VM Access
|
||||
|
||||
Convivo currently runs **entirely on localhost** (see
|
||||
Convivo runs locally for development and on the production VM at
|
||||
`/home/APPE/convivo`. The VM is a flat file copy, not a Git checkout. See
|
||||
[backend/supabase-core.md](./backend/supabase-core.md) and
|
||||
[backend/docker.md](./backend/docker.md)). This page documents the **remote VM** that is
|
||||
the intended deployment target for the `appe.at` subdomains
|
||||
(`convivo.appe.at`, `admin.appe.at`, `db.appe.at`).
|
||||
[backend/docker.md](./backend/docker.md) for service ownership.
|
||||
|
||||
> **Status:** the VM is reachable and the credentials below are **verified**
|
||||
> (last validated 2026-08-25). The full Convivo stack is **deployed and running**
|
||||
> on the VM (see [Running services](#running-services)). DNS, TLS, and the
|
||||
> reverse proxy for the `appe.at` subdomains are **not** set up yet — see
|
||||
> [next-steps.md](./next-steps.md#cross-cutting--later).
|
||||
## Production status (2026-10-07)
|
||||
|
||||
| Public URL | Role | Verified result |
|
||||
|---|---|---|
|
||||
| `https://convivo.appe.at` | Attendee app | DNS points to `68.210.96.53`; valid TLS; HTTP 200 |
|
||||
| `https://convivo.appe.at/speaker` | Speaker portal | HTTP 200 SPA route |
|
||||
| `https://convivo.appe.at/speaker/secret` | Speaker portal alternate entry | HTTP 200 SPA route |
|
||||
| `https://admin.appe.at` | Admin console | DNS points to the VM; valid TLS; HTTP 200 |
|
||||
| `https://admin.appe.at/auth/callback` | Admin magic-link callback | HTTP 200 SPA, not an Auth 404 |
|
||||
| `https://convivo.appe.at/auth/v1` | Public Supabase Auth | `/health` returns 200; `/verify` without a token returns expected 400 |
|
||||
| `https://db.appe.at` | Reserved database/API domain | No DNS record; not used by this deployment |
|
||||
|
||||
Nginx Proxy Manager routes the attendee and Admin domains to host ports 3000
|
||||
and 3001. Both apps proxy same-origin Supabase API paths to
|
||||
`supabase_kong_Convivo:8000` on `supabase_network_Convivo`.
|
||||
|
||||
### Deployment evidence
|
||||
|
||||
- Supabase CLI remains **2.115.0** at `~/.supabase/bin/supabase`; every core
|
||||
container image ID and the Auth JWT secret/issuer were unchanged after the
|
||||
volume-preserving stop/start. Frontends were built before the interruption.
|
||||
- Only the approved 10 frontend runtime files and three speaker migrations
|
||||
were transferred. The VM baseline predates local Reports/networking changes:
|
||||
tracked feature diffs were applied against backed-up VM source, excluding
|
||||
unchanged Reports-only patch context. Unrelated views, dependencies and
|
||||
migrations were not deployed. Manifests, lockfiles, app dotenv files and
|
||||
Compose configuration were preserved.
|
||||
- Applied and verified migration versions: `20261006175622` (empty history
|
||||
entry), `20261006175631`, and `20261007153957`. Each missing migration and its
|
||||
statement-array history entry were committed in one transaction. No reset,
|
||||
seed, fixture sync, user creation, Git commit or Git reset was performed.
|
||||
- The protected backup directory is
|
||||
`/home/APPE/convivo-backups/20261007T155959Z` (directory mode 0700; artifacts
|
||||
0600). It contains a full `postgres.dump`, a second pre-restart database dump,
|
||||
source/config backups, private runtime metadata, and validation summaries.
|
||||
Old frontend images remain tagged
|
||||
`convivo-app:rollback-20261007T155959Z` and
|
||||
`convivo-admin:rollback-20261007T155959Z`; no rollback was needed.
|
||||
- All pre-deployment records were preserved. Counts changed from 68 to 84
|
||||
contacts, 121 to 137 Auth users, and 67 to 83 registrations while the existing
|
||||
Pretix-enabled sidecar kept running. Events (1), sessions (21), and storage
|
||||
objects (1) stayed constant. Archive-to-live key comparisons found zero
|
||||
missing records; CLI startup showed no seed execution.
|
||||
- Core services and both frontends are healthy; all three nginx configuration
|
||||
checks passed; sidecar `/health` returns 200. Served build markers are
|
||||
`index-Gv3o7AW6.js` (attendee/speaker) and `index-CocPCSGt.js` (Admin).
|
||||
- Lago's existing Auth account and eligible Admin contact were verified, with
|
||||
two eligible speaker-portal sessions. One authorized Admin magic-link request
|
||||
to `[email protected]` returned HTTP 200 with `create_user = false`. Inbox receipt,
|
||||
consuming the email link, and browser screenshots were not verified.
|
||||
|
||||
SMTP, exact redirects, issuer preservation and private dotenv provisioning are
|
||||
documented in [Production Auth](./backend/supabase-core.md#production-activation-2026-10-07).
|
||||
|
||||
## VM credentials
|
||||
|
||||
|
||||
+57
-11
@@ -3,8 +3,9 @@
|
||||
The admin console is a **desktop-first single-page React app** in
|
||||
[`apps/admin/`](../../apps/admin/), branded **APPE Admin**. It is a separate app
|
||||
from the attendee PWA (same stack, same Supabase core, same same-origin proxy
|
||||
pattern) and is **guarded to the `is_admin` flag** — anyone else who signs in is
|
||||
immediately signed out.
|
||||
pattern). Its admin gate accepts an existing contact with **`is_admin = true`
|
||||
or an `@appe.at` email**, matching the database admin rule; other accounts are
|
||||
signed out. Backend RLS remains the authorization boundary.
|
||||
|
||||
It runs on **port 3001** (Vite dev) or as the `convivo-admin` Docker container
|
||||
(nginx). The attendee app stays on 3000.
|
||||
@@ -24,19 +25,64 @@ It runs on **port 3001** (Vite dev) or as the `convivo-admin` Docker container
|
||||
|
||||
## Auth guard
|
||||
|
||||
Login is **email + password** (`signInWithPassword({ email, password })`), but
|
||||
`AuthContext` checks the contact's `is_admin` flag after signing in:
|
||||
Login uses **email-only magic links**, with no password field, sign-in method
|
||||
selector, password fallback, or password-change prompt. `AuthContext` checks
|
||||
the contact after signing in:
|
||||
|
||||
- If `is_admin === true` → the session is accepted and the console is shown.
|
||||
- If `is_admin === true` or the contact email ends in `@appe.at` → the session
|
||||
is accepted and the console is shown.
|
||||
- Otherwise → the app calls `signOut()` and shows **"This account is not an
|
||||
admin."** The same check runs on session restore (page reload) and on every
|
||||
`onAuthStateChange`, so a non-admin can never see the console.
|
||||
|
||||
The password is **event-independent** — it is the contact's Auth password
|
||||
(`contacts.password` must match the bcrypt hash in `auth.users.encrypted_password`),
|
||||
so the same admin can log in for any event. The seeded staff are
|
||||
`[email protected]`, `[email protected]`, `[email protected]`, and `[email protected]`, all
|
||||
with password `appe-admin-2026` (see [../backend/seed.md](../backend/seed.md)).
|
||||
### Magic links
|
||||
|
||||
The email-only form calls `signInWithOtp` with `shouldCreateUser: false` and
|
||||
`emailRedirectTo: <current Admin origin>/auth/callback`. It does not create
|
||||
accounts or grant admin privileges. Eligible accounts must already exist in
|
||||
Supabase Auth and have a matching contact. Account-related send failures show
|
||||
the same generic confirmation as success; rate limits, network failures and
|
||||
server failures show a generic retry error instead of server details. The
|
||||
recipient is locked while sending, and resend has a 60-second UI
|
||||
cooldown. A failed resend clears the previous confirmation.
|
||||
|
||||
`/auth/callback` accepts implicit-flow access/refresh tokens in the fragment,
|
||||
or a PKCE `code` query parameter when a verifier exists in the same browser.
|
||||
The callback is consumed once even under React StrictMode. It removes query
|
||||
parameters and fragments from browser history before exchanging credentials,
|
||||
ignores supplied `next`/`redirect_to` destinations, and always returns to `/`.
|
||||
Invalid, expired or rejected links clear the local Auth session and allow a new
|
||||
link request. The default client uses implicit flow and
|
||||
`detectSessionInUrl: false`; the callback performs session handling explicitly.
|
||||
A token-hash `/auth/confirm` email template is not supported by this handler.
|
||||
|
||||
Auth-state listeners defer Supabase calls with `setTimeout` rather than awaiting
|
||||
them inside `onAuthStateChange`, avoiding Auth lock deadlocks. Revision checks
|
||||
discard outdated listener/session-restore lookups after later auth events.
|
||||
|
||||
Vite proxies only `/auth/v1` so the SPA owns `/auth/callback`; nginx serves the
|
||||
callback with `Cache-Control: no-store` and `Referrer-Policy: no-referrer`.
|
||||
Local redirect allowlisting, Mailpit, and explicit production SMTP/URL setup are
|
||||
documented in [Supabase Core](../backend/supabase-core.md#magic-link-configuration).
|
||||
`admin.appe.at` is an intended production domain, not a verified deployment.
|
||||
|
||||
Focused browser coverage (mocked Auth/REST; no real email or database writes):
|
||||
|
||||
```bash
|
||||
npm --prefix apps/admin run build
|
||||
npm --prefix e2e test -- admin-magic-link.spec.ts
|
||||
```
|
||||
|
||||
The spec defaults to `http://localhost:3001`; set `CONVIVO_ADMIN_URL` to test an
|
||||
alternate local server. Real delivery and Supabase redirect enforcement require
|
||||
a separate local Mailpit smoke test after restarting the local Auth service.
|
||||
|
||||
This is an **Admin frontend-only** change. Existing database passwords, password
|
||||
sync triggers, shared password operations and Supabase Auth's password endpoint
|
||||
remain unchanged because attendee/staff login still uses them. Admin sessions
|
||||
remain event-independent, and contacts with existing default passwords do not
|
||||
receive a password-change prompt. See [demo accounts](../backend/seed.md#demo-accounts)
|
||||
for seeded staff credentials used by the Convivo app.
|
||||
|
||||
## Source layout
|
||||
|
||||
@@ -55,7 +101,7 @@ apps/admin/src/
|
||||
├─ components/
|
||||
│ └─ ui.tsx # Avatar, Spinner, Empty, Modal, QrImage, TypeBadge, Toggle
|
||||
├─ screens/
|
||||
│ └─ Login.tsx # email + password login (admin-only)
|
||||
│ └─ Login.tsx # email-only magic-link login (admin-only)
|
||||
└─ views/
|
||||
├─ Dashboard.tsx # active event + aggregates + top points + activity
|
||||
├─ Contacts.tsx # table + edit / is_admin / visibility / points
|
||||
|
||||
@@ -55,7 +55,7 @@ These map 1:1 to the Postgres RPCs documented in
|
||||
| `submitFeedback(sessionId, rating, comment)` | `submit_feedback` | Rate a session (+5/+10) |
|
||||
| `getLeaderboard()` | `get_leaderboard` | Active-event leaderboard |
|
||||
| `uploadSessionMaterial(sessionId, file)` | `set_session_material` | Upload to `materials` bucket + set `material_path` |
|
||||
| `removeSessionMaterial(sessionId)` | `set_session_material` | Delete storage object + clear `material_path` (speakers) |
|
||||
| `removeSessionMaterial(sessionId)` | `set_session_material` | Clear `material_path`, then delete the detached storage object |
|
||||
| `updateMyProfile({linkedin_url, show_email, show_linkedin})` | `update_my_profile` | Self-service: set LinkedIn + visibility toggles on the caller's own contact |
|
||||
|
||||
### Direct table reads (RLS-scoped)
|
||||
@@ -82,6 +82,38 @@ client-side to avoid leaking other people's data:
|
||||
- **`sessionMaterialUrl(path)`** — builds the public URL for a session material
|
||||
in the `materials` bucket.
|
||||
|
||||
## Speaker Portal
|
||||
|
||||
[speakerPortal.ts](../../apps/convivo/src/lib/speakerPortal.ts) recognizes only
|
||||
`/speaker/secret` and `/speaker` (optional trailing slash). It exposes a shared
|
||||
`speakerPortalSession` promise, consuming implicit token pairs with `setSession`
|
||||
or PKCE codes with `exchangeCodeForSession` exactly once per page load, including
|
||||
React StrictMode. Automatic URL session detection remains disabled. Callback
|
||||
parameters are scrubbed before auth calls; errors use generic recoverable text.
|
||||
|
||||
`SpeakerPortal` requests `signInWithOtp` with `shouldCreateUser: false` and
|
||||
`emailRedirectTo: window.location.origin + '/speaker/secret'`. Supabase Auth's
|
||||
redirect allowlist must include this URL on each deployment origin. This does
|
||||
not create contacts, registrations or Auth users.
|
||||
|
||||
`getSpeakerPortalSessions()` calls `get_my_speaker_sessions`, returning typed
|
||||
`SpeakerSession` rows with talk/material, event and slot information. Authorization
|
||||
is [backend-owned](../backend/rls.md#speaker-portal-authorization); the client
|
||||
does not filter by active event, clock, points or physical check-in.
|
||||
|
||||
Material helpers are shared with Agenda. Upload reads the previous path, creates
|
||||
a unique `sessions/<session UUID>/<random UUID>-<sanitized filename>` object,
|
||||
then calls `set_session_material`. A rejected attachment removes the new object.
|
||||
After successful replacement, the previous object is removed. Removal detaches
|
||||
the path first, then deletes the old object. Cleanup errors distinguish a saved
|
||||
or detached material from a failed attachment; the portal refreshes the list
|
||||
after each attempted operation. These Storage and RPC calls are not one atomic
|
||||
transaction, so simultaneous clients remain last-writer-wins and can leave an
|
||||
unattached object; they never mutate attendance or points.
|
||||
|
||||
See [RPC contract](../backend/rpcs.md#speaker-portal-rpcs),
|
||||
[screen states](./screens.md#speaker-portal) and [tests](../backend/tests.md#speaker-portal).
|
||||
|
||||
## Types (`lib/types.ts`)
|
||||
|
||||
TypeScript interfaces mirroring the DB tables and RPC return shapes
|
||||
|
||||
@@ -3,8 +3,9 @@
|
||||
Every screen in [`apps/convivo/src/screens/`](../../apps/convivo/src/screens/).
|
||||
All screens are mobile-first and use the shared UI components
|
||||
([app-structure.md#shared-ui-components](./app-structure.md#shared-ui-components)).
|
||||
Data comes from the typed [api client](./api-client.md); the current user comes
|
||||
from `useAuth()` (`contact` + `registration`).
|
||||
Data comes from the typed [api client](./api-client.md); the normal app's current
|
||||
user comes from `useAuth()` (`contact` + `registration`). The speaker portal
|
||||
uses its own auth lifecycle and backend-scoped session list.
|
||||
|
||||
| Screen | File | Reach |
|
||||
|---|---|---|
|
||||
@@ -17,6 +18,33 @@ from `useAuth()` (`contact` + `registration`).
|
||||
| Leaderboard | `Leaderboard.tsx` | from Home (points pill / quick action) |
|
||||
| Feedback | `Feedback.tsx` | full-screen takeover from Agenda |
|
||||
| EventFeedback | `EventFeedback.tsx` | full-screen takeover from Home ("Rate this event") |
|
||||
| Speaker Portal | [SpeakerPortal.tsx](../../apps/convivo/src/screens/SpeakerPortal.tsx) | `/speaker/secret` (also `/speaker`) |
|
||||
|
||||
## Speaker Portal
|
||||
|
||||
An email-only magic-link login for **existing Auth users**. The canonical
|
||||
redirect is `/speaker/secret`; `/speaker` is also accepted. Neither route is a
|
||||
secret credential: authorization is enforced by the backend. Failed/expired
|
||||
callbacks show a recoverable error and callback tokens/codes are removed from
|
||||
the address bar. Callback consumption is shared across StrictMode mounts.
|
||||
|
||||
Signed-in users see only their own assigned non-service talks with a `speaker`
|
||||
or `staff` registration for the corresponding event. Admin/organizer staff can
|
||||
also speak while retaining their staff category; service-slot assignments are excluded.
|
||||
The list spans all events, including
|
||||
inactive, past and future events. No physical check-in is required. An empty
|
||||
list grants no material controls; access/load failures offer retry.
|
||||
|
||||
Each talk shows event, date/time, room and material status, with upload,
|
||||
replacement, download and confirmed removal. Uploads accept non-empty PDF,
|
||||
PowerPoint, ODP, ZIP and TXT files up to 50 MB. Controls are disabled during a
|
||||
material operation; failures reload server state. Signing out is local to the
|
||||
browser session.
|
||||
|
||||
Portal operations never mark attendance or award points. Visiting `/` still
|
||||
uses the normal app's check-in gate. See [portal API behavior](./api-client.md#speaker-portal),
|
||||
[authorization](../backend/rls.md#speaker-portal-authorization) and
|
||||
[regression coverage](../backend/tests.md#speaker-portal).
|
||||
|
||||
## Login
|
||||
|
||||
@@ -39,7 +67,7 @@ A 3-step flow: **splash → scan → confirm**.
|
||||
mismatch, an error is shown ("Email and QR code do not match" for attendees,
|
||||
"That password is incorrect" for staff).
|
||||
|
||||
> No email is ever sent. See
|
||||
> This normal QR login sends no email; the separate speaker portal uses magic links. See
|
||||
> [../architecture.md#6-authentication-model](../architecture.md#6-authentication-model)
|
||||
> and [../backend/rls.md](../backend/rls.md).
|
||||
|
||||
|
||||
+7
-1
@@ -8,7 +8,8 @@ current phase.
|
||||
> rounds: **Fixes & Refinements** (QR token moved to the registration, role-pill
|
||||
> capitalization, connection detail sheet + red-dot recalc, admin schedule
|
||||
> speaker multi-select + upload/speaker bug fixes, sponsor contact search),
|
||||
> **Admin password + profile self-service** (admin logs in with email + password;
|
||||
> **Admin password + profile self-service** (historical password login, now
|
||||
> superseded by [Admin magic links](frontend/admin-app.md#auth-guard);
|
||||
> attendees set LinkedIn + visibility on their Profile), **Staff exclusions +
|
||||
> password sync** (setting `contacts.password` auto-syncs the Auth password;
|
||||
> staff excluded from the leaderboard; Home/Agenda/Profile identical for all
|
||||
@@ -342,6 +343,11 @@ A cross-cutting polish round (migration `20260826000000_registration_qr_token.sq
|
||||
|
||||
## Admin password + profile self-service — ✅ complete
|
||||
|
||||
The Admin password-login details below record the original milestone, not the
|
||||
current UI. Admin now uses only [email magic links](frontend/admin-app.md#auth-guard),
|
||||
with no password-change prompt. Database passwords and Convivo attendee/staff
|
||||
password login remain unchanged.
|
||||
|
||||
Migration `20260827000000_admin_password_profile.sql` + app changes, all
|
||||
browser-verified.
|
||||
|
||||
|
||||
@@ -0,0 +1,223 @@
|
||||
import { test, expect, type Page } from '@playwright/test';
|
||||
|
||||
const adminUrl = process.env.CONVIVO_ADMIN_URL || 'http://localhost:3001';
|
||||
const confirmation = 'If this email belongs to an eligible account, a sign-in link has been sent.';
|
||||
const invalidLink = 'This sign-in link is invalid or expired. Please request a new link.';
|
||||
|
||||
function mockSession(email: string) {
|
||||
const user = {
|
||||
id: '11111111-1111-4111-8111-111111111111',
|
||||
aud: 'authenticated', role: 'authenticated', email,
|
||||
app_metadata: {}, user_metadata: {}, created_at: '2026-01-01T00:00:00Z',
|
||||
};
|
||||
const payload = Buffer.from(JSON.stringify({ sub: user.id, exp: Math.floor(Date.now() / 1000) + 3600 })).toString('base64url');
|
||||
return { user, access_token: `eyJhbGciOiJIUzI1NiJ9.${payload}.test-signature`, refresh_token: 'mock-refresh-token', token_type: 'bearer', expires_in: 3600 };
|
||||
}
|
||||
|
||||
async function mockApi(page: Page, email = '[email protected]', isAdmin = false, password = 'personal-password') {
|
||||
const session = mockSession(email);
|
||||
const calls = { users: 0, exchanges: 0, logouts: 0, passwords: 0 };
|
||||
await page.route('**/auth/v1/**', async (route) => {
|
||||
const url = new URL(route.request().url());
|
||||
if (url.pathname.endsWith('/user')) {
|
||||
calls.users++;
|
||||
await route.fulfill({ json: session.user });
|
||||
} else if (url.pathname.endsWith('/token')) {
|
||||
if (url.searchParams.get('grant_type') === 'pkce') calls.exchanges++;
|
||||
if (url.searchParams.get('grant_type') === 'password') calls.passwords++;
|
||||
await route.fulfill({ json: session });
|
||||
} else if (url.pathname.endsWith('/logout')) {
|
||||
calls.logouts++;
|
||||
await route.fulfill({ status: 204 });
|
||||
} else {
|
||||
await route.fulfill({ json: {} });
|
||||
}
|
||||
});
|
||||
await page.route('**/rest/v1/**', async (route) => {
|
||||
const url = new URL(route.request().url());
|
||||
await route.fulfill({ json: url.pathname.endsWith('/contacts')
|
||||
? { email, full_name: 'Test Admin', is_admin: isAdmin, password }
|
||||
: [] });
|
||||
});
|
||||
return { session, calls };
|
||||
}
|
||||
|
||||
test.describe('Admin magic links', () => {
|
||||
test('pending send locks the recipient and failed resend clears stale confirmation', async ({ page }) => {
|
||||
await mockApi(page);
|
||||
await page.clock.install();
|
||||
let requestCount = 0;
|
||||
let releaseSend!: () => void;
|
||||
const pendingSend = new Promise<void>((resolve) => { releaseSend = resolve; });
|
||||
await page.route('**/auth/v1/otp**', async (route) => {
|
||||
requestCount++;
|
||||
if (requestCount === 1) {
|
||||
await pendingSend;
|
||||
await route.fulfill({ json: {} });
|
||||
} else {
|
||||
await route.fulfill({ status: 500, json: { msg: 'SMTP unavailable' } });
|
||||
}
|
||||
});
|
||||
await page.goto(adminUrl);
|
||||
await page.getByLabel('Email', { exact: true }).fill('[email protected]');
|
||||
await page.getByRole('button', { name: 'Send magic link', exact: true }).click();
|
||||
await expect(page.getByLabel('Email', { exact: true })).toBeDisabled();
|
||||
await expect(page.getByRole('button', { name: 'Sending...', exact: true })).toBeDisabled();
|
||||
releaseSend();
|
||||
await expect(page.locator('.login-form [role="status"]')).toHaveText(confirmation);
|
||||
await expect(page.getByLabel('Email', { exact: true })).toBeEnabled();
|
||||
await page.clock.runFor(60_000);
|
||||
await page.getByRole('button', { name: 'Resend magic link', exact: true }).click();
|
||||
await expect(page.getByRole('alert')).toHaveText('Unable to send a sign-in link right now. Please try again later.');
|
||||
await expect(page.locator('.login-form [role="status"]')).toHaveCount(0);
|
||||
await expect(page.getByRole('button', { name: 'Send magic link', exact: true })).toBeEnabled();
|
||||
await expect(page.getByText('SMTP unavailable')).toHaveCount(0);
|
||||
expect(requestCount).toBe(2);
|
||||
});
|
||||
|
||||
test('email-only sending, private confirmation, cooldown and resend', async ({ page }) => {
|
||||
await mockApi(page);
|
||||
await page.clock.install();
|
||||
let requestCount = 0;
|
||||
await page.route('**/auth/v1/otp**', async (route) => {
|
||||
requestCount++;
|
||||
expect(route.request().postDataJSON()).toMatchObject({ email: '[email protected]', create_user: false });
|
||||
expect(new URL(route.request().url()).searchParams.get('redirect_to')).toBe(`${adminUrl}/auth/callback`);
|
||||
await route.fulfill({ json: {} });
|
||||
});
|
||||
await page.goto(adminUrl);
|
||||
await expect(page.getByLabel('Password', { exact: true })).toHaveCount(0);
|
||||
await page.getByLabel('Email', { exact: true }).fill('[email protected]');
|
||||
await page.getByRole('button', { name: 'Send magic link', exact: true }).click();
|
||||
await expect(page.locator('.login-form [role="status"]')).toHaveText(confirmation);
|
||||
await expect(page.getByRole('button', { name: 'Resend in 60s' })).toBeDisabled();
|
||||
await page.clock.runFor(60_000);
|
||||
await page.getByRole('button', { name: 'Resend magic link', exact: true }).click();
|
||||
await expect(page.getByRole('button', { name: 'Resend in 60s' })).toBeDisabled();
|
||||
expect(requestCount).toBe(2);
|
||||
});
|
||||
|
||||
for (const status of [400, 422, 429, 500]) {
|
||||
test(`OTP status ${status} does not reveal account existence`, async ({ page }) => {
|
||||
await mockApi(page);
|
||||
await page.route('**/auth/v1/otp**', (route) => route.fulfill({ status, json: { msg: 'User not found', code: 'test_error' } }));
|
||||
await page.goto(adminUrl);
|
||||
await page.getByLabel('Email', { exact: true }).fill('[email protected]');
|
||||
await page.getByRole('button', { name: 'Send magic link', exact: true }).click();
|
||||
if (status < 429) await expect(page.locator('.login-form [role="status"]')).toHaveText(confirmation);
|
||||
else await expect(page.getByRole('alert')).toHaveText('Unable to send a sign-in link right now. Please try again later.');
|
||||
await expect(page.getByText('User not found')).toHaveCount(0);
|
||||
});
|
||||
}
|
||||
|
||||
for (const account of [
|
||||
{ email: '[email protected]', isAdmin: false, admitted: true },
|
||||
{ email: '[email protected]', isAdmin: true, admitted: true },
|
||||
{ email: '[email protected]', isAdmin: false, admitted: false },
|
||||
]) {
|
||||
test(`implicit callback applies admin gate for ${account.email}`, async ({ page }) => {
|
||||
const { session, calls } = await mockApi(page, account.email, account.isAdmin);
|
||||
await page.goto(`${adminUrl}/auth/callback?next=https://example.org#access_token=${session.access_token}&refresh_token=${session.refresh_token}&type=magiclink`);
|
||||
await expect(page).toHaveURL(`${adminUrl}/`);
|
||||
if (account.admitted) {
|
||||
await expect(page.getByRole('button', { name: 'Sign out', exact: true })).toBeVisible();
|
||||
await page.getByRole('button', { name: 'Sign out', exact: true }).click();
|
||||
await expect(page.getByRole('heading', { name: 'APPE Admin' })).toBeVisible();
|
||||
} else {
|
||||
await expect(page.getByRole('alert')).toHaveText('This account is not an admin.');
|
||||
await expect(page.getByRole('button', { name: 'Sign out', exact: true })).toHaveCount(0);
|
||||
expect(calls.logouts).toBe(1);
|
||||
expect(await page.evaluate(() => Object.keys(localStorage).filter((key) => key.endsWith('-auth-token')))).toEqual([]);
|
||||
}
|
||||
expect(calls.users).toBe(1);
|
||||
});
|
||||
}
|
||||
|
||||
test('code callback is exchanged once under StrictMode', async ({ page }) => {
|
||||
const { calls } = await mockApi(page);
|
||||
await page.goto(`${adminUrl}/auth/callback?code=mock-code&redirect_to=https://example.org`);
|
||||
await expect(page.getByRole('button', { name: 'Sign out', exact: true })).toBeVisible();
|
||||
await expect(page).toHaveURL(`${adminUrl}/`);
|
||||
expect(calls.exchanges).toBe(1);
|
||||
});
|
||||
|
||||
for (const suffix of [
|
||||
'#error=access_denied&error_code=otp_expired&error_description=Sensitive+server+detail',
|
||||
'?error=access_denied&error_code=otp_expired',
|
||||
'#access_token=incomplete',
|
||||
'',
|
||||
]) {
|
||||
test(`invalid callback is scrubbed and recoverable: ${suffix || 'empty'}`, async ({ page }) => {
|
||||
const { calls } = await mockApi(page);
|
||||
await page.goto(`${adminUrl}/auth/callback${suffix}`);
|
||||
await expect(page).toHaveURL(`${adminUrl}/`);
|
||||
await expect(page.getByRole('alert')).toHaveText(invalidLink);
|
||||
await expect(page.getByRole('button', { name: 'Send magic link', exact: true })).toBeVisible();
|
||||
expect(calls.users).toBe(0);
|
||||
expect(calls.exchanges).toBe(0);
|
||||
await expect(page.getByText('Sensitive server detail')).toHaveCount(0);
|
||||
});
|
||||
}
|
||||
|
||||
test('login has no password field or sign-in method selector', async ({ page }) => {
|
||||
const { calls } = await mockApi(page);
|
||||
await page.goto(adminUrl);
|
||||
await expect(page.getByLabel('Email', { exact: true })).toBeVisible();
|
||||
await expect(page.locator('input[type="password"]')).toHaveCount(0);
|
||||
await expect(page.getByRole('group', { name: 'Sign-in method' })).toHaveCount(0);
|
||||
await expect(page.getByRole('button', { name: 'Password', exact: true })).toHaveCount(0);
|
||||
await expect(page.getByRole('button', { name: 'Sign in', exact: true })).toHaveCount(0);
|
||||
await expect(page.getByRole('button', { name: 'Send magic link', exact: true })).toBeVisible();
|
||||
expect(calls.passwords).toBe(0);
|
||||
});
|
||||
|
||||
test('expired callback can recover by requesting a new magic link', async ({ page }) => {
|
||||
const { calls } = await mockApi(page);
|
||||
let requestCount = 0;
|
||||
await page.route('**/auth/v1/otp**', async (route) => {
|
||||
requestCount++;
|
||||
expect(route.request().postDataJSON()).toMatchObject({ email: '[email protected]', create_user: false });
|
||||
await route.fulfill({ json: {} });
|
||||
});
|
||||
await page.goto(`${adminUrl}/auth/callback#error=access_denied&error_code=otp_expired`);
|
||||
await expect(page.getByRole('alert')).toHaveText(invalidLink);
|
||||
await page.getByLabel('Email', { exact: true }).fill('[email protected]');
|
||||
await page.getByRole('button', { name: 'Send magic link', exact: true }).click();
|
||||
await expect(page.getByRole('alert')).toHaveCount(0);
|
||||
await expect(page.locator('.login-form [role="status"]')).toHaveText(confirmation);
|
||||
await expect(page.getByRole('button', { name: 'Resend in 60s' })).toBeDisabled();
|
||||
expect(requestCount).toBe(1);
|
||||
expect(calls.passwords).toBe(0);
|
||||
await expect(page).toHaveURL(`${adminUrl}/`);
|
||||
});
|
||||
|
||||
test('default-password contact has no change-password prompt on callback or session restore', async ({ page }) => {
|
||||
const { session, calls } = await mockApi(page, '[email protected]', false, 'appe-admin-2026');
|
||||
await page.goto(`${adminUrl}/auth/callback#access_token=${session.access_token}&refresh_token=${session.refresh_token}&type=magiclink`);
|
||||
await expect(page.getByRole('button', { name: 'Sign out', exact: true })).toBeVisible();
|
||||
await expect(page.getByRole('dialog')).toHaveCount(0);
|
||||
await expect(page.getByText('Change your password', { exact: true })).toHaveCount(0);
|
||||
await expect(page.locator('input[type="password"]')).toHaveCount(0);
|
||||
await page.reload();
|
||||
await expect(page.getByRole('button', { name: 'Sign out', exact: true })).toBeVisible();
|
||||
await expect(page.getByRole('dialog')).toHaveCount(0);
|
||||
await expect(page.getByText('Change your password', { exact: true })).toHaveCount(0);
|
||||
await expect(page.locator('input[type="password"]')).toHaveCount(0);
|
||||
expect(calls.passwords).toBe(0);
|
||||
});
|
||||
|
||||
test('rejected code exchange clears a previously stored local session', async ({ page }) => {
|
||||
const { session } = await mockApi(page);
|
||||
await page.goto(`${adminUrl}/auth/callback#access_token=${session.access_token}&refresh_token=${session.refresh_token}&type=magiclink`);
|
||||
await expect(page.getByRole('button', { name: 'Sign out', exact: true })).toBeVisible();
|
||||
await page.route('**/auth/v1/token**', (route) => route.fulfill({
|
||||
status: 400, json: { error: 'invalid_grant', error_description: 'Sensitive exchange detail' },
|
||||
}));
|
||||
await page.goto(`${adminUrl}/auth/callback?code=expired-code`);
|
||||
await expect(page.getByRole('alert')).toHaveText(invalidLink);
|
||||
await expect(page).toHaveURL(`${adminUrl}/`);
|
||||
await expect(page.getByRole('button', { name: 'Sign out', exact: true })).toHaveCount(0);
|
||||
expect(await page.evaluate(() => Object.keys(localStorage).filter((key) => key.endsWith('-auth-token')))).toEqual([]);
|
||||
await expect(page.getByText('Sensitive exchange detail')).toHaveCount(0);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,235 @@
|
||||
import { test, expect, type Page } from '@playwright/test';
|
||||
|
||||
const appUrl = process.env.CONVIVO_BASE_URL || 'http://localhost:3000';
|
||||
const portalUrl = `${appUrl}/speaker/secret`;
|
||||
const invalidLink = 'This sign-in link has expired or is invalid. Request a new link.';
|
||||
|
||||
function mockSession(email = '[email protected]') {
|
||||
const user = {
|
||||
id: '11111111-1111-4111-8111-111111111111',
|
||||
aud: 'authenticated', role: 'authenticated', email,
|
||||
app_metadata: {}, user_metadata: {}, created_at: '2026-01-01T00:00:00Z',
|
||||
};
|
||||
const payload = Buffer.from(JSON.stringify({ sub: user.id, exp: Math.floor(Date.now() / 1000) + 3600 })).toString('base64url');
|
||||
return { user, access_token: `eyJhbGciOiJIUzI1NiJ9.${payload}.test-signature`, refresh_token: 'mock-refresh-token', token_type: 'bearer', expires_in: 3600 };
|
||||
}
|
||||
|
||||
async function mockApi(page: Page, talks: Record<string, unknown>[] = [], email = '[email protected]') {
|
||||
const session = mockSession(email);
|
||||
const calls = { users: 0, exchanges: 0, portal: 0, unexpected: [] as string[] };
|
||||
await page.route('**/auth/v1/**', async (route) => {
|
||||
const url = new URL(route.request().url());
|
||||
if (url.pathname.endsWith('/user')) {
|
||||
calls.users++;
|
||||
await route.fulfill({ json: session.user });
|
||||
} else if (url.pathname.endsWith('/token')) {
|
||||
calls.exchanges++;
|
||||
await route.fulfill({ json: session });
|
||||
} else if (url.pathname.endsWith('/logout')) {
|
||||
await route.fulfill({ status: 204 });
|
||||
} else await route.fulfill({ json: {} });
|
||||
});
|
||||
await page.route('**/rest/v1/**', async (route) => {
|
||||
if (new URL(route.request().url()).pathname.endsWith('/rpc/get_my_speaker_sessions')) calls.portal++;
|
||||
else calls.unexpected.push(route.request().url());
|
||||
await route.fulfill({ json: talks });
|
||||
});
|
||||
return { session, calls };
|
||||
}
|
||||
|
||||
test.describe('Speaker portal', () => {
|
||||
const talkId = '22222222-2222-4222-8222-222222222222';
|
||||
const talk = {
|
||||
session_id: talkId, title: 'Past talk', description: null, room: 'Room A', material_path: null as string | null,
|
||||
event_id: '33333333-3333-4333-8333-333333333333', event_name: 'Past conference',
|
||||
event_start_date: '2020-01-01', event_end_date: '2020-01-01', is_active: false,
|
||||
slot_date: '2020-01-01', start_time: '09:00:00', end_time: '10:00:00',
|
||||
};
|
||||
|
||||
for (const { width, title } of [
|
||||
{ width: 1280, title: 'Past talk' }, { width: 390, title: 'Past talk' },
|
||||
{ width: 1280, title: 'Future talk' }, { width: 390, title: 'Future talk' },
|
||||
]) {
|
||||
test(`inactive ${title} materials can upload, replace and delete at ${width}px`, async ({ page }) => {
|
||||
await page.setViewportSize({ width, height: 844 });
|
||||
const talks = [{ ...talk }, { ...talk, session_id: '44444444-4444-4444-8444-444444444444', title: 'Future talk', event_name: 'Future conference', slot_date: '2099-01-01' }];
|
||||
const materialTalk = talks.find((entry) => entry.title === title)!;
|
||||
const materialId = materialTalk.session_id;
|
||||
const { session, calls } = await mockApi(page, talks);
|
||||
let materialPath: string | null = null;
|
||||
const uploaded: string[] = [];
|
||||
const removed: string[] = [];
|
||||
await page.route('**/rest/v1/sessions?**', (route) => route.fulfill({ json: { material_path: materialPath } }));
|
||||
await page.route('**/rest/v1/rpc/set_session_material', async (route) => {
|
||||
const body = route.request().postDataJSON();
|
||||
expect(body.p_session_id).toBe(materialId);
|
||||
materialPath = body.p_material_path;
|
||||
materialTalk.material_path = materialPath;
|
||||
await route.fulfill({ json: { material_path: materialPath } });
|
||||
});
|
||||
await page.route('**/storage/v1/object/materials/**', async (route) => {
|
||||
const path = decodeURIComponent(new URL(route.request().url()).pathname.split('/object/materials/')[1]);
|
||||
expect(path).toMatch(new RegExp(`^sessions/${materialId}/[a-f0-9-]+-slides\\.txt$`));
|
||||
uploaded.push(path);
|
||||
await route.fulfill({ json: { Key: `materials/${path}` } });
|
||||
});
|
||||
await page.route('**/storage/v1/object/materials', async (route) => {
|
||||
removed.push(...route.request().postDataJSON().prefixes);
|
||||
await route.fulfill({ json: [] });
|
||||
});
|
||||
await page.goto(`${portalUrl}#access_token=${session.access_token}&refresh_token=${session.refresh_token}`);
|
||||
const article = page.getByTestId(`speaker-talk-${materialId}`);
|
||||
await expect(page.getByText('Future talk', { exact: true })).toBeVisible();
|
||||
await expect(page.getByTestId('checkin-required-gate')).toHaveCount(0);
|
||||
await article.getByLabel(`Upload material for ${title}`).setInputFiles({ name: 'slides.txt', mimeType: 'text/plain', buffer: Buffer.from('First slides') });
|
||||
await expect(article.getByRole('link', { name: 'Download material' })).toBeVisible();
|
||||
const firstPath = materialPath;
|
||||
await article.getByLabel(`Replace material for ${title}`).setInputFiles({ name: 'slides.txt', mimeType: 'text/plain', buffer: Buffer.from('Replacement slides') });
|
||||
await expect.poll(() => uploaded.length).toBe(2);
|
||||
await expect(article.getByRole('button', { name: 'Remove material' })).toBeEnabled();
|
||||
expect(materialPath).not.toBe(firstPath);
|
||||
expect(removed).toEqual([firstPath]);
|
||||
await expect(article.getByRole('link', { name: 'Download material' })).toHaveAttribute('href', new RegExp(`${materialPath}$`));
|
||||
await page.screenshot({ path: `/tmp/convivo-speaker-${width}-${title.split(' ')[0]}.png`, fullPage: true });
|
||||
expect(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth)).toBe(true);
|
||||
page.once('dialog', (dialog) => dialog.accept());
|
||||
await article.getByRole('button', { name: 'Remove material' }).click();
|
||||
await expect(article.getByText('No material uploaded')).toBeVisible();
|
||||
expect(materialPath).toBeNull();
|
||||
expect(removed).toEqual(uploaded);
|
||||
expect(calls.unexpected).toEqual([]);
|
||||
});
|
||||
}
|
||||
|
||||
for (const email of ['[email protected]', '[email protected]']) {
|
||||
test(`assigned staff identity ${email} can manage talk material without a registration role gate`, async ({ page }) => {
|
||||
const materialTalk = { ...talk };
|
||||
const { session, calls } = await mockApi(page, [materialTalk], email);
|
||||
let materialPath: string | null = null;
|
||||
await page.route('**/rest/v1/sessions?**', (route) => route.fulfill({ json: { material_path: materialPath } }));
|
||||
await page.route('**/storage/v1/object/materials/**', (route) => route.fulfill({ json: { Key: 'uploaded' } }));
|
||||
await page.route('**/rest/v1/rpc/set_session_material', async (route) => {
|
||||
expect(route.request().postDataJSON().p_session_id).toBe(talkId);
|
||||
materialPath = route.request().postDataJSON().p_material_path;
|
||||
materialTalk.material_path = materialPath;
|
||||
await route.fulfill({ json: { material_path: materialPath } });
|
||||
});
|
||||
await page.goto(`${portalUrl}#access_token=${session.access_token}&refresh_token=${session.refresh_token}`);
|
||||
await expect(page.getByText(email, { exact: true })).toBeVisible();
|
||||
await page.getByLabel('Upload material for Past talk').setInputFiles({
|
||||
name: 'slides.txt', mimeType: 'text/plain', buffer: Buffer.from('Staff talk slides'),
|
||||
});
|
||||
await expect(page.getByRole('link', { name: 'Download material' })).toBeVisible();
|
||||
await expect(page.getByTestId('checkin-required-gate')).toHaveCount(0);
|
||||
expect(calls.unexpected).toEqual([]);
|
||||
});
|
||||
}
|
||||
|
||||
test('failed material attachment cleans up upload and re-enables controls', async ({ page }) => {
|
||||
const { session } = await mockApi(page, [{ ...talk }]);
|
||||
const removed: string[] = [];
|
||||
await page.route('**/rest/v1/sessions?**', (route) => route.fulfill({ json: { material_path: null } }));
|
||||
await page.route('**/storage/v1/object/materials/**', (route) => route.fulfill({ json: { Key: 'uploaded' } }));
|
||||
await page.route('**/rest/v1/rpc/set_session_material', (route) => route.fulfill({ status: 403, json: { message: 'Assignment removed', code: '42501' } }));
|
||||
await page.route('**/storage/v1/object/materials', async (route) => {
|
||||
removed.push(...route.request().postDataJSON().prefixes);
|
||||
await route.fulfill({ json: [] });
|
||||
});
|
||||
await page.goto(`${portalUrl}#access_token=${session.access_token}&refresh_token=${session.refresh_token}`);
|
||||
const input = page.getByLabel('Upload material for Past talk');
|
||||
await input.setInputFiles({ name: 'slides.txt', mimeType: 'text/plain', buffer: Buffer.from('Slides') });
|
||||
await expect(page.getByRole('alert')).toHaveText('Assignment removed');
|
||||
await expect(input).toBeEnabled();
|
||||
expect(removed).toHaveLength(1);
|
||||
await expect(page.getByRole('link', { name: 'Download material' })).toHaveCount(0);
|
||||
await input.setInputFiles({ name: 'bad.exe', mimeType: 'application/octet-stream', buffer: Buffer.from('Invalid') });
|
||||
await expect(page.getByRole('alert')).toHaveText(/Choose a non-empty PDF/);
|
||||
expect(removed).toHaveLength(1);
|
||||
});
|
||||
|
||||
test('portal authentication does not bypass the normal app check-in gate', async ({ page }) => {
|
||||
const { session } = await mockApi(page);
|
||||
await page.goto(`${portalUrl}#access_token=${session.access_token}&refresh_token=${session.refresh_token}`);
|
||||
await expect(page.getByRole('status')).toHaveText(/No assigned talks/);
|
||||
await page.route('**/rest/v1/contacts?**', (route) => route.fulfill({ json: { email: session.user.email, full_name: 'Speaker', is_admin: false } }));
|
||||
await page.route('**/rest/v1/registrations?**', (route) => route.fulfill({ json: { contact_email: session.user.email, type: 'speaker', checked_in: false, points: 37 } }));
|
||||
await page.goto(appUrl);
|
||||
await expect(page.getByTestId('checkin-required-gate')).toBeVisible();
|
||||
await expect(page.getByTestId('speaker-portal')).toHaveCount(0);
|
||||
});
|
||||
|
||||
for (const callback of ['implicit', 'pkce']) {
|
||||
test(`rejected ${callback} callback leaves no session and allows a new link`, async ({ page }) => {
|
||||
const { session } = await mockApi(page);
|
||||
const endpoint = callback === 'implicit' ? '**/auth/v1/user' : '**/auth/v1/token?**';
|
||||
await page.route(endpoint, (route) => route.fulfill({ status: 400, json: { msg: 'Sensitive server detail', code: 'test_error' } }));
|
||||
const suffix = callback === 'implicit'
|
||||
? `#access_token=${session.access_token}&refresh_token=${session.refresh_token}` : '?code=invalid-code';
|
||||
await page.goto(`${portalUrl}${suffix}`);
|
||||
await expect(page).toHaveURL(portalUrl);
|
||||
await expect(page.getByRole('alert')).toHaveText(callback === 'implicit' ? invalidLink
|
||||
: 'This sign-in link could not be opened on this device. Request a new link.');
|
||||
await expect(page.getByLabel('Email', { exact: true })).toBeVisible();
|
||||
await expect(page.getByRole('button', { name: 'Sign out', exact: true })).toHaveCount(0);
|
||||
expect(await page.evaluate(() => Object.keys(localStorage).filter((key) => key.endsWith('-auth-token')))).toEqual([]);
|
||||
});
|
||||
}
|
||||
|
||||
for (const path of ['/speaker/secret', '/speaker']) {
|
||||
test(`requests links for existing users only at ${path}`, async ({ page }) => {
|
||||
await mockApi(page);
|
||||
let requests = 0;
|
||||
await page.route('**/auth/v1/otp**', async (route) => {
|
||||
requests++;
|
||||
expect(route.request().postDataJSON()).toMatchObject({ email: '[email protected]', create_user: false });
|
||||
expect(new URL(route.request().url()).searchParams.get('redirect_to')).toBe(portalUrl);
|
||||
await route.fulfill({ json: {} });
|
||||
});
|
||||
await page.goto(`${appUrl}${path}`);
|
||||
await page.getByLabel('Email', { exact: true }).fill('[email protected]');
|
||||
await page.getByRole('button', { name: 'Send sign-in link', exact: true }).click();
|
||||
await expect(page.getByRole('status')).toHaveText('Sign-in link requested. Check your email.');
|
||||
expect(requests).toBe(1);
|
||||
await expect(page.getByTestId('checkin-required-gate')).toHaveCount(0);
|
||||
});
|
||||
}
|
||||
|
||||
for (const suffix of [
|
||||
'#error=access_denied&error_description=Sensitive+server+detail',
|
||||
'?error=access_denied&error_code=otp_expired',
|
||||
'#access_token=incomplete',
|
||||
]) {
|
||||
test(`callback error is scrubbed and recoverable: ${suffix}`, async ({ page }) => {
|
||||
const { calls } = await mockApi(page);
|
||||
await page.goto(`${portalUrl}${suffix}`);
|
||||
await expect(page).toHaveURL(portalUrl);
|
||||
await expect(page.getByRole('alert')).toHaveText(suffix.includes('incomplete')
|
||||
? 'Incomplete sign-in link. Request a new link.' : invalidLink);
|
||||
await expect(page.getByRole('button', { name: 'Send sign-in link', exact: true })).toBeVisible();
|
||||
await expect(page.getByText('Sensitive server detail')).toHaveCount(0);
|
||||
expect(calls.users).toBe(0);
|
||||
expect(calls.exchanges).toBe(0);
|
||||
});
|
||||
}
|
||||
|
||||
for (const callback of ['implicit', 'pkce']) {
|
||||
test(`${callback} callback is consumed once under StrictMode and empty access stays isolated`, async ({ page }) => {
|
||||
const { session, calls } = await mockApi(page);
|
||||
const suffix = callback === 'implicit'
|
||||
? `#access_token=${session.access_token}&refresh_token=${session.refresh_token}&type=magiclink`
|
||||
: '?code=mock-code&next=https://example.org';
|
||||
await page.goto(`${portalUrl}${suffix}`);
|
||||
await expect(page).toHaveURL(portalUrl);
|
||||
await expect(page.getByRole('status')).toHaveText(/No assigned talks/);
|
||||
expect(calls.users).toBe(callback === 'implicit' ? 1 : 0);
|
||||
expect(calls.exchanges).toBe(callback === 'pkce' ? 1 : 0);
|
||||
expect(calls.portal).toBeGreaterThan(0);
|
||||
expect(calls.unexpected).toEqual([]);
|
||||
await expect(page.locator('input[type="file"]')).toHaveCount(0);
|
||||
await expect(page.getByTestId('checkin-required-gate')).toHaveCount(0);
|
||||
await page.getByRole('button', { name: 'Sign out', exact: true }).click();
|
||||
await expect(page.getByLabel('Email', { exact: true })).toBeVisible();
|
||||
expect(await page.evaluate(() => Object.keys(localStorage).filter((key) => key.endsWith('-auth-token')))).toEqual([]);
|
||||
});
|
||||
}
|
||||
});
|
||||
+22
-12
@@ -160,7 +160,17 @@ site_url = "http://127.0.0.1:3000"
|
||||
# The public URL that Auth serves on. Defaults to the API external URL with `/auth/v1` appended.
|
||||
# external_url = ""
|
||||
# A list of *exact* URLs that auth providers are permitted to redirect to post authentication.
|
||||
additional_redirect_urls = ["https://127.0.0.1:3000"]
|
||||
additional_redirect_urls = [
|
||||
"https://127.0.0.1:3000",
|
||||
"http://localhost:3000",
|
||||
"http://127.0.0.1:3000",
|
||||
"http://localhost:3000/speaker",
|
||||
"http://localhost:3000/speaker/secret",
|
||||
"http://127.0.0.1:3000/speaker",
|
||||
"http://127.0.0.1:3000/speaker/secret",
|
||||
"http://localhost:3001/auth/callback",
|
||||
"http://127.0.0.1:3001/auth/callback",
|
||||
]
|
||||
# How long tokens are valid for, in seconds. Defaults to 3600 (1 hour), maximum 604,800 (1 week).
|
||||
jwt_expiry = 86400
|
||||
# JWT issuer URL. If not set, defaults to auth.external_url.
|
||||
@@ -196,7 +206,7 @@ password_requirements = ""
|
||||
|
||||
[auth.rate_limit]
|
||||
# Number of emails that can be sent per hour. Requires auth.email.smtp to be enabled.
|
||||
email_sent = 2
|
||||
email_sent = 100
|
||||
# Number of SMS messages that can be sent per hour. Requires auth.sms to be enabled.
|
||||
sms_sent = 30
|
||||
# Number of anonymous sign-ins that can be made per hour per IP address. Requires enable_anonymous_sign_ins = true.
|
||||
@@ -227,21 +237,21 @@ enable_confirmations = false
|
||||
# If enabled, users will need to reauthenticate or have logged in recently to change their password.
|
||||
secure_password_change = false
|
||||
# Controls the minimum amount of time that must pass before sending another signup confirmation or password reset email.
|
||||
max_frequency = "1s"
|
||||
max_frequency = "60s"
|
||||
# Number of characters used in the email OTP.
|
||||
otp_length = 6
|
||||
# Number of seconds before the email OTP expires (defaults to 1 hour).
|
||||
otp_expiry = 3600
|
||||
|
||||
# Use a production-ready SMTP server
|
||||
# [auth.email.smtp]
|
||||
# enabled = true
|
||||
# host = "smtp.sendgrid.net"
|
||||
# port = 587
|
||||
# user = "apikey"
|
||||
# pass = "env(SENDGRID_API_KEY)"
|
||||
# admin_email = "[email protected]"
|
||||
# sender_name = "Admin"
|
||||
# Local Auth explicitly opts into real email delivery; password stays in a private env file.
|
||||
[auth.email.smtp]
|
||||
enabled = true
|
||||
host = "heracles.mxrouting.net"
|
||||
port = 465
|
||||
user = "[email protected]"
|
||||
pass = "env(CONVIVO_SMTP_PASSWORD)"
|
||||
admin_email = "[email protected]"
|
||||
sender_name = "Convivo APP"
|
||||
|
||||
# Uncomment to customize email template
|
||||
# [auth.email.template.invite]
|
||||
|
||||
Whitespace-only changes.
@@ -0,0 +1,89 @@
|
||||
create or replace function public.owns_speaker_session(p_session_id uuid)
|
||||
returns boolean
|
||||
language sql stable security definer set search_path = '' as $$
|
||||
select public.current_email() is not null and exists (
|
||||
select 1
|
||||
from public.session_speakers assignment
|
||||
join public.sessions talk on talk.id = assignment.session_id
|
||||
join public.slots slot on slot.id = talk.slot_id and slot.event_id = talk.event_id
|
||||
join public.registrations registration
|
||||
on registration.event_id = talk.event_id
|
||||
and registration.contact_email = assignment.contact_email
|
||||
where assignment.session_id = p_session_id
|
||||
and assignment.contact_email = public.current_email()
|
||||
and registration.type = 'speaker'
|
||||
and slot.type = 'session'
|
||||
);
|
||||
$$;
|
||||
|
||||
create or replace function public.can_write_session_material(p_path text)
|
||||
returns boolean
|
||||
language plpgsql stable security definer set search_path = '' as $$
|
||||
begin
|
||||
if public.current_email() is null then return false; end if;
|
||||
if public.is_admin() then return true; end if;
|
||||
if p_path is null or p_path !~ '^sessions/[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}/[^/]+$' then
|
||||
return false;
|
||||
end if;
|
||||
return public.owns_speaker_session(split_part(p_path, '/', 2)::uuid);
|
||||
end;
|
||||
$$;
|
||||
|
||||
create or replace function public.get_my_speaker_sessions()
|
||||
returns table (
|
||||
session_id uuid, title text, description text, room text, material_path text,
|
||||
event_id uuid, event_name text, event_start_date date, event_end_date date,
|
||||
is_active boolean, slot_date date, start_time time, end_time time
|
||||
)
|
||||
language sql stable security definer set search_path = '' as $$
|
||||
select talk.id, talk.title, talk.description, talk.room, talk.material_path,
|
||||
event.id, event.name, event.start_date, event.end_date, event.is_active,
|
||||
slot.slot_date, slot.start_time, slot.end_time
|
||||
from public.sessions talk
|
||||
join public.events event on event.id = talk.event_id
|
||||
join public.slots slot on slot.id = talk.slot_id
|
||||
where public.owns_speaker_session(talk.id)
|
||||
order by slot.slot_date, slot.start_time, event.name, talk.title, talk.id;
|
||||
$$;
|
||||
|
||||
create or replace function public.set_session_material(p_session_id uuid, p_material_path text)
|
||||
returns public.sessions
|
||||
language plpgsql security definer set search_path = '' as $$
|
||||
declare
|
||||
result public.sessions;
|
||||
begin
|
||||
if public.current_email() is null then raise exception 'not authenticated' using errcode = '42501'; end if;
|
||||
select * into result from public.sessions where id = p_session_id for update;
|
||||
if not found then raise exception 'session not found'; end if;
|
||||
if not (public.is_admin() or public.owns_speaker_session(p_session_id)) then
|
||||
raise exception 'not a registered speaker of this session' using errcode = '42501';
|
||||
end if;
|
||||
if p_material_path is not null and not public.is_admin() then
|
||||
if not public.can_write_session_material(p_material_path)
|
||||
or split_part(p_material_path, '/', 2) <> p_session_id::text
|
||||
or not exists (select 1 from storage.objects where bucket_id = 'materials' and name = p_material_path) then
|
||||
raise exception 'material must be an uploaded object for this session' using errcode = '42501';
|
||||
end if;
|
||||
end if;
|
||||
update public.sessions set material_path = p_material_path
|
||||
where id = p_session_id returning * into result;
|
||||
return result;
|
||||
end;
|
||||
$$;
|
||||
|
||||
drop policy if exists "materials_write" on storage.objects;
|
||||
drop policy if exists "materials_update" on storage.objects;
|
||||
drop policy if exists "materials_delete" on storage.objects;
|
||||
create policy "materials_write" on storage.objects for insert to authenticated
|
||||
with check (bucket_id = 'materials' and public.can_write_session_material(name));
|
||||
create policy "materials_update" on storage.objects for update to authenticated
|
||||
using (bucket_id = 'materials' and public.can_write_session_material(name))
|
||||
with check (bucket_id = 'materials' and public.can_write_session_material(name));
|
||||
create policy "materials_delete" on storage.objects for delete to authenticated
|
||||
using (bucket_id = 'materials' and public.can_write_session_material(name));
|
||||
|
||||
revoke all on function public.owns_speaker_session(uuid), public.can_write_session_material(text),
|
||||
public.get_my_speaker_sessions(), public.set_session_material(uuid, text) from public, anon;
|
||||
grant execute on function public.owns_speaker_session(uuid), public.can_write_session_material(text),
|
||||
public.get_my_speaker_sessions(), public.set_session_material(uuid, text) to authenticated, service_role;
|
||||
notify pgrst, 'reload schema';
|
||||
@@ -0,0 +1,21 @@
|
||||
create or replace function public.owns_speaker_session(p_session_id uuid)
|
||||
returns boolean
|
||||
language sql stable security definer set search_path = '' as $$
|
||||
select public.current_email() is not null and exists (
|
||||
select 1
|
||||
from public.session_speakers assignment
|
||||
join public.sessions talk on talk.id = assignment.session_id
|
||||
join public.slots slot on slot.id = talk.slot_id and slot.event_id = talk.event_id
|
||||
join public.registrations registration
|
||||
on registration.event_id = talk.event_id
|
||||
and registration.contact_email = assignment.contact_email
|
||||
where assignment.session_id = p_session_id
|
||||
and assignment.contact_email = public.current_email()
|
||||
and registration.type in ('speaker', 'staff')
|
||||
and slot.type = 'session'
|
||||
);
|
||||
$$;
|
||||
|
||||
revoke all on function public.owns_speaker_session(uuid) from public, anon;
|
||||
grant execute on function public.owns_speaker_session(uuid) to authenticated, service_role;
|
||||
notify pgrst, 'reload schema';
|
||||
@@ -0,0 +1,245 @@
|
||||
\set ON_ERROR_STOP on
|
||||
begin;
|
||||
set local storage.allow_delete_query = 'true';
|
||||
|
||||
create function pg_temp.assert_speaker(p_condition boolean, p_name text)
|
||||
returns void language plpgsql as $$
|
||||
begin
|
||||
if p_condition is distinct from true then
|
||||
raise exception 'FAIL: %', p_name;
|
||||
end if;
|
||||
raise notice 'PASS: %', p_name;
|
||||
end;
|
||||
$$;
|
||||
|
||||
create function pg_temp.expect_speaker_denied(p_statement text, p_name text)
|
||||
returns void language plpgsql as $$
|
||||
begin
|
||||
begin
|
||||
execute p_statement;
|
||||
exception when insufficient_privilege then
|
||||
raise notice 'PASS: %', p_name;
|
||||
return;
|
||||
end;
|
||||
raise exception 'FAIL: % was allowed', p_name;
|
||||
end;
|
||||
$$;
|
||||
|
||||
create temporary table speaker_fixture as
|
||||
select kind, gen_random_uuid() as event_id, gen_random_uuid() as session_id,
|
||||
(select least(coalesce(min(id), 0), 0) from public.slots) - row_number() over ()::integer as slot_id,
|
||||
case when kind like '%future' then current_date + 365 else current_date - 365 end as event_date
|
||||
from unnest(array['past', 'future', 'active', 'other', 'service', 'attendee', 'unregistered',
|
||||
'staff_past', 'staff_future', 'staff_active', 'unassigned_staff', 'wrong_event_staff',
|
||||
'admin_past', 'admin_future', 'admin_active', 'admin_service']) as kind;
|
||||
create temporary table speaker_identity as
|
||||
select 'portal-owner-' || gen_random_uuid() || '@example.invalid' as owner_email,
|
||||
'portal-other-' || gen_random_uuid() || '@example.invalid' as other_email,
|
||||
'portal-admin-' || gen_random_uuid() || '@appe.at' as admin_email;
|
||||
grant select on speaker_fixture, speaker_identity to authenticated;
|
||||
|
||||
insert into public.contacts(email, full_name)
|
||||
select owner_email, 'Portal Owner' from speaker_identity
|
||||
union all select other_email, 'Other Speaker' from speaker_identity
|
||||
union all select admin_email, 'Portal Admin' from speaker_identity;
|
||||
insert into public.events(id, name, start_date, end_date, is_active)
|
||||
select event_id, 'Portal regression ' || kind, event_date, event_date, false from speaker_fixture;
|
||||
insert into public.slots(id, event_id, name, type, slot_date, start_time, end_time)
|
||||
select slot_id, event_id, 'Portal slot',
|
||||
(case when kind in ('service', 'admin_service') then 'service_session' else 'session' end)::public.slot_type,
|
||||
event_date, '09:00', '10:00' from speaker_fixture;
|
||||
insert into public.sessions(id, event_id, slot_id, title)
|
||||
select session_id, event_id, slot_id, 'Portal talk ' || kind from speaker_fixture;
|
||||
insert into public.registrations(event_id, contact_email, type, points, checked_in)
|
||||
select event_id, case when kind in ('other', 'wrong_event_staff') then other_email
|
||||
when kind like 'admin_%' then admin_email else owner_email end,
|
||||
(case when kind like 'staff_%' or kind in ('service', 'unassigned_staff', 'wrong_event_staff')
|
||||
then 'staff' else 'speaker' end)::public.registration_type, 37, false
|
||||
from speaker_fixture cross join speaker_identity where kind <> 'unregistered';
|
||||
insert into public.session_speakers(session_id, contact_email)
|
||||
select session_id, case when kind in ('other', 'unassigned_staff') then other_email
|
||||
when kind like 'admin_%' then admin_email else owner_email end
|
||||
from speaker_fixture cross join speaker_identity where kind not in ('service', 'admin_service');
|
||||
select public._assign_service_session_speakers(session_id, event_id)
|
||||
from speaker_fixture where kind in ('service', 'admin_service');
|
||||
update public.registrations set type = 'attendee'
|
||||
where event_id = (select event_id from speaker_fixture where kind = 'attendee');
|
||||
update public.events set is_active = false where is_active;
|
||||
update public.events set is_active = true
|
||||
where id = (select event_id from speaker_fixture where kind = 'active');
|
||||
|
||||
create temporary table speaker_registration_before as
|
||||
select registration.* from public.registrations registration join speaker_fixture using (event_id);
|
||||
create temporary table speaker_points_before as select * from public.points_log;
|
||||
create temporary table speaker_checkins_before as select * from public.checkins;
|
||||
create temporary table speaker_leaderboard_before as select * from public.leaderboard;
|
||||
|
||||
select pg_temp.assert_speaker(not has_function_privilege('anon', 'public.get_my_speaker_sessions()', 'execute'), 'anonymous portal RPC revoked');
|
||||
select pg_temp.assert_speaker(not has_function_privilege('anon', 'public.set_session_material(uuid,text)', 'execute'), 'anonymous material RPC revoked');
|
||||
|
||||
select set_config('request.jwt.claims', json_build_object('email', owner_email, 'role', 'authenticated')::text, true)
|
||||
from speaker_identity;
|
||||
set local role authenticated;
|
||||
|
||||
select pg_temp.assert_speaker(
|
||||
(select count(*) = 6 from public.get_my_speaker_sessions()),
|
||||
'only own registered non-service talks across active, past and future events');
|
||||
select pg_temp.assert_speaker(
|
||||
(select count(*) = 5 from public.get_my_speaker_sessions() where not is_active),
|
||||
'inactive events remain accessible without physical check-in');
|
||||
select pg_temp.assert_speaker(not public.is_admin(), 'staff material restrictions tested without Admin privileges');
|
||||
reset role;
|
||||
update public.events set is_active = false where is_active;
|
||||
update public.events set is_active = true
|
||||
where id = (select event_id from speaker_fixture where kind = 'staff_active');
|
||||
set local role authenticated;
|
||||
select pg_temp.assert_speaker(
|
||||
(select count(*) = 1 from public.get_my_speaker_sessions() where is_active),
|
||||
'assigned non-admin staff can access an active-event talk without check-in');
|
||||
select pg_temp.assert_speaker(
|
||||
not public.can_write_session_material(path), 'reject malformed path: ' || coalesce(path, 'NULL'))
|
||||
from unnest(array[null, '', 'sessions/not-a-uuid/slides.pdf', 'foreign/slides.pdf',
|
||||
'sessions/' || (select session_id from speaker_fixture where kind = 'past') || '/',
|
||||
'sessions/' || (select session_id from speaker_fixture where kind = 'past') || '/nested/slides.pdf']) as path;
|
||||
select pg_temp.expect_speaker_denied(
|
||||
format('insert into storage.objects(bucket_id,name) values (''materials'',%L)', path),
|
||||
'malformed storage insert denied: ' || path)
|
||||
from unnest(array['sessions/not-a-uuid/slides.pdf', 'foreign/slides.pdf',
|
||||
'sessions/' || (select session_id from speaker_fixture where kind = 'past') || '/nested/slides.pdf']) as path;
|
||||
|
||||
do $$
|
||||
declare
|
||||
fixture record;
|
||||
material text;
|
||||
affected integer;
|
||||
begin
|
||||
for fixture in select * from speaker_fixture where kind in ('past', 'future', 'active', 'staff_past', 'staff_future', 'staff_active') loop
|
||||
material := 'sessions/' || fixture.session_id || '/slides.pdf';
|
||||
perform pg_temp.assert_speaker(public.owns_speaker_session(fixture.session_id), 'ownership: ' || fixture.kind);
|
||||
perform pg_temp.expect_speaker_denied(
|
||||
format('select public.set_session_material(%L::uuid, %L)', fixture.session_id, material),
|
||||
'nonexistent object cannot be attached: ' || fixture.kind);
|
||||
insert into storage.objects(bucket_id, name, metadata)
|
||||
values ('materials', material, '{"version":1}');
|
||||
perform public.set_session_material(fixture.session_id, material);
|
||||
perform pg_temp.assert_speaker(
|
||||
(select material_path = material from public.sessions where id = fixture.session_id),
|
||||
'upload attached: ' || fixture.kind);
|
||||
update storage.objects set metadata = '{"version":2}' where bucket_id = 'materials' and name = material;
|
||||
get diagnostics affected = row_count;
|
||||
perform pg_temp.assert_speaker(affected = 1, 'storage replacement allowed: ' || fixture.kind);
|
||||
insert into storage.objects(bucket_id, name) values ('materials', replace(material, 'slides.pdf', 'replacement.pdf'));
|
||||
perform public.set_session_material(fixture.session_id, replace(material, 'slides.pdf', 'replacement.pdf'));
|
||||
perform pg_temp.assert_speaker(
|
||||
(select material_path = replace(material, 'slides.pdf', 'replacement.pdf') from public.sessions where id = fixture.session_id),
|
||||
'replacement attached: ' || fixture.kind);
|
||||
perform pg_temp.expect_speaker_denied(
|
||||
format('update storage.objects set name = %L where bucket_id = ''materials'' and name = %L',
|
||||
'sessions/' || (select session_id from speaker_fixture where kind = 'other') || '/stolen.pdf', material),
|
||||
'UPDATE WITH CHECK prevents reassignment: ' || fixture.kind);
|
||||
perform public.set_session_material(fixture.session_id, null);
|
||||
delete from storage.objects where bucket_id = 'materials'
|
||||
and name in (material, replace(material, 'slides.pdf', 'replacement.pdf'));
|
||||
get diagnostics affected = row_count;
|
||||
perform pg_temp.assert_speaker(affected = 2, 'storage delete allowed: ' || fixture.kind);
|
||||
end loop;
|
||||
for fixture in select * from speaker_fixture where kind in ('other', 'service', 'attendee', 'unregistered', 'unassigned_staff', 'wrong_event_staff', 'admin_past') loop
|
||||
material := 'sessions/' || fixture.session_id || '/slides.pdf';
|
||||
perform pg_temp.assert_speaker(not public.owns_speaker_session(fixture.session_id), 'ownership denied: ' || fixture.kind);
|
||||
perform pg_temp.assert_speaker(not public.can_write_session_material(material), 'storage ownership denied: ' || fixture.kind);
|
||||
perform pg_temp.expect_speaker_denied(
|
||||
format('insert into storage.objects(bucket_id,name) values (''materials'',%L)', material),
|
||||
'storage insert denied: ' || fixture.kind);
|
||||
perform pg_temp.expect_speaker_denied(
|
||||
format('select public.set_session_material(%L::uuid,null)', fixture.session_id),
|
||||
'material detach denied: ' || fixture.kind);
|
||||
end loop;
|
||||
perform pg_temp.expect_speaker_denied(
|
||||
format('select public.set_session_material(%L::uuid,%L)',
|
||||
(select session_id from speaker_fixture where kind = 'past'),
|
||||
'sessions/' || (select session_id from speaker_fixture where kind = 'future') || '/slides.pdf'),
|
||||
'another owned session path cannot be attached');
|
||||
end;
|
||||
$$;
|
||||
|
||||
reset role;
|
||||
insert into storage.objects(bucket_id, name)
|
||||
select 'materials', 'sessions/' || session_id || '/foreign.pdf'
|
||||
from speaker_fixture where kind = 'other';
|
||||
set local role authenticated;
|
||||
do $$
|
||||
declare affected integer;
|
||||
begin
|
||||
update storage.objects set metadata = '{"changed":true}'
|
||||
where bucket_id = 'materials' and name = 'sessions/' || (select session_id from speaker_fixture where kind = 'other') || '/foreign.pdf';
|
||||
get diagnostics affected = row_count;
|
||||
perform pg_temp.assert_speaker(affected = 0, 'foreign storage update denied');
|
||||
delete from storage.objects
|
||||
where bucket_id = 'materials' and name = 'sessions/' || (select session_id from speaker_fixture where kind = 'other') || '/foreign.pdf';
|
||||
get diagnostics affected = row_count;
|
||||
perform pg_temp.assert_speaker(affected = 0, 'foreign storage delete denied');
|
||||
end;
|
||||
$$;
|
||||
|
||||
select set_config('request.jwt.claims', json_build_object('email', other_email, 'role', 'authenticated')::text, true)
|
||||
from speaker_identity;
|
||||
select pg_temp.assert_speaker(
|
||||
(select count(*) = 1 from public.get_my_speaker_sessions()), 'other speaker sees only own assignment');
|
||||
reset role;
|
||||
update public.registrations set type = 'attendee'
|
||||
where event_id = (select event_id from speaker_fixture where kind = 'other');
|
||||
set local role authenticated;
|
||||
select pg_temp.assert_speaker(
|
||||
not exists (select 1 from public.get_my_speaker_sessions()), 'attendee with assignment has empty access');
|
||||
reset role;
|
||||
update public.registrations set type = 'speaker'
|
||||
where event_id = (select event_id from speaker_fixture where kind = 'other');
|
||||
|
||||
select set_config('request.jwt.claims', '{"role":"authenticated"}', true);
|
||||
set local role authenticated;
|
||||
select pg_temp.assert_speaker(
|
||||
not exists (select 1 from public.get_my_speaker_sessions()), 'missing identity has empty access');
|
||||
select pg_temp.expect_speaker_denied(
|
||||
format('select public.set_session_material(%L::uuid,null)',
|
||||
(select session_id from speaker_fixture where kind = 'past')), 'missing identity cannot detach material');
|
||||
reset role;
|
||||
|
||||
select set_config('request.jwt.claims', json_build_object('email', admin_email, 'role', 'authenticated')::text, true)
|
||||
from speaker_identity;
|
||||
update public.events set is_active = false where is_active;
|
||||
update public.events set is_active = true
|
||||
where id = (select event_id from speaker_fixture where kind = 'admin_active');
|
||||
set local role authenticated;
|
||||
select pg_temp.assert_speaker(public.is_admin(), 'assigned Admin retains Admin access');
|
||||
select pg_temp.assert_speaker(
|
||||
(select count(*) = 3 from public.get_my_speaker_sessions()), 'Admin portal lists only own assigned talks across event dates');
|
||||
select pg_temp.assert_speaker(
|
||||
(select count(*) = 1 from public.get_my_speaker_sessions() where is_active),
|
||||
'assigned Admin staff can access an active-event talk without check-in');
|
||||
select pg_temp.assert_speaker(
|
||||
public.owns_speaker_session(session_id), 'Admin staff owns assigned talk: ' || kind)
|
||||
from speaker_fixture where kind in ('admin_past', 'admin_future', 'admin_active');
|
||||
select pg_temp.assert_speaker(
|
||||
not public.owns_speaker_session(session_id), 'Admin portal ownership denied: ' || kind)
|
||||
from speaker_fixture where kind in ('admin_service', 'other');
|
||||
select pg_temp.assert_speaker(
|
||||
public.can_write_session_material('sessions/' || session_id || '/admin.pdf'), 'Admin global material permission preserved')
|
||||
from speaker_fixture where kind = 'other';
|
||||
select public.set_session_material(session_id, null)
|
||||
from speaker_fixture where kind = 'other';
|
||||
reset role;
|
||||
|
||||
select pg_temp.assert_speaker(
|
||||
not exists (select * from speaker_registration_before except select registration.* from public.registrations registration join speaker_fixture using (event_id))
|
||||
and not exists (select registration.* from public.registrations registration join speaker_fixture using (event_id) except select * from speaker_registration_before),
|
||||
'registrations, points, QR tokens and physical check-in unchanged');
|
||||
select pg_temp.assert_speaker(
|
||||
not exists (select * from public.points_log except select * from speaker_points_before)
|
||||
and not exists (select * from speaker_points_before except select * from public.points_log), 'no points-log mutation');
|
||||
select pg_temp.assert_speaker(
|
||||
not exists (select * from public.checkins except select * from speaker_checkins_before)
|
||||
and not exists (select * from speaker_checkins_before except select * from public.checkins), 'no check-in mutation');
|
||||
select pg_temp.assert_speaker(
|
||||
not exists (select * from public.leaderboard except select * from speaker_leaderboard_before)
|
||||
and not exists (select * from speaker_leaderboard_before except select * from public.leaderboard), 'no leaderboard mutation');
|
||||
rollback;
|
||||
Reference in new issue
Block a user