Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .changeset/pretty-bats-bathe.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
---
---
86 changes: 85 additions & 1 deletion packages/ui/src/components/SignIn/SignInClientTrust.tsx
Original file line number Diff line number Diff line change
@@ -1,16 +1,31 @@
import { useClerk } from '@clerk/shared/react';
import type { SignInFactor, SignInResource } from '@clerk/shared/types';
import React from 'react';

import { withCardStateProvider } from '@/ui/elements/contexts';
import type { VerificationCodeCardProps } from '@/ui/elements/VerificationCodeCard';
import { LoadingCard } from '@/ui/elements/LoadingCard';

import { withRedirectToAfterSignIn, withRedirectToSignInTask } from '../../common';
import { useCoreSignIn } from '../../contexts';
import { buildVerificationRedirectUrl } from '../../common/redirects';
import { useCoreSignIn, useSignInContext } from '../../contexts';
import { useRouter } from '../../router';
import { SignInFactorTwoAlternativeMethods } from './SignInFactorTwoAlternativeMethods';
import { SignInFactorTwoEmailCodeCard } from './SignInFactorTwoEmailCodeCard';
import { SignInFactorTwoEmailLinkCard } from './SignInFactorTwoEmailLinkCard';
import { SignInFactorTwoPhoneCodeCard } from './SignInFactorTwoPhoneCodeCard';
import { useHandleSecondFactorResult, useHandleUserLockedError } from './useHandleAttemptResult';
import { useSecondFactorSelection } from './useSecondFactorSelection';
import { isResetPasswordStrategy } from './utils';

function SignInClientTrustInternal(): JSX.Element {
const clerk = useClerk();
const signIn = useCoreSignIn();
const router = useRouter();
const signInContext = useSignInContext();
const { afterSignInUrl } = signInContext;
const handleSecondFactorResult = useHandleSecondFactorResult();
const handleUserLockedError = useHandleUserLockedError();
const {
currentFactor,
factorAlreadyPrepared,
Expand All @@ -20,6 +35,58 @@ function SignInClientTrustInternal(): JSX.Element {
toggleAllStrategies,
} = useSecondFactorSelection(signIn.supportedSecondFactors);

const isResettingPassword =
isResetPasswordStrategy(signIn.firstFactorVerification?.strategy) &&
signIn.firstFactorVerification?.status === 'verified';

const handleAttemptCode: VerificationCodeCardProps['onCodeEntryFinishedAction'] = React.useCallback(
(code: string, resolve: () => Promise<void>, reject: (err: unknown) => void) => {
if (!currentFactor) {
return;
}
signIn
.attemptSecondFactor({ strategy: currentFactor.strategy as any, code })
.then(async res => {
await resolve();
return handleSecondFactorResult(res);
})
.catch(err => {
if (handleUserLockedError(err)) {
return;
}
return reject(err);
});
},
[signIn, currentFactor, handleSecondFactorResult, handleUserLockedError],
);

const handlePrepareSecondFactor = React.useCallback(
(factor: SignInFactor) => signIn.prepareSecondFactor(factor as any),
[signIn],
);

const handleEmailLinkVerificationComplete = React.useCallback(
async (si: SignInResource) => {
if (si.status === 'complete') {
await clerk.setActive({
session: si.createdSessionId,
redirectUrl: afterSignInUrl,
});
}
},
[clerk, afterSignInUrl],
);

const emailLinkRedirectUrl = React.useMemo(
() =>
buildVerificationRedirectUrl({
ctx: signInContext,
baseUrl: signInContext.signInUrl,
intent: 'sign-in',
}),
[signInContext],
);

if (!currentFactor) {
return <LoadingCard />;
}
Expand All @@ -33,6 +100,13 @@ function SignInClientTrustInternal(): JSX.Element {
);
}

const codeCardProps = {
onAttemptCode: handleAttemptCode,
avatarUrl: signIn.userData.imageUrl,
isResettingPassword,
showNewDeviceVerificationNotice: false,
} as const;

switch (currentFactor?.strategy) {
case 'phone_code':
return (
Expand All @@ -42,6 +116,8 @@ function SignInClientTrustInternal(): JSX.Element {
onFactorPrepare={handleFactorPrepare}
factor={currentFactor}
onShowAlternativeMethodsClicked={toggleAllStrategies}
onPrepareSecondFactor={handlePrepareSecondFactor as (factor: any) => Promise<SignInResource>}
{...codeCardProps}
/>
);
case 'email_code':
Expand All @@ -52,6 +128,8 @@ function SignInClientTrustInternal(): JSX.Element {
onFactorPrepare={handleFactorPrepare}
factor={currentFactor}
onShowAlternativeMethodsClicked={toggleAllStrategies}
onPrepareSecondFactor={handlePrepareSecondFactor as (factor: any) => Promise<SignInResource>}
{...codeCardProps}
/>
);
case 'email_link':
Expand All @@ -62,6 +140,12 @@ function SignInClientTrustInternal(): JSX.Element {
onFactorPrepare={handleFactorPrepare}
factor={currentFactor}
onShowAlternativeMethodsClicked={toggleAllStrategies}
signIn={signIn}
onVerificationComplete={handleEmailLinkVerificationComplete}
onUserLockedError={handleUserLockedError}
avatarUrl={signIn.userData.imageUrl}
redirectUrl={emailLinkRedirectUrl}
isNewDevice={signIn.clientTrustState === 'new'}
/>
);
default:
Expand Down
122 changes: 113 additions & 9 deletions packages/ui/src/components/SignIn/SignInFactorTwo.tsx
Original file line number Diff line number Diff line change
@@ -1,25 +1,34 @@
import { useClerk } from '@clerk/shared/react';
import React from 'react';
import type { SignInFactor, SignInResource } from '@clerk/shared/types';
import React, { useMemo } from 'react';

import { withCardStateProvider } from '@/ui/elements/contexts';
import type { VerificationCodeCardProps } from '@/ui/elements/VerificationCodeCard';
import { LoadingCard } from '@/ui/elements/LoadingCard';

import { withRedirectToAfterSignIn, withRedirectToSignInTask } from '../../common';
import { useCoreSignIn, useSignInContext } from '../../contexts';
import { buildVerificationRedirectUrl } from '../../common/redirects';
import { useCoreSignIn, useEnvironment, useSignInContext } from '../../contexts';
import { useRouter } from '../../router';
import { SignInFactorTwoAlternativeMethods } from './SignInFactorTwoAlternativeMethods';
import { SignInFactorTwoBackupCodeCard } from './SignInFactorTwoBackupCodeCard';
import { SignInFactorTwoEmailCodeCard } from './SignInFactorTwoEmailCodeCard';
import { SignInFactorTwoEmailLinkCard } from './SignInFactorTwoEmailLinkCard';
import { SignInFactorTwoPhoneCodeCard } from './SignInFactorTwoPhoneCodeCard';
import { SignInFactorTwoTOTPCard } from './SignInFactorTwoTOTPCard';
import { useHandleSecondFactorResult, useHandleUserLockedError } from './useHandleAttemptResult';
import { useSecondFactorSelection } from './useSecondFactorSelection';
import { isResetPasswordStrategy } from './utils';

function SignInFactorTwoInternal(): JSX.Element {
const clerk = useClerk();
const signIn = useCoreSignIn();
const env = useEnvironment();
const router = useRouter();
const { afterSignInUrl } = useSignInContext();
const signInContext = useSignInContext();
const { afterSignInUrl } = signInContext;
const handleSecondFactorResult = useHandleSecondFactorResult();
const handleUserLockedError = useHandleUserLockedError();
const {
currentFactor,
factorAlreadyPrepared,
Expand All @@ -29,17 +38,88 @@ function SignInFactorTwoInternal(): JSX.Element {
toggleAllStrategies,
} = useSecondFactorSelection(signIn.supportedSecondFactors);

const isResettingPassword =
isResetPasswordStrategy(signIn.firstFactorVerification?.strategy) &&
signIn.firstFactorVerification?.status === 'verified';

const showNewDeviceVerificationNotice = useMemo(() => {
const anyAttributeUsedForSecondFactor = Object.values(env.userSettings.attributes).some(
attr => attr.used_for_second_factor,
);
return signIn.clientTrustState === 'new' && !anyAttributeUsedForSecondFactor;
}, [signIn.clientTrustState, env.userSettings.attributes]);

const handleAttemptCode: VerificationCodeCardProps['onCodeEntryFinishedAction'] = React.useCallback(
(code: string, resolve: () => Promise<void>, reject: (err: unknown) => void) => {
if (!currentFactor) {
return;
}
signIn
.attemptSecondFactor({ strategy: currentFactor.strategy as any, code })
.then(async res => {
await resolve();
return handleSecondFactorResult(res);
})
.catch(err => {
if (handleUserLockedError(err)) {
return;
}
return reject(err);
});
},
[signIn, currentFactor, handleSecondFactorResult, handleUserLockedError],
);

const handleAttemptBackupCode = React.useCallback(
async (code: string) => {
try {
const res = await signIn.attemptSecondFactor({ strategy: 'backup_code', code });
await handleSecondFactorResult(res);
} catch (err) {
if (handleUserLockedError(err)) {
return;
}
throw err;
}
},
[signIn, handleSecondFactorResult, handleUserLockedError],
);

const handlePrepareSecondFactor = React.useCallback(
(factor: SignInFactor) => signIn.prepareSecondFactor(factor as any),
[signIn],
);

const handleEmailLinkVerificationComplete = React.useCallback(
async (si: SignInResource) => {
if (si.status === 'complete') {
await clerk.setActive({
session: si.createdSessionId,
redirectUrl: afterSignInUrl,
});
} else if (si.status === 'needs_second_factor') {
await router.navigate('../factor-two');
}
},
[clerk, afterSignInUrl, router],
);

const emailLinkRedirectUrl = React.useMemo(
() =>
buildVerificationRedirectUrl({
ctx: signInContext,
baseUrl: signInContext.signInUrl,
intent: 'sign-in',
}),
[signInContext],
);

React.useEffect(() => {
if (clerk.__internal_setActiveInProgress) {
return;
}

// If the sign-in doesn't need second factor verification, redirect away.
// Don't redirect for 'complete' status - setActive will handle navigation.
if (signIn.status === null || signIn.status === 'needs_identifier' || signIn.status === 'needs_first_factor') {
// If the user is already signed in (e.g. multi-session app, page reload after
// successful verification), redirect forward to afterSignInUrl instead of
// back to sign-in start.
if (clerk.isSignedIn) {
void router.navigate(afterSignInUrl);
} else {
Expand All @@ -62,6 +142,13 @@ function SignInFactorTwoInternal(): JSX.Element {
);
}

const codeCardProps = {
onAttemptCode: handleAttemptCode,
avatarUrl: signIn.userData.imageUrl,
isResettingPassword,
showNewDeviceVerificationNotice,
} as const;

switch (currentFactor?.strategy) {
case 'phone_code':
return (
Expand All @@ -70,6 +157,8 @@ function SignInFactorTwoInternal(): JSX.Element {
onFactorPrepare={handleFactorPrepare}
factor={currentFactor}
onShowAlternativeMethodsClicked={toggleAllStrategies}
onPrepareSecondFactor={handlePrepareSecondFactor as (factor: any) => Promise<SignInResource>}
{...codeCardProps}
/>
);
case 'totp':
Expand All @@ -79,17 +168,26 @@ function SignInFactorTwoInternal(): JSX.Element {
onFactorPrepare={handleFactorPrepare}
factor={currentFactor}
onShowAlternativeMethodsClicked={toggleAllStrategies}
{...codeCardProps}
/>
);
case 'backup_code':
return <SignInFactorTwoBackupCodeCard onShowAlternativeMethodsClicked={toggleAllStrategies} />;
return (
<SignInFactorTwoBackupCodeCard
onShowAlternativeMethodsClicked={toggleAllStrategies}
onAttemptBackupCode={handleAttemptBackupCode}
isResettingPassword={isResettingPassword}
/>
);
case 'email_code':
return (
<SignInFactorTwoEmailCodeCard
factorAlreadyPrepared={factorAlreadyPrepared}
onFactorPrepare={handleFactorPrepare}
factor={currentFactor}
onShowAlternativeMethodsClicked={toggleAllStrategies}
onPrepareSecondFactor={handlePrepareSecondFactor as (factor: any) => Promise<SignInResource>}
{...codeCardProps}
/>
);
case 'email_link':
Expand All @@ -99,6 +197,12 @@ function SignInFactorTwoInternal(): JSX.Element {
onFactorPrepare={handleFactorPrepare}
factor={currentFactor}
onShowAlternativeMethodsClicked={toggleAllStrategies}
signIn={signIn}
onVerificationComplete={handleEmailLinkVerificationComplete}
onUserLockedError={handleUserLockedError}
avatarUrl={signIn.userData.imageUrl}
redirectUrl={emailLinkRedirectUrl}
isNewDevice={signIn.clientTrustState === 'new'}
/>
);
default:
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import type { SignInResource } from '@clerk/shared/types';
import React from 'react';

import { Card } from '@/ui/elements/Card';
Expand All @@ -8,42 +7,28 @@ import { Header } from '@/ui/elements/Header';
import { handleError } from '@/ui/utils/errorHandler';
import { useFormControl } from '@/ui/utils/useFormControl';

import { useCoreSignIn } from '../../contexts';
import { Col, descriptors, localizationKeys } from '../../customizables';
import { useHandleSecondFactorResult, useHandleUserLockedError } from './useHandleAttemptResult';
import { isResetPasswordStrategy } from './utils';

type SignInFactorTwoBackupCodeCardProps = {
onShowAlternativeMethodsClicked: React.MouseEventHandler;
onAttemptBackupCode: (code: string) => Promise<void>;
isResettingPassword: boolean;
};

export const SignInFactorTwoBackupCodeCard = (props: SignInFactorTwoBackupCodeCardProps) => {
const { onShowAlternativeMethodsClicked } = props;
const signIn = useCoreSignIn();
const { onShowAlternativeMethodsClicked, onAttemptBackupCode, isResettingPassword } = props;
const card = useCardState();
const codeControl = useFormControl('code', '', {
type: 'text',
label: localizationKeys('formFieldLabel__backupCode'),
isRequired: true,
});
const handleSecondFactorResult = useHandleSecondFactorResult();
const handleUserLockedError = useHandleUserLockedError();

const isResettingPassword = (resource: SignInResource) =>
isResetPasswordStrategy(resource.firstFactorVerification?.strategy) &&
resource.firstFactorVerification?.status === 'verified';

const handleBackupCodeSubmit: React.FormEventHandler = e => {
e.preventDefault();
return signIn
.attemptSecondFactor({ strategy: 'backup_code', code: codeControl.value })
.then(handleSecondFactorResult)
.catch(err => {
if (handleUserLockedError(err)) {
return;
}
handleError(err, [codeControl], card.setError);
});
return onAttemptBackupCode(codeControl.value).catch(err => {
handleError(err, [codeControl], card.setError);
});
};

return (
Expand All @@ -53,7 +38,7 @@ export const SignInFactorTwoBackupCodeCard = (props: SignInFactorTwoBackupCodeCa
<Header.Title localizationKey={localizationKeys('signIn.backupCodeMfa.title')} />
<Header.Subtitle
localizationKey={
isResettingPassword(signIn)
isResettingPassword
? localizationKeys('signIn.forgotPassword.subtitle')
: localizationKeys('signIn.backupCodeMfa.subtitle')
}
Expand Down
Loading
Loading