-
Notifications
You must be signed in to change notification settings - Fork 467
Expand file tree
/
Copy pathSignInFactorTwoCodeForm.tsx
More file actions
149 lines (134 loc) · 5.66 KB
/
Copy pathSignInFactorTwoCodeForm.tsx
File metadata and controls
149 lines (134 loc) · 5.66 KB
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
import { isUserLockedError } from '@clerk/shared/error';
import { clerkInvalidFAPIResponse } from '@clerk/shared/internal/clerk-js/errors';
import { useClerk } from '@clerk/shared/react';
import type { EmailCodeFactor, PhoneCodeFactor, SignInResource, TOTPFactor } from '@clerk/shared/types';
import React, { useMemo } from 'react';
import { useCardState } from '@/ui/elements/contexts';
import type { VerificationCodeCardProps } from '@/ui/elements/VerificationCodeCard';
import { VerificationCodeCard } from '@/ui/elements/VerificationCodeCard';
import { handleError } from '@/ui/utils/errorHandler';
import { useCoreSignIn, useEnvironment, useSignInContext } from '../../contexts';
import { localizationKeys, Text } from '../../customizables';
import { useSupportEmail } from '../../hooks/useSupportEmail';
import type { LocalizationKey } from '../../localization';
import { useRouter } from '../../router';
import { navigateOnSignInProtectGate } from './handleProtectCheck';
import { isResetPasswordStrategy } from './utils';
export type SignInFactorTwoCodeCard = Pick<VerificationCodeCardProps, 'onShowAlternativeMethodsClicked'> & {
showClientTrustNotice?: boolean;
factor: EmailCodeFactor | PhoneCodeFactor | TOTPFactor;
factorAlreadyPrepared: boolean;
onFactorPrepare: () => void;
prepare?: () => Promise<SignInResource>;
};
type SignInFactorTwoCodeFormProps = SignInFactorTwoCodeCard & {
cardTitle: LocalizationKey;
cardSubtitle: LocalizationKey;
inputLabel: LocalizationKey;
resendButton?: LocalizationKey;
};
const isResettingPassword = (resource: SignInResource) =>
isResetPasswordStrategy(resource.firstFactorVerification?.strategy) &&
resource.firstFactorVerification?.status === 'verified';
export const SignInFactorTwoCodeForm = (props: SignInFactorTwoCodeFormProps) => {
const env = useEnvironment();
const signIn = useCoreSignIn();
const card = useCardState();
const { afterSignInUrl, navigateOnSetActive } = useSignInContext();
const { setActive } = useClerk();
const { navigate } = useRouter();
const supportEmail = useSupportEmail();
const clerk = useClerk();
const signInAsDifferentUser = () => navigate('../');
// Only show the new device verification notice if the user is new
// and no attributes are explicitly used for second factor.
// Retained for backwards compatibility.
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]);
React.useEffect(() => {
if (props.factorAlreadyPrepared) {
return;
}
void prepare?.();
}, []);
const prepare = props.prepare
? () => {
return props
.prepare?.()
.then(() => props.onFactorPrepare())
.catch(err => {
if (isUserLockedError(err)) {
// @ts-expect-error -- private method for the time being
return clerk.__internal_navigateWithError('..', err.errors[0]);
}
handleError(err, [], card.setError);
});
}
: undefined;
const action: VerificationCodeCardProps['onCodeEntryFinishedAction'] = (code, resolve, reject) => {
signIn
.attemptSecondFactor({ strategy: props.factor.strategy, code })
.then(async res => {
await resolve();
if (navigateOnSignInProtectGate(res, navigate, '../protect-check')) {
return;
}
switch (res.status) {
case 'complete':
if (isResettingPassword(res) && res.createdSessionId) {
const queryParams = new URLSearchParams();
queryParams.set('createdSessionId', res.createdSessionId);
return navigate(`../reset-password-success?${queryParams.toString()}`);
}
return setActive({
session: res.createdSessionId,
navigate: async ({ session, decorateUrl }) => {
await navigateOnSetActive({ session, redirectUrl: afterSignInUrl, decorateUrl });
},
});
default:
return console.error(clerkInvalidFAPIResponse(res.status, supportEmail));
}
})
.catch(err => {
if (isUserLockedError(err)) {
// @ts-expect-error -- private method for the time being
return clerk.__internal_navigateWithError('..', err.errors[0]);
}
return reject(err);
});
};
return (
<VerificationCodeCard
cardTitle={props.cardTitle}
cardSubtitle={
isResettingPassword(signIn) ? localizationKeys('signIn.forgotPassword.subtitle') : props.cardSubtitle
}
cardNotice={
props.showClientTrustNotice || showNewDeviceVerificationNotice
? localizationKeys('signIn.newDeviceVerificationNotice')
: undefined
}
resendButton={props.resendButton}
inputLabel={props.inputLabel}
onCodeEntryFinishedAction={action}
onResendCodeClicked={prepare}
safeIdentifier={'safeIdentifier' in props.factor ? props.factor.safeIdentifier : undefined}
profileImageUrl={signIn.userData.imageUrl}
identityPreviewEditButtonAriaLabel={localizationKeys('identityPreviewEditButton__identifier')}
onShowAlternativeMethodsClicked={props.onShowAlternativeMethodsClicked}
onDifferentAccountClicked={signInAsDifferentUser}
>
{isResettingPassword(signIn) && (
<Text
localizationKey={localizationKeys('signIn.resetPasswordMfa.detailsLabel')}
colorScheme='secondary'
/>
)}
</VerificationCodeCard>
);
};