Skip to content
Merged
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/wild-cycles-jog.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
---
---
Original file line number Diff line number Diff line change
Expand Up @@ -185,6 +185,34 @@ export default function SignInPage() {
</Submit>
</SignInStrategy>

<SignInStrategy name='email_code'>
<Field
name='code'
className='flex flex-col gap-4'
>
<div className='flex gap-4 justify-between items-center'>
<Label>Email Code</Label>
<Input
type='code'
className='bg-tertiary rounded-sm px-2 py-1 border border-foreground data-[invalid]:border-red-500'
/>
</div>

<Errors
render={({ code, message }) => (
<CustomError
code={code}
message={message}
/>
)}
/>
</Field>

<Submit className='px-4 py-2 b-1 bg-blue-950 bg-opacity-20 hover:bg-opacity-10 active:bg-opacity-5 rounded-md dark:bg-opacity-100 dark:hover:bg-opacity-80 dark:active:bg-opacity-50 transition'>
Sign In
</Submit>
</SignInStrategy>

<SignInStrategy name='phone_code'>
<Field
name='code'
Expand Down
31 changes: 22 additions & 9 deletions packages/elements/src/internals/machines/sign-in.actors.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import type {
AttemptFirstFactorParams,
AttemptSecondFactorParams,
AuthenticateWithRedirectParams,
EnvironmentResource,
HandleOAuthCallbackParams,
Expand All @@ -9,6 +8,7 @@ import type {
PrepareSecondFactorParams,
SignInFirstFactor,
SignInResource,
SignInSecondFactor,
} from '@clerk/types';
import { fromPromise } from 'xstate';

Expand Down Expand Up @@ -108,19 +108,32 @@ export const attemptFirstFactor = fromPromise<SignInResource, AttemptFirstFactor

// ================= prepareSecondFactor ================= //

export type PrepareSecondFactorInput = WithClient<WithParams<PrepareSecondFactorParams>>;
export type PrepareSecondFactorInput = WithClient<WithParams<PrepareSecondFactorParams | null>>;

export const prepareSecondFactor = fromPromise<SignInResource, PrepareSecondFactorInput>(({ input }) =>
input.client.signIn.prepareSecondFactor(input.params),
);
export const prepareSecondFactor = fromPromise<SignInResource, PrepareSecondFactorInput>(({ input }) => {
const currentFactor = input.params;
assertIsDefined(currentFactor);

return input.client.signIn.prepareSecondFactor({
strategy: currentFactor.strategy,
phoneNumberId: currentFactor.phoneNumberId,
});
});

// ================= attemptSecondFactor ================= //

export type AttemptSecondFactorInput = WithClient<WithParams<AttemptSecondFactorParams>>;
export type AttemptSecondFactorInput = WithClient<
WithParams<{ fields: SignInMachineContext['fields']; currentFactor: SignInSecondFactor | null }>
>;

export const attemptSecondFactor = fromPromise<SignInResource, AttemptSecondFactorInput>(({ input }) =>
input.client.signIn.attemptSecondFactor(input.params),
);
export const attemptSecondFactor = fromPromise<SignInResource, AttemptSecondFactorInput>(({ input }) => {
assertIsDefined(input.params.currentFactor);

return input.client.signIn.attemptSecondFactor({
strategy: input.params.currentFactor.strategy,
code: input.params.fields.get('code').value,
});
});

// ================= handleSSOCallback ================= //

Expand Down
123 changes: 111 additions & 12 deletions packages/elements/src/internals/machines/sign-in.machine.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,26 +4,30 @@ import type {
EnvironmentResource,
OAuthStrategy,
PrepareFirstFactorParams,
PrepareSecondFactorParams,
SignInFactor,
SignInFirstFactor,
SignInResource,
SignInSecondFactor,
Web3Strategy,
} from '@clerk/types';
import type { ActorRefFrom, ErrorActorEvent, MachineContext } from 'xstate';
import { and, assertEvent, assign, log, not, or, sendTo, setup } from 'xstate';
import { and, assertEvent, assign, not, or, sendTo, setup } from 'xstate';

import type { ClerkRouter } from '../router';
import type { FormMachine } from './form.machine';
import { waitForClerk } from './shared.actors';
import {
attemptFirstFactor,
attemptSecondFactor,
authenticateWithRedirect,
createSignIn,
handleSSOCallback,
prepareFirstFactor,
prepareSecondFactor,
} from './sign-in.actors';
import type { LoadedClerkWithEnv } from './sign-in.types';
import { determineStartingSignInFactor } from './sign-in.utils';
import { determineStartingSignInFactor, determineStartingSignInSecondFactor } from './sign-in.utils';
import { assertActorEventError } from './utils/assert';

export interface SignInMachineContext extends MachineContext {
Expand Down Expand Up @@ -72,8 +76,12 @@ export const SignInMachine = setup({
createSignIn,

// First Factor
attemptFirstFactor,
prepareFirstFactor,
attemptFirstFactor,

// Second Factor
prepareSecondFactor,
attemptSecondFactor,

// SSO
handleSSOCallback,
Expand Down Expand Up @@ -105,6 +113,7 @@ export const SignInMachine = setup({
isServer: ({ context }) => context.mode === 'server',
isBrowser: ({ context }) => context.mode === 'browser',
isCurrentFactorPassword: ({ context }) => context.currentFactor?.strategy === 'password',
isCurrentFactorTOTP: ({ context }) => context.currentFactor?.strategy === 'totp',
isClerkLoaded: ({ context }) => context.clerk.loaded,
isClerkEnvironmentLoaded: ({ context }) => Boolean(context.clerk.__unstable__environment),
isSignInComplete: ({ context }) => context?.resource?.status === 'complete',
Expand Down Expand Up @@ -292,12 +301,6 @@ export const SignInMachine = setup({
states: {
DeterminingState: {
always: [
{
description: 'If the current factor is not set, determine the starting factor details',
guard: not('hasCurrentFactor'),
target: 'DetermineStartingFactor',
reenter: true,
},
{
description: 'If the current factor is not password, prepare the factor',
guard: not('isCurrentFactorPassword'),
Expand Down Expand Up @@ -387,7 +390,7 @@ export const SignInMachine = setup({
},
{
guard: 'needsSecondFactor',
target: '#SignIn.FirstFactor',
target: '#SignIn.SecondFactor',
},
{
target: '#SignIn.DeterminingState',
Expand All @@ -403,8 +406,104 @@ export const SignInMachine = setup({
},
},
SecondFactor: {
type: 'final',
actions: [log('SecondFactor'), 'debug'],
initial: 'DeterminingState',
entry: assign({
currentFactor: ({ context }) =>
determineStartingSignInSecondFactor(context.clerk.client.signIn.supportedSecondFactors),
}),
states: {
DeterminingState: {
always: [
{
description: 'If the current factor is not TOTP, prepare the factor',
guard: not('isCurrentFactorTOTP'),
target: 'Preparing',
reenter: true,
},
{
description: 'Else, skip to awaiting input',
target: 'AwaitingInput',
reenter: true,
},
],
},
Preparing: {
invoke: {
id: 'prepareSecondFactor',
src: 'prepareSecondFactor',
input: ({ context }) => {
return {
client: context.clerk.client,
params: !context.currentFactor ? null : (context.currentFactor as PrepareSecondFactorParams),
};
},
onDone: {
target: 'AwaitingInput',
actions: [
assign({
resource: ({ event }) => event.output,
}),
],
},
onError: {
actions: 'setFormErrors',
target: 'Failure',
},
},
},
AwaitingInput: {
description: 'Waiting for user input',
on: {
SUBMIT: {
target: 'Attempting',
reenter: true,
},
},
},
Attempting: {
invoke: {
id: 'attemptSecondFactor',
src: 'attemptSecondFactor',
input: ({ context }) => ({
client: context.clerk.client,
params: {
currentFactor: context.currentFactor as SignInSecondFactor,
fields: context.formRef.getSnapshot().context.fields,
},
}),
onDone: {
actions: [
assign({
resource: ({ event }) => event.output,
}),
],
target: 'Success',
},
onError: {
actions: 'setFormErrors',
target: 'AwaitingInput',
},
},
},
Success: {
type: 'final',
always: [
{
guard: 'isSignInComplete',
target: '#SignIn.Complete',
},
{
target: '#SignIn.DeterminingState',
reenter: true,
},
],
},
Failure: {
type: 'final',
target: '#SignIn.DeterminingState',
reenter: true,
},
},
},
SSOCallbackRunning: {
invoke: {
Expand Down