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
12 changes: 12 additions & 0 deletions .changeset/light-trees-battle.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
---
"@clerk/clerk-js": minor
"@clerk/types": minor
---

Move SessionVerification methods from UserResource to SessionResource:

- `user.__experimental_verifySession` -> `session.__experimental_startVerification`
- `user.__experimental_verifySessionPrepareFirstFactor` -> `session.__experimental_prepareFirstFactorVerification`
- `user.__experimental_verifySessionAttemptFirstFactor` -> `session.__experimental_attemptFirstFactorVerification`
- `user.__experimental_verifySessionPrepareSecondFactor` -> `session.__experimental_prepareSecondFactorVerification`
- `user.__experimental_verifySessionAttemptSecondFactor` -> `session.__experimental_attemptSecondFactorVerification`
103 changes: 103 additions & 0 deletions packages/clerk-js/src/core/resources/Session.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,19 @@
import { runWithExponentialBackOff } from '@clerk/shared';
import { is4xxError } from '@clerk/shared/error';
import type {
__experimental_SessionVerificationJSON,
__experimental_SessionVerificationResource,
__experimental_SessionVerifyAttemptFirstFactorParams,
__experimental_SessionVerifyAttemptSecondFactorParams,
__experimental_SessionVerifyCreateParams,
__experimental_SessionVerifyPrepareFirstFactorParams,
__experimental_SessionVerifyPrepareSecondFactorParams,
ActJWTClaim,
CheckAuthorization,
EmailCodeConfig,
GetToken,
GetTokenOptions,
PhoneCodeConfig,
SessionJSON,
SessionResource,
SessionStatus,
Expand All @@ -13,9 +22,11 @@ import type {
} from '@clerk/types';

import { unixEpochToDate } from '../../utils/date';
import { clerkInvalidStrategy } from '../errors';
import { eventBus, events } from '../events';
import { SessionTokenCache } from '../tokenCache';
import { BaseResource, PublicUserData, Token, User } from './internal';
import { SessionVerification } from './SessionVerification';

export class Session extends BaseResource implements SessionResource {
pathRoot = '/client/sessions';
Expand Down Expand Up @@ -123,6 +134,98 @@ export class Session extends BaseResource implements SessionResource {
return [this.id, template, resolvedOrganizationId, this.updatedAt.getTime()].filter(Boolean).join('-');
}

__experimental_startVerification = async ({
level,
maxAge,
}: __experimental_SessionVerifyCreateParams): Promise<__experimental_SessionVerificationResource> => {
const json = (
await BaseResource._fetch({
method: 'POST',
path: `/client/sessions/${this.id}/verify`,
body: {
level,
maxAge,
} as any,
})
)?.response as unknown as __experimental_SessionVerificationJSON;

return new SessionVerification(json);
};

__experimental_prepareFirstFactorVerification = async (
factor: __experimental_SessionVerifyPrepareFirstFactorParams,
): Promise<__experimental_SessionVerificationResource> => {
let config;
switch (factor.strategy) {
case 'email_code':
config = { emailAddressId: factor.emailAddressId } as EmailCodeConfig;
break;
case 'phone_code':
config = {
phoneNumberId: factor.phoneNumberId,
default: factor.default,
} as PhoneCodeConfig;
break;
default:
clerkInvalidStrategy('Session.prepareFirstFactorVerification', (factor as any).strategy);
}

const json = (
await BaseResource._fetch({
method: 'POST',
path: `/client/sessions/${this.id}/verify/prepare_first_factor`,
body: {
...config,
strategy: factor.strategy,
} as any,
})
)?.response as unknown as __experimental_SessionVerificationJSON;

return new SessionVerification(json);
};

__experimental_attemptFirstFactorVerification = async (
attemptFactor: __experimental_SessionVerifyAttemptFirstFactorParams,
): Promise<__experimental_SessionVerificationResource> => {
const json = (
await BaseResource._fetch({
method: 'POST',
path: `/client/sessions/${this.id}/verify/attempt_first_factor`,
body: { ...attemptFactor, strategy: attemptFactor.strategy } as any,
})
)?.response as unknown as __experimental_SessionVerificationJSON;

return new SessionVerification(json);
};

__experimental_prepareSecondFactorVerification = async (
params: __experimental_SessionVerifyPrepareSecondFactorParams,
): Promise<__experimental_SessionVerificationResource> => {
const json = (
await BaseResource._fetch({
method: 'POST',
path: `/client/sessions/${this.id}/verify/prepare_second_factor`,
body: params as any,
})
)?.response as unknown as __experimental_SessionVerificationJSON;

return new SessionVerification(json);
};

__experimental_attemptSecondFactorVerification = async (
params: __experimental_SessionVerifyAttemptSecondFactorParams,
): Promise<__experimental_SessionVerificationResource> => {
const json = (
await BaseResource._fetch({
method: 'POST',
path: `/client/sessions/${this.id}/verify/attempt_second_factor`,
body: params as any,
})
)?.response as unknown as __experimental_SessionVerificationJSON;

return new SessionVerification(json);
};

protected fromJSON(data: SessionJSON | null): this {
if (!data) {
return this;
Expand Down
103 changes: 0 additions & 103 deletions packages/clerk-js/src/core/resources/User.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,4 @@
import type {
__experimental_SessionVerificationJSON,
__experimental_SessionVerificationResource,
__experimental_SessionVerifyAttemptFirstFactorParams,
__experimental_SessionVerifyAttemptSecondFactorParams,
__experimental_SessionVerifyCreateParams,
__experimental_SessionVerifyPrepareFirstFactorParams,
__experimental_SessionVerifyPrepareSecondFactorParams,
BackupCodeJSON,
BackupCodeResource,
CreateEmailAddressParams,
Expand All @@ -15,7 +8,6 @@ import type {
DeletedObjectJSON,
DeletedObjectResource,
EmailAddressResource,
EmailCodeConfig,
ExternalAccountJSON,
ExternalAccountResource,
GetOrganizationMemberships,
Expand All @@ -24,7 +16,6 @@ import type {
ImageResource,
OrganizationMembershipResource,
PasskeyResource,
PhoneCodeConfig,
PhoneNumberResource,
RemoveUserPasswordParams,
SamlAccountResource,
Expand All @@ -42,7 +33,6 @@ import type {
import { unixEpochToDate } from '../../utils/date';
import { normalizeUnsafeMetadata } from '../../utils/resourceParams';
import { getFullName } from '../../utils/user';
import { clerkInvalidStrategy } from '../errors';
import { BackupCode } from './BackupCode';
import {
BaseResource,
Expand All @@ -60,7 +50,6 @@ import {
UserOrganizationInvitation,
Web3Wallet,
} from './internal';
import { SessionVerification } from './SessionVerification';

export class User extends BaseResource implements UserResource {
pathRoot = '/me';
Expand Down Expand Up @@ -250,98 +239,6 @@ export class User extends BaseResource implements UserResource {
return this._baseDelete({ path: '/me' });
};

__experimental_verifySession = async ({
level,
maxAge,
}: __experimental_SessionVerifyCreateParams): Promise<__experimental_SessionVerificationResource> => {
const json = (
await BaseResource._fetch({
method: 'POST',
path: `/me/sessions/verify`,
body: {
level,
maxAge,
} as any,
})
)?.response as unknown as __experimental_SessionVerificationJSON;

return new SessionVerification(json);
};

__experimental_verifySessionPrepareFirstFactor = async (
factor: __experimental_SessionVerifyPrepareFirstFactorParams,
): Promise<__experimental_SessionVerificationResource> => {
let config;
switch (factor.strategy) {
case 'email_code':
config = { emailAddressId: factor.emailAddressId } as EmailCodeConfig;
break;
case 'phone_code':
config = {
phoneNumberId: factor.phoneNumberId,
default: factor.default,
} as PhoneCodeConfig;
break;
default:
clerkInvalidStrategy('User.verifySessionPrepareFirstFactor', (factor as any).strategy);
}

const json = (
await BaseResource._fetch({
method: 'POST',
path: `/me/sessions/verify/prepare_first_factor`,
body: {
...config,
strategy: factor.strategy,
} as any,
})
)?.response as unknown as __experimental_SessionVerificationJSON;

return new SessionVerification(json);
};

__experimental_verifySessionAttemptFirstFactor = async (
attemptFactor: __experimental_SessionVerifyAttemptFirstFactorParams,
): Promise<__experimental_SessionVerificationResource> => {
const json = (
await BaseResource._fetch({
method: 'POST',
path: `/me/sessions/verify/attempt_first_factor`,
body: { ...attemptFactor, strategy: attemptFactor.strategy } as any,
})
)?.response as unknown as __experimental_SessionVerificationJSON;

return new SessionVerification(json);
};

__experimental_verifySessionPrepareSecondFactor = async (
params: __experimental_SessionVerifyPrepareSecondFactorParams,
): Promise<__experimental_SessionVerificationResource> => {
const json = (
await BaseResource._fetch({
method: 'POST',
path: `/me/sessions/verify/prepare_second_factor`,
body: params as any,
})
)?.response as unknown as __experimental_SessionVerificationJSON;

return new SessionVerification(json);
};

__experimental_verifySessionAttemptSecondFactor = async (
params: __experimental_SessionVerifyAttemptSecondFactorParams,
): Promise<__experimental_SessionVerificationResource> => {
const json = (
await BaseResource._fetch({
method: 'POST',
path: `/me/sessions/verify/attempt_second_factor`,
body: params as any,
})
)?.response as unknown as __experimental_SessionVerificationJSON;

return new SessionVerification(json);
};

getSessions = async (): Promise<SessionWithActivities[]> => {
if (this.cachedSessionsWithActivities) {
return this.cachedSessionsWithActivities;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useUser } from '@clerk/shared/react';
import { useSession } from '@clerk/shared/react';
import type { EmailCodeFactor, PhoneCodeFactor } from '@clerk/types';
import React from 'react';

Expand All @@ -25,7 +25,7 @@ export type UVFactorOneCodeFormProps = UVFactorOneCodeCard & {
};

export const UVFactorOneCodeForm = (props: UVFactorOneCodeFormProps) => {
const { user } = useUser();
const { session } = useSession();
const card = useCardState();

const { handleVerificationResponse } = useAfterVerification();
Expand All @@ -37,15 +37,15 @@ export const UVFactorOneCodeForm = (props: UVFactorOneCodeFormProps) => {
}, []);

const prepare = () => {
void user!
.__experimental_verifySessionPrepareFirstFactor(props.factor)
void session!
.__experimental_prepareFirstFactorVerification(props.factor)
.then(() => props.onFactorPrepare())
.catch(err => handleError(err, [], card.setError));
};

const action: VerificationCodeCardProps['onCodeEntryFinishedAction'] = (code, resolve, reject) => {
user!
.__experimental_verifySessionAttemptFirstFactor({ strategy: props.factor.strategy, code })
session!
.__experimental_attemptFirstFactorVerification({ strategy: props.factor.strategy, code })
.then(async res => {
await resolve();
return handleVerificationResponse(res);
Expand All @@ -62,7 +62,7 @@ export const UVFactorOneCodeForm = (props: UVFactorOneCodeFormProps) => {
onCodeEntryFinishedAction={action}
onResendCodeClicked={prepare}
safeIdentifier={props.factor.safeIdentifier}
profileImageUrl={user?.imageUrl}
profileImageUrl={session?.user?.imageUrl}
onShowAlternativeMethodsClicked={props.onShowAlternativeMethodsClicked}
showAlternativeMethods={props.showAlternativeMethods}
onBackLinkClicked={props.onBackLinkClicked}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useUser } from '@clerk/shared/react';
import { useSession } from '@clerk/shared/react';
import React from 'react';

import { Col, descriptors, localizationKeys } from '../../customizables';
Expand All @@ -12,7 +12,7 @@ type UVFactorTwoBackupCodeCardProps = {

export const UVFactorTwoBackupCodeCard = (props: UVFactorTwoBackupCodeCardProps) => {
const { onShowAlternativeMethodsClicked } = props;
const { user } = useUser();
const { session } = useSession();
const { handleVerificationResponse } = useAfterVerification();

const card = useCardState();
Expand All @@ -24,8 +24,8 @@ export const UVFactorTwoBackupCodeCard = (props: UVFactorTwoBackupCodeCardProps)

const handleBackupCodeSubmit: React.FormEventHandler = e => {
e.preventDefault();
return user!
.__experimental_verifySessionAttemptSecondFactor({ strategy: 'backup_code', code: codeControl.value })
return session!
.__experimental_attemptSecondFactorVerification({ strategy: 'backup_code', code: codeControl.value })
.then(handleVerificationResponse)
.catch(err => handleError(err, [codeControl], card.setError));
};
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useUser } from '@clerk/shared/react';
import { useSession } from '@clerk/shared/react';
import type { __experimental_SessionVerificationResource, PhoneCodeFactor, TOTPFactor } from '@clerk/types';
import React from 'react';

Expand All @@ -24,7 +24,7 @@ type SignInFactorTwoCodeFormProps = UVFactorTwoCodeCard & {

export const UVFactorTwoCodeForm = (props: SignInFactorTwoCodeFormProps) => {
const card = useCardState();
const { user } = useUser();
const { session } = useSession();
const { handleVerificationResponse } = useAfterVerification();

React.useEffect(() => {
Expand All @@ -44,8 +44,8 @@ export const UVFactorTwoCodeForm = (props: SignInFactorTwoCodeFormProps) => {
: undefined;

const action: VerificationCodeCardProps['onCodeEntryFinishedAction'] = (code, resolve, reject) => {
user!
.__experimental_verifySessionAttemptSecondFactor({ strategy: props.factor.strategy, code })
session!
.__experimental_attemptSecondFactorVerification({ strategy: props.factor.strategy, code })
.then(async res => {
await resolve();
return handleVerificationResponse(res);
Expand All @@ -62,7 +62,7 @@ export const UVFactorTwoCodeForm = (props: SignInFactorTwoCodeFormProps) => {
onCodeEntryFinishedAction={action}
onResendCodeClicked={prepare}
safeIdentifier={'safeIdentifier' in props.factor ? props.factor.safeIdentifier : undefined}
profileImageUrl={user!.imageUrl}
profileImageUrl={session?.user?.imageUrl}
onShowAlternativeMethodsClicked={props.onShowAlternativeMethodsClicked}
/>
);
Expand Down
Loading