import type { Session } from '@supabase/supabase-js'; import { supabase } from './supabase'; import { getMyContact, getMyRegistration } from './api'; import type { Contact, Registration } from './types'; export const invalidAdminLink = 'This sign-in link is invalid or expired. Please request a new link.'; export const adminLinkNotice = 'If this email belongs to an eligible admin account, a sign-in link has been sent.'; export const adminLinkFailure = 'Unable to send a sign-in link right now. Please try again later.'; export function isEmailEntry(value: string): boolean { return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value.trim()); } export async function requestAdminLink(email: string): Promise { const normalizedEmail = email.trim().toLowerCase(); const { data: eligible, error: eligibilityError } = await supabase.rpc('can_request_admin_magic_link', { p_email: normalizedEmail }); if (eligibilityError) throw new Error(adminLinkFailure); if (eligible !== true) return; const { error } = await supabase.auth.signInWithOtp({ email: normalizedEmail, options: { shouldCreateUser: false, emailRedirectTo: `${window.location.origin}/auth/callback` }, }); if (error && error.status !== 400 && error.status !== 422) throw new Error(adminLinkFailure); } const entryUrl = new URL(window.location.href); const entryHash = new URLSearchParams(entryUrl.hash.slice(1)); export const hasAdminCallback = entryUrl.pathname === '/auth/callback' || (entryUrl.pathname === '/' && ['access_token', 'refresh_token', 'error', 'error_code'].some((key) => entryHash.has(key))) || (entryUrl.pathname === '/' && ['code', 'error', 'error_code'].some((key) => entryUrl.searchParams.has(key))); if (hasAdminCallback) window.history.replaceState(null, '', '/'); export let adminCallbackPending = hasAdminCallback; export interface EntryProfile { session: Session | null; contact: Contact | null; registration: Registration | null; error: string | null; } export async function loadEntryProfile(session: Session, adminOnly = false): Promise { const { data: verified, error: userError } = await supabase.auth.getUser(session.access_token); if (userError || !verified.user?.email || verified.user.id !== session.user.id) throw new Error(invalidAdminLink); const { data: isAdmin, error: adminError } = await supabase.rpc('is_admin'); if (adminError) throw new Error(invalidAdminLink); if (adminOnly && isAdmin !== true) throw new Error('This account is not an admin.'); const [contact, registration] = await Promise.all([ getMyContact(verified.user.email), getMyRegistration(verified.user.email), ]); if (!contact) throw new Error(invalidAdminLink); return { session: { ...session, user: verified.user }, contact: { ...contact, is_admin: isAdmin === true }, registration, error: null }; } let callbackResult: Promise | null = null; export function consumeAdminCallback(): Promise { if (!callbackResult) callbackResult = (async () => { try { if (['error', 'error_code'].some((key) => entryHash.has(key) || entryUrl.searchParams.has(key))) throw new Error(invalidAdminLink); const accessToken = entryHash.get('access_token'); const refreshToken = entryHash.get('refresh_token'); const code = entryUrl.searchParams.get('code'); const result = accessToken && refreshToken ? await supabase.auth.setSession({ access_token: accessToken, refresh_token: refreshToken }) : code && !accessToken && !refreshToken ? await supabase.auth.exchangeCodeForSession(code) : null; if (!result || result.error || !result.data.session) throw new Error(invalidAdminLink); return await loadEntryProfile(result.data.session, true); } catch (failure) { await supabase.auth.signOut({ scope: 'local' }).catch(() => {}); return { session: null, contact: null, registration: null, error: failure instanceof Error && failure.message === 'This account is not an admin.' ? failure.message : invalidAdminLink }; } finally { adminCallbackPending = false; } })(); return callbackResult; }