Repository navigation
feat(clerk-react,nextjs,shared): Introduce experimental useReverification
#4362
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
panteliselef
merged 33 commits into
main
from
elef/user-896-introduce-usereverification
Oct 31, 2024
Merged
Changes from all commits
Commits
Show all changes
33 commits
Select commit
Hold shift + click to select a range
27bf018
utilities for generating the authorization error objects
panteliselef 148be60
wip useReverification
panteliselef 5290f20
fix setActive inside transitions for next >= 14
panteliselef 4467912
only keep re-verification errors
panteliselef e1c3987
cleanup useReverification
panteliselef 993ceaf
add changesets
panteliselef 43fac9c
fix formatting
panteliselef b339816
update snapshot for clerk-extension
panteliselef a574620
update e2e tests for reverification
panteliselef fe92ddc
Merge branch 'refs/heads/main' into elef/user-896-introduce-usereveri…
panteliselef 2238126
fix __unstable__onAfterSetActive definition
panteliselef 3e87422
Merge branch 'refs/heads/main' into elef/user-896-introduce-usereveri…
panteliselef 4b507aa
fix e2e tests
panteliselef 5c300a3
Merge branch 'refs/heads/main' into elef/user-896-introduce-usereveri…
panteliselef 853f884
Merge branch 'refs/heads/main' into elef/user-896-introduce-usereveri…
panteliselef 07b93dc
Merge branch 'main' into elef/user-896-introduce-usereverification
panteliselef a0c108b
Merge branch 'main' into elef/user-896-introduce-usereverification
panteliselef 42ad902
remove skipped test
panteliselef 828dc90
revert global timeout extention
panteliselef dfad7e6
address PR review comments
panteliselef 75902dc
Merge branch 'refs/heads/main' into elef/user-896-introduce-usereveri…
panteliselef 835e972
update package-lock.json
panteliselef d9f4076
extend duration
panteliselef 0637a82
Merge branch 'refs/heads/main' into elef/user-896-introduce-usereveri…
panteliselef 9cf75a6
remove delay subtraction
panteliselef fe5b823
update dx of `useReverification`
panteliselef 10e1430
replace useAssurance with useReverification
panteliselef a7129cf
Merge branch 'main' into elef/user-896-introduce-usereverification
panteliselef 1e4e852
highlight experimental utilities
panteliselef b47124a
align usage for consistency
panteliselef 58238d6
Merge branch 'main' into elef/user-896-introduce-usereverification
panteliselef 51f3a0e
Merge branch 'main' into elef/user-896-introduce-usereverification
panteliselef f86c9cb
simplify types of `__experimental_useReverification`
panteliselef File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,5 @@ | ||
| --- | ||
| "@clerk/nextjs": minor | ||
| --- | ||
|
|
||
| Bug fix: For next>=14 applications resolve `__unstable__onBeforeSetActive` once `invalidateCacheAction` resolves. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,33 @@ | ||
| --- | ||
| "@clerk/nextjs": minor | ||
| "@clerk/clerk-react": minor | ||
| --- | ||
|
|
||
| Introduce a new experimental hook called `useReverification` that makes it easy to handle reverification errors. | ||
| It returns a high order function (HOF) and allows developers to wrap any function that triggers a fetch request which might fail due to a user's session verification status. | ||
| When such error is returned, the recommended UX is to offer a way to the user to recover by re-verifying their credentials. | ||
| This helper will automatically handle this flow in the developer's behalf, by displaying a modal the end-user can interact with. | ||
| Upon completion, the original request that previously failed, will be retried (only once). | ||
|
|
||
| Example with clerk-js methods. | ||
| ```tsx | ||
| import { __experimental_useReverification as useReverification } from '@clerk/nextjs'; | ||
|
|
||
| function DeleteAccount() { | ||
| const { user } = useUser(); | ||
| const [deleteUserAccount] = useReverification(() => { | ||
| if (!user) return; | ||
| return user.delete() | ||
| }); | ||
|
|
||
| return <> | ||
| <button | ||
| onClick={async () => { | ||
| await deleteUserAccount(); | ||
| }}> | ||
| Delete account | ||
| </button> | ||
| </> | ||
| } | ||
|
|
||
| ``` | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,7 @@ | ||
| --- | ||
| "@clerk/shared": minor | ||
| --- | ||
|
|
||
| Introduce experimental reverification error helpers. | ||
| - `reverificationMismatch` returns the error as an object which can later be used as a return value from a React Server Action. | ||
| - `reverificationMismatchResponse` returns a Response with the above object serialized. It can be used in any Backend Javascript frameworks that supports `Response`. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,5 @@ | ||
| --- | ||
| "@clerk/clerk-js": patch | ||
| --- | ||
|
|
||
| Chore: Replace beforeEmit with an explicit call after `setActive`, inside the experimental UserVerification. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
30 changes: 30 additions & 0 deletions
30
...emplates/next-app-router/src/app/(reverification)/action-with-use-reverification/page.tsx
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,30 @@ | ||
| 'use client'; | ||
| import { useState, useTransition } from 'react'; | ||
| import { __experimental_useReverification as useReverification } from '@clerk/nextjs'; | ||
| import { logUserIdActionReverification } from '@/app/(reverification)/actions'; | ||
|
|
||
| function Page() { | ||
| const [logUserWithReverification] = useReverification(logUserIdActionReverification); | ||
| const [pending, startTransition] = useTransition(); | ||
| const [res, setRes] = useState(null); | ||
|
|
||
| return ( | ||
| <> | ||
| <button | ||
| disabled={pending} | ||
| onClick={() => { | ||
| startTransition(async () => { | ||
| await logUserWithReverification().then(e => { | ||
| setRes(e as any); | ||
| }); | ||
| }); | ||
| }} | ||
| > | ||
| LogUserId | ||
| </button> | ||
| <pre>{JSON.stringify(res)}</pre> | ||
| </> | ||
| ); | ||
| } | ||
|
|
||
| export default Page; |
27 changes: 27 additions & 0 deletions
27
integration/templates/next-app-router/src/app/(reverification)/actions.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,27 @@ | ||
| 'use server'; | ||
|
|
||
| import { auth } from '@clerk/nextjs/server'; | ||
| import { __experimental_reverificationMismatch as reverificationMismatch } from '@clerk/shared/authorization-errors'; | ||
|
|
||
| const logUserIdActionReverification = async () => { | ||
| const { userId, has } = await auth.protect(); | ||
|
|
||
| const config = { | ||
| level: 'secondFactor', | ||
| afterMinutes: 1, | ||
| } as const; | ||
|
|
||
| const userNeedsReverification = !has({ | ||
| __experimental_reverification: config, | ||
| }); | ||
|
|
||
| if (userNeedsReverification) { | ||
| return reverificationMismatch(config); | ||
| } | ||
|
|
||
| return { | ||
| userId, | ||
| }; | ||
| }; | ||
|
|
||
| export { logUserIdActionReverification }; |
23 changes: 23 additions & 0 deletions
23
integration/templates/next-app-router/src/app/(reverification)/button-action.tsx
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,23 @@ | ||
| 'use client'; | ||
| import { useState, useTransition } from 'react'; | ||
|
|
||
| export function ButtonAction({ action }: { action: () => Promise<any> }) { | ||
| const [pending, startTransition] = useTransition(); | ||
| const [res, setRes] = useState(null); | ||
|
|
||
| return ( | ||
| <> | ||
| <button | ||
| disabled={pending} | ||
| onClick={() => { | ||
| startTransition(async () => { | ||
| await action().then(setRes); | ||
| }); | ||
| }} | ||
| > | ||
| LogUserId | ||
| </button> | ||
| <pre>{JSON.stringify(res)}</pre> | ||
| </> | ||
| ); | ||
| } |
8 changes: 8 additions & 0 deletions
8
...tion/templates/next-app-router/src/app/(reverification)/requires-re-verification/page.tsx
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,8 @@ | ||
| import { logUserIdActionReverification } from '../actions'; | ||
| import { ButtonAction } from '../button-action'; | ||
|
|
||
| function Page() { | ||
| return <ButtonAction action={logUserIdActionReverification} />; | ||
| } | ||
|
|
||
| export default Page; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,27 @@ | ||
| import type { Browser, BrowserContext } from '@playwright/test'; | ||
|
|
||
| import type { createAppPageObject } from './appPageObject'; | ||
| import { common } from './commonPageObject'; | ||
|
|
||
| export type EnchancedPage = ReturnType<typeof createAppPageObject>; | ||
| export type TestArgs = { page: EnchancedPage; context: BrowserContext; browser: Browser }; | ||
|
|
||
| export const createUserVerificationComponentPageObject = (testArgs: TestArgs) => { | ||
| const { page } = testArgs; | ||
| const self = { | ||
| ...common(testArgs), | ||
| waitForMounted: (selector = '.cl-userVerification-root') => { | ||
| return page.waitForSelector(selector, { state: 'attached' }); | ||
| }, | ||
| getUseAnotherMethodLink: () => { | ||
| return page.getByRole('link', { name: /use another method/i }); | ||
| }, | ||
| getAltMethodsEmailCodeButton: () => { | ||
| return page.getByRole('button', { name: /email code to/i }); | ||
| }, | ||
| getAltMethodsEmailLinkButton: () => { | ||
| return page.getByRole('button', { name: /email link to/i }); | ||
| }, | ||
| }; | ||
| return self; | ||
| }; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,104 @@ | ||
| import type { OrganizationMembershipRole } from '@clerk/backend'; | ||
| import { expect, test } from '@playwright/test'; | ||
|
|
||
| import { appConfigs } from '../presets'; | ||
| import type { FakeOrganization, FakeUser } from '../testUtils'; | ||
| import { createTestUtils, testAgainstRunningApps } from '../testUtils'; | ||
|
|
||
| const utils = [ | ||
| 'action', | ||
| // , 'route' | ||
| ]; | ||
| const capitalize = (type: string) => type[0].toUpperCase() + type.slice(1); | ||
| testAgainstRunningApps({ withEnv: [appConfigs.envs.withReverification] })( | ||
| '@nextjs require re-verification', | ||
| ({ app }) => { | ||
| test.describe.configure({ mode: 'parallel' }); | ||
|
|
||
| let fakeAdmin: FakeUser; | ||
| let fakeViewer: FakeUser; | ||
| let fakeOrganization: FakeOrganization; | ||
|
|
||
| test.beforeAll(async () => { | ||
| const m = createTestUtils({ app }); | ||
| fakeAdmin = m.services.users.createFakeUser(); | ||
| const admin = await m.services.users.createBapiUser(fakeAdmin); | ||
| fakeOrganization = await m.services.users.createFakeOrganization(admin.id); | ||
| fakeViewer = m.services.users.createFakeUser(); | ||
| const viewer = await m.services.users.createBapiUser(fakeViewer); | ||
| await m.services.clerk.organizations.createOrganizationMembership({ | ||
| organizationId: fakeOrganization.organization.id, | ||
| role: 'org:viewer' as OrganizationMembershipRole, | ||
| userId: viewer.id, | ||
| }); | ||
| }); | ||
|
|
||
| test.afterAll(async () => { | ||
| await fakeOrganization.delete(); | ||
| await fakeViewer.deleteIfExists(); | ||
| await fakeAdmin.deleteIfExists(); | ||
| await app.teardown(); | ||
| }); | ||
|
|
||
| utils.forEach(type => { | ||
| test(`reverification error from ${capitalize(type)}`, async ({ page, context }) => { | ||
| test.setTimeout(270_000); | ||
| const u = createTestUtils({ app, page, context }); | ||
|
|
||
| await u.po.signIn.goTo(); | ||
| await u.po.signIn.waitForMounted(); | ||
| await u.po.signIn.signInWithEmailAndInstantPassword({ email: fakeAdmin.email, password: fakeAdmin.password }); | ||
| await u.po.expect.toBeSignedIn(); | ||
|
|
||
| await u.po.organizationSwitcher.goTo(); | ||
| await u.po.organizationSwitcher.waitForMounted(); | ||
| await u.po.organizationSwitcher.waitForAnOrganizationToSelected(); | ||
|
|
||
| await u.page.goToRelative(`/requires-re-verification`); | ||
| await u.page.getByRole('button', { name: /LogUserId/i }).click(); | ||
| await expect(u.page.getByText(/\{\s*"userId"\s*:\s*"user_[^"]+"\s*\}/i)).toBeVisible(); | ||
|
|
||
| const total = 1000 * 120; | ||
| await page.waitForTimeout(total / 3); | ||
| await page.waitForTimeout(total / 3); | ||
| await u.po.userProfile.goTo(); | ||
| await page.waitForTimeout(total / 3); | ||
| await u.page.goToRelative(`/requires-re-verification`); | ||
| await u.page.getByRole('button', { name: /LogUserId/i }).click(); | ||
| await expect( | ||
| u.page.getByText( | ||
| /\{\s*"clerk_error"\s*:\s*\{\s*"type"\s*:\s*"forbidden"\s*,\s*"reason"\s*:\s*"reverification-mismatch"\s*,\s*"metadata"\s*:\s*\{\s*"reverification"\s*:\s*\{\s*"level"\s*:\s*"secondFactor"\s*,\s*"afterMinutes"\s*:\s*1\s*\}\s*\}\s*\}\s*\}/i, | ||
| ), | ||
| ).toBeVisible(); | ||
| }); | ||
|
|
||
| test(`reverification recovery from ${capitalize(type)}`, async ({ page, context }) => { | ||
| test.setTimeout(270_000); | ||
| const u = createTestUtils({ app, page, context }); | ||
|
|
||
| await u.po.signIn.goTo(); | ||
| await u.po.signIn.waitForMounted(); | ||
| await u.po.signIn.signInWithEmailAndInstantPassword({ email: fakeAdmin.email, password: fakeAdmin.password }); | ||
| await u.po.expect.toBeSignedIn(); | ||
|
|
||
| await u.po.organizationSwitcher.goTo(); | ||
| await u.po.organizationSwitcher.waitForMounted(); | ||
| await u.po.organizationSwitcher.waitForAnOrganizationToSelected(); | ||
|
|
||
| await u.page.goToRelative(`/requires-re-verification`); | ||
| await u.page.getByRole('button', { name: /LogUserId/i }).click(); | ||
| await expect(u.page.getByText(/\{\s*"userId"\s*:\s*"user_[^"]+"\s*\}/i)).toBeVisible(); | ||
|
|
||
| const total = 1000 * 120; | ||
| await page.waitForTimeout(total / 3); | ||
| await page.waitForTimeout(total / 3); | ||
| await u.po.userProfile.goTo(); | ||
| await page.waitForTimeout(total / 3); | ||
| await u.page.goToRelative(`/action-with-use-reverification`); | ||
| await u.po.expect.toBeSignedIn(); | ||
| await u.page.getByRole('button', { name: /LogUserId/i }).click(); | ||
| await u.po.userVerification.waitForMounted(); | ||
| }); | ||
| }); | ||
| }, | ||
| ); |
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.