-
Notifications
You must be signed in to change notification settings - Fork 449
Expand file tree
/
Copy pathSignInFactorOneCodeForm.tsx
More file actions
156 lines (138 loc) · 5.31 KB
/
SignInFactorOneCodeForm.tsx
File metadata and controls
156 lines (138 loc) · 5.31 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
150
151
152
153
154
155
156
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, ResetPasswordCodeFactor } from '@clerk/shared/types';
import { 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 { useFetch } from '../../hooks';
import { useSupportEmail } from '../../hooks/useSupportEmail';
import { type LocalizationKey } from '../../localization';
import { useRouter } from '../../router';
import { handleSignUpIfMissingTransfer } from './handleSignUpIfMissingTransfer';
export type SignInFactorOneCodeCard = Pick<
VerificationCodeCardProps,
'onShowAlternativeMethodsClicked' | 'showAlternativeMethods' | 'onBackLinkClicked'
> & {
factor: EmailCodeFactor | PhoneCodeFactor | ResetPasswordCodeFactor;
factorAlreadyPrepared: boolean;
onFactorPrepare: () => void;
};
export type SignInFactorOneCodeFormProps = SignInFactorOneCodeCard & {
cardTitle: LocalizationKey;
cardSubtitle: LocalizationKey;
inputLabel: LocalizationKey;
resendButton: LocalizationKey;
};
export const SignInFactorOneCodeForm = (props: SignInFactorOneCodeFormProps) => {
const signIn = useCoreSignIn();
const card = useCardState();
const { navigate } = useRouter();
const ctx = useSignInContext();
const { afterSignInUrl, afterSignUpUrl, navigateOnSetActive, isCombinedFlow } = ctx;
const { setActive } = useClerk();
const { userSettings } = useEnvironment();
const supportEmail = useSupportEmail();
const clerk = useClerk();
const shouldAvoidPrepare = signIn.firstFactorVerification.status === 'verified' && props.factorAlreadyPrepared;
const cacheKey = useMemo(() => {
const factor = props.factor;
let factorKey = factor.strategy;
if ('emailAddressId' in factor) {
factorKey += `_${factor.emailAddressId}`;
}
if ('phoneNumberId' in factor) {
factorKey += `_${factor.phoneNumberId}`;
}
if ('channel' in factor && factor.channel) {
factorKey += `_${factor.channel}`;
}
return {
name: 'signIn.prepareFirstFactor',
factorKey,
};
}, [
props.factor.strategy,
'emailAddressId' in props.factor ? props.factor.emailAddressId : undefined,
'phoneNumberId' in props.factor ? props.factor.phoneNumberId : undefined,
'channel' in props.factor ? props.factor.channel : undefined,
]);
const goBack = () => {
return navigate('../');
};
const prepare = () => {
if (shouldAvoidPrepare) {
return;
}
void signIn
.prepareFirstFactor(props.factor)
.then(() => props.onFactorPrepare())
.catch(err => handleError(err, [], card.setError));
};
useFetch(shouldAvoidPrepare ? undefined : () => signIn?.prepareFirstFactor(props.factor), cacheKey, {
staleTime: 100,
onSuccess: () => props.onFactorPrepare(),
onError: err => handleError(err, [], card.setError),
});
const action: VerificationCodeCardProps['onCodeEntryFinishedAction'] = (code, resolve, reject) => {
signIn
.attemptFirstFactor({ strategy: props.factor.strategy, code })
.then(async res => {
await resolve();
switch (res.status) {
case 'complete':
return setActive({
session: res.createdSessionId,
navigate: async ({ session, decorateUrl }) => {
await navigateOnSetActive({ session, redirectUrl: afterSignInUrl, decorateUrl });
},
});
case 'needs_second_factor':
return navigate('../factor-two');
case 'needs_new_password':
return navigate('../reset-password');
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]);
}
if (
isCombinedFlow &&
userSettings.attackProtection.enumeration_protection.enabled &&
signIn.firstFactorVerification.status === 'transferable'
) {
return handleSignUpIfMissingTransfer({
clerk,
navigate,
afterSignUpUrl,
navigateOnSetActive,
unsafeMetadata: ctx.unsafeMetadata,
});
}
return reject(err);
});
};
return (
<VerificationCodeCard
cardTitle={props.cardTitle}
cardSubtitle={props.cardSubtitle}
inputLabel={props.inputLabel}
resendButton={props.resendButton}
onCodeEntryFinishedAction={action}
onResendCodeClicked={prepare}
safeIdentifier={props.factor.safeIdentifier}
profileImageUrl={signIn.userData.imageUrl}
onShowAlternativeMethodsClicked={props.onShowAlternativeMethodsClicked}
showAlternativeMethods={props.showAlternativeMethods}
onIdentityPreviewEditClicked={goBack}
onBackLinkClicked={props.onBackLinkClicked}
/>
);
};