Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 | 1x 12x 3x 1x 1x 12x 12x 12x 12x 12x 2x | import { useMutation, useQuery } from '@tanstack/react-query'
import type { ReactElement } from 'react'
import { ApiRequestError } from '@/lib/api'
import { BrokerError, completeBroker, getBrokerTarget, startBroker } from '../../lib/session'
import { SignInScreen } from '../SignInScreen'
interface SignInBrokerPageProps {
/** The preview's sign-in page to send Google's ID token back to (`?return=`). */
returnUrl: string | null
/** The preview's random state, echoed back so it takes only its own hand-off (`?state=`). */
state: string | null
}
const BROKER_RESULT_KEY = ['auth', 'broker-result'] as const
function getErrorCode(error: Error | null): string | null {
if (!error) return null
if (error instanceof BrokerError || error instanceof ApiRequestError) return error.code
return 'sign_in_failed'
}
// On the dev site: signs in for a branch preview, whose own host Firebase and Google do not know.
// It waits for a click that names the preview, so a link alone never sends a token anywhere.
export const SignInBrokerPage = ({ returnUrl, state }: SignInBrokerPageProps): ReactElement => {
const result = useQuery({
queryKey: BROKER_RESULT_KEY,
queryFn: completeBroker,
retry: false,
staleTime: Infinity,
})
// Navigates away to Google, so it stays pending until the page unloads.
const start = useMutation({ mutationFn: () => startBroker(returnUrl, state) })
const error = result.error ?? start.error
const target = getBrokerTarget(returnUrl)
return (
<SignInScreen
isBusy={!error && (result.isPending || result.data === true || start.isPending)}
errorCode={getErrorCode(error)}
requestId={error instanceof ApiRequestError ? error.requestId : null}
description={target ? `Signing in for the preview ${target}.` : undefined}
onSignInClick={() => start.mutate()}
/>
)
}
|