Fix post-auth session handoff flow
This commit is contained in:
60
hooks/use-auth-handoff.ts
Normal file
60
hooks/use-auth-handoff.ts
Normal file
@@ -0,0 +1,60 @@
|
||||
'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
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user