Files
Convivo/apps/convivo/src/lib/speakerPortal.ts
T

56 lines
2.3 KiB
TypeScript

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[];
}