61 lines
1.3 KiB
TypeScript
61 lines
1.3 KiB
TypeScript
'use client';
|
|
|
|
import { useEffect, useRef } from 'react';
|
|
|
|
const HANDOFF_TIMEOUT_MS = 10_000;
|
|
|
|
type AuthSession = {
|
|
user?: {
|
|
id?: string;
|
|
};
|
|
} | null;
|
|
|
|
type UseAuthHandoffOptions = {
|
|
nextPath: string;
|
|
session: AuthSession;
|
|
isPending: boolean;
|
|
awaitingSession: boolean;
|
|
onTimeout: () => void;
|
|
};
|
|
|
|
export function useAuthHandoff({
|
|
nextPath,
|
|
session,
|
|
isPending,
|
|
awaitingSession,
|
|
onTimeout
|
|
}: UseAuthHandoffOptions) {
|
|
const hasNavigatedRef = useRef(false);
|
|
const hasSession = Boolean(session?.user?.id);
|
|
|
|
useEffect(() => {
|
|
if (typeof window === 'undefined' || isPending || !hasSession || hasNavigatedRef.current) {
|
|
return;
|
|
}
|
|
|
|
hasNavigatedRef.current = true;
|
|
window.location.replace(nextPath);
|
|
}, [hasSession, isPending, nextPath]);
|
|
|
|
useEffect(() => {
|
|
if (typeof window === 'undefined' || !awaitingSession || hasSession || hasNavigatedRef.current) {
|
|
return;
|
|
}
|
|
|
|
const timeoutId = window.setTimeout(() => {
|
|
onTimeout();
|
|
}, HANDOFF_TIMEOUT_MS);
|
|
|
|
return () => {
|
|
window.clearTimeout(timeoutId);
|
|
};
|
|
}, [awaitingSession, hasSession, onTimeout]);
|
|
|
|
return {
|
|
isHandingOff: awaitingSession || (!isPending && hasSession),
|
|
statusText: awaitingSession
|
|
? 'Establishing your session and opening the workspace...'
|
|
: null
|
|
};
|
|
}
|