All files / apps / web/src / features / auth / components / SignInPage index.tsx

100% Statements 16/16
100% Branches 20/20
100% Functions 4/4
100% Lines 14/14

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 49 50 51 52 53                                  1x   1x 16x     7x 3x   3x           16x   16x 16x 16x     16x 2x     14x         1x        
import { AUTH_ERROR_CODE } from '@chattra/shared'
import { useMutation, useQuery } from '@tanstack/react-query'
import type { ReactElement } from 'react'
import { ApiRequestError } from '@/lib/api'
import { getSignInErrorCode } from '../../lib/errors'
import { completeSignIn, startSignIn } from '../../lib/session'
import { SignInRefused } from '../SignInRefused'
import { SignInScreen } from '../SignInScreen'
 
interface SignInPageProps {
  /** Called once the session is open; the route then goes where the person was headed. */
  onSignedIn: () => void
  /** Why the app sent the person here (an API error code from ?reason=), shown until they act. */
  reason?: string | null
}
 
// One result per page load: Google sends the browser back here, and the redirect is read once.
const REDIRECT_RESULT_KEY = ['auth', 'redirect-result'] as const
 
export const SignInPage = ({ onSignedIn, reason = null }: SignInPageProps): ReactElement => {
  const result = useQuery({
    queryKey: REDIRECT_RESULT_KEY,
    queryFn: async () => {
      const isSignedIn = await completeSignIn()
      if (isSignedIn) onSignedIn()
 
      return isSignedIn
    },
    retry: false,
    staleTime: Infinity,
  })
  // Navigates away to Google, so it stays pending until the page unloads.
  const start = useMutation({ mutationFn: startSignIn })
 
  const error = result.error ?? start.error
  const errorCode = error ? getSignInErrorCode(error) : null
  const isBusy = result.isPending || result.data === true || start.isPending
 
  // A Google account outside the allowed domains gets its own screen (AUTH-1).
  if (errorCode === AUTH_ERROR_CODE.domainNotAllowed && !start.isPending) {
    return <SignInRefused email={null} onUseAnotherAccountClick={() => start.mutate()} />
  }
 
  return (
    <SignInScreen
      isBusy={isBusy}
      errorCode={errorCode ?? (isBusy ? null : reason)}
      requestId={error instanceof ApiRequestError ? error.requestId : null}
      onSignInClick={() => start.mutate()}
    />
  )
}