import { SelfServiceLoginFlow , SubmitSelfServiceLoginFlowBody } from '@ory/kratos-client' ; import { CardTitle } from '@ory/themes' ; import { AxiosError } from 'axios' ; import type { NextPage } from 'next' ; import Head from 'next/head' ; import Link from 'next/link' ; import { useRouter } from 'next/router' ; import { useEffect , useState } from 'react' ; import { ActionCard , CenterLink , createLogoutHandler , Flow , MarginCard } from '../pkg' ; import { handleGetFlowError , handleFlowError } from '../pkg/errors' ; import ory from '../pkg/sdk' ; const Login = ( ) => { const [ flow , setFlow ] = useState < SelfServiceLoginFlow > ( ) ; const router = useRouter ( ) ; const { return_to : returnTo , flow : flowId , refresh , aal } = router . query ; const onLogout = createLogoutHandler ( [ aal , refresh ] ) ; useEffect ( ( ) => { if ( ! router . isReady || flow ) { return ; } if ( flowId ) { ory . getSelfServiceLoginFlow ( String ( flowId ) ) . then ( ( { data } ) => { setFlow ( data ) ; } ) . catch ( handleGetFlowError ( router , 'login' , setFlow ) ) ; return ; } ory . initializeSelfServiceLoginFlowForBrowsers ( Boolean ( refresh ) , aal ? String ( aal ) : undefined , returnTo ? String ( returnTo ) : undefined ) . then ( ( { data } ) => { setFlow ( data ) ; } ) . catch ( handleFlowError ( router , 'login' , setFlow ) ) ; } , [ flowId , router , router . isReady , aal , refresh , returnTo , flow ] ) ; const onSubmit = ( values ) => router . push ( `/login?flow=${ flow ?. id }` , undefined , { shallow : true } ) . then ( ( ) => ory . submitSelfServiceLoginFlow ( String ( flow ?. id ) , undefined , values ) . then ( ( res ) => { if ( flow ?. return_to ) { window . location . href = flow ?. return_to ; return ; } router . push ( '/' ) ; } ) . then ( ( ) => { } ) . catch ( handleFlowError ( router , 'login' , setFlow ) ) . catch ( ( err ) => { if ( err . response ?. status === 400 ) { setFlow ( err . response ?. data ) ; return ; } return Promise . reject ( err ) ; } ) ) ; return ( < > < Head > < title > Sign in - Ory NextJS Integration Example < /title> < meta name = "description" content = "NextJS + React + Vercel + Ory" / > < /Head> < MarginCard > < CardTitle > { ( ( ) => { if ( flow ?. refresh ) { return 'Confirm Action' ; } else if ( flow ?. requested_aal === 'aal2' ) { return 'Two-Factor Authentication' ; } return 'Sign In' ; } ) ( ) } < /CardTitle> < Flow onSubmit = { onSubmit } flow = { flow } / > < /MarginCard> { aal || refresh ? ( < ActionCard > < CenterLink data - testid = "logout-link" onClick = { onLogout } > Log out < /CenterLink> < /ActionCard>) : (<> < ActionCard > < Link href = "/registration" passHref > < CenterLink > Create account < /CenterLink> < /Link> < /ActionCard> < ActionCard > < Link href = "/recovery" passHref > < CenterLink > Recover your account < /CenterLink> < /Link> < /ActionCard> < />)} < />); } ; export default Login ;