-
Notifications
You must be signed in to change notification settings - Fork 3.8k
feat(account): let users delete their own account #6831
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
Merged
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
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,42 @@ | ||
| import { deleteAccountContract, getAccountDeletionPlanContract } from '@/lib/api/contracts' | ||
| import { | ||
| defineInternalJsonRoute, | ||
| internalOrchestrationErrorPolicy, | ||
| internalRateLimits, | ||
| internalSessionAuth, | ||
| } from '@/lib/api/server/routes' | ||
| import { | ||
| deleteAccountUseCase, | ||
| previewAccountDeletionUseCase, | ||
| } from '@/lib/users/application/delete-account' | ||
| import { userAccountOperations } from '@/lib/users/application/operations' | ||
|
|
||
| export const dynamic = 'force-dynamic' | ||
|
|
||
| export const GET = defineInternalJsonRoute({ | ||
| contract: getAccountDeletionPlanContract, | ||
| auth: internalSessionAuth, | ||
| operation: userAccountOperations.previewDeletion, | ||
| rateLimit: internalRateLimits.none({ reason: 'Read-only preview of the caller’s own account' }), | ||
| errorPolicy: internalOrchestrationErrorPolicy, | ||
| mapInput: () => ({}), | ||
| useCase: previewAccountDeletionUseCase, | ||
| present: (plan) => ({ plan }), | ||
| }) | ||
|
|
||
| /** | ||
| * `AccountDeletionBlockedError` classifies itself as a conflict, so the shared | ||
| * orchestration policy renders a refused deletion as a 409 carrying the first | ||
| * blocker's sentence. The dialog lists every blocker from the GET above; this | ||
| * message covers only the race where one appears between the two calls. | ||
| */ | ||
| export const POST = defineInternalJsonRoute({ | ||
| contract: deleteAccountContract, | ||
| auth: internalSessionAuth, | ||
| operation: userAccountOperations.delete, | ||
| rateLimit: internalRateLimits.none({ reason: 'Guarded by the email confirmation it requires' }), | ||
| errorPolicy: internalOrchestrationErrorPolicy, | ||
| mapInput: ({ body }) => ({ confirmEmail: body.confirmEmail }), | ||
| useCase: deleteAccountUseCase, | ||
| present: () => ({ success: true as const }), | ||
| }) |
160 changes: 160 additions & 0 deletions
160
...p/workspace/[workspaceId]/settings/components/general/components/delete-account-modal.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,160 @@ | ||
| 'use client' | ||
|
|
||
| import { useState } from 'react' | ||
| import { ChipConfirmModal, ChipModalError, ChipModalField } from '@sim/emcn' | ||
| import { createLogger } from '@sim/logger' | ||
| import { sleep } from '@sim/utils/helpers' | ||
| import { formatQuotedNameList, normalizeEmail } from '@sim/utils/string' | ||
| import { signOut } from '@/lib/auth/auth-client' | ||
| import { useAccountDeletionPlan, useDeleteAccount } from '@/hooks/queries/account-deletion' | ||
| import { clearUserData } from '@/stores' | ||
|
|
||
| const logger = createLogger('DeleteAccountModal') | ||
|
|
||
| /** Matches the naming used in the server's blocker sentences. */ | ||
| const MAX_NAMES_LISTED = 3 | ||
|
|
||
| /** How long the post-deletion sign-out and store cleanup may take before the redirect goes anyway. */ | ||
| const SIGN_OUT_TIMEOUT_MS = 3000 | ||
|
|
||
| interface DeleteAccountModalProps { | ||
| open: boolean | ||
| onOpenChange: (open: boolean) => void | ||
| /** The signed-in account's email, which must be retyped to confirm. */ | ||
| email: string | ||
| } | ||
|
|
||
| function names(workspaces: { name: string }[]): string { | ||
| return formatQuotedNameList( | ||
| workspaces.map((workspace) => workspace.name), | ||
| MAX_NAMES_LISTED | ||
| ) | ||
| } | ||
|
|
||
| /** | ||
| * Confirms and performs account deletion. | ||
| * | ||
| * The dialog is deliberately explicit rather than alarming: it names every | ||
| * workspace that goes, every workspace that changes hands, and — when the account | ||
| * cannot be deleted yet — exactly what has to happen first. Retyping the account's | ||
| * own email address is the only guard, which is the point: the decision should | ||
| * cost a deliberate action, not a hunt for the right button. | ||
| */ | ||
| export function DeleteAccountModal({ open, onOpenChange, email }: DeleteAccountModalProps) { | ||
| const [confirmEmail, setConfirmEmail] = useState('') | ||
| const { data: plan, isFetching: isPlanFetching, error: planError } = useAccountDeletionPlan(open) | ||
| const deleteAccount = useDeleteAccount() | ||
|
|
||
| const blockers = plan?.blockers ?? [] | ||
| const toDelete = plan?.workspacesToDelete ?? [] | ||
| const toTransfer = plan?.workspacesToTransfer ?? [] | ||
| const isBlocked = blockers.length > 0 | ||
| const isConfirmed = normalizeEmail(confirmEmail) === normalizeEmail(email) | ||
| const isPending = deleteAccount.isPending | ||
|
|
||
| const close = () => { | ||
| onOpenChange(false) | ||
| setConfirmEmail('') | ||
| deleteAccount.reset() | ||
| } | ||
|
|
||
| const handleDelete = () => { | ||
| deleteAccount.mutate( | ||
| { confirmEmail }, | ||
| { | ||
| onSuccess: async () => { | ||
| /** | ||
| * The session row is already gone, so signing out can only fail by | ||
| * telling us so — what matters is that its cookie is dropped and no | ||
| * cached client state survives the redirect. The race bounds that | ||
| * cleanup: the account is deleted either way, so a request left hanging | ||
| * must not strand the user on "Deleting..." forever. The redirect is a | ||
| * full document load, which discards anything the cleanup missed. | ||
| */ | ||
| await Promise.race([ | ||
| Promise.allSettled([signOut(), clearUserData()]), | ||
| sleep(SIGN_OUT_TIMEOUT_MS), | ||
| ]) | ||
| window.location.href = '/login?fromLogout=true' | ||
| }, | ||
| onError: (error) => { | ||
| logger.error('Account deletion failed', { error }) | ||
| }, | ||
| } | ||
| ) | ||
| } | ||
|
|
||
| const errorMessage = | ||
| deleteAccount.error?.message ?? | ||
| (planError ? 'Could not check whether this account can be deleted. Try again.' : null) | ||
|
|
||
| return ( | ||
| <ChipConfirmModal | ||
| open={open} | ||
| onOpenChange={(next) => { | ||
| if (!next) close() | ||
| }} | ||
| size='md' | ||
| title='Delete account' | ||
| confirm={{ | ||
| label: 'Delete account', | ||
| pendingLabel: 'Deleting...', | ||
| onClick: handleDelete, | ||
| pending: isPending, | ||
| disabled: isBlocked || isPlanFetching || !isConfirmed || !plan, | ||
| disabledTooltip: isBlocked | ||
| ? 'Resolve the items above first' | ||
| : isConfirmed | ||
| ? undefined | ||
| : 'Enter your account email to confirm', | ||
| }} | ||
| > | ||
| {isBlocked ? ( | ||
| <div className='flex flex-col gap-2 px-2'> | ||
| <p className='text-[var(--text-primary)] text-sm'>Your account can’t be deleted yet:</p> | ||
| <ul className='flex list-disc flex-col gap-1 pl-4'> | ||
| {blockers.map((blocker) => ( | ||
| <li key={blocker.code} className='text-[var(--text-secondary)] text-sm'> | ||
| {blocker.message} | ||
| </li> | ||
| ))} | ||
| </ul> | ||
| </div> | ||
| ) : ( | ||
| <div className='flex flex-col gap-2 px-2'> | ||
| <p className='text-[var(--text-primary)] text-sm'> | ||
| This permanently deletes <span className='font-medium'>{email}</span> along with its | ||
| workflows, chats, files, knowledge bases and credentials.{' '} | ||
| <span className='text-[var(--text-error)]'>This cannot be undone.</span> | ||
| </p> | ||
| {toDelete.length > 0 && ( | ||
| <p className='text-[var(--text-secondary)] text-sm'> | ||
| {toDelete.length === 1 ? 'The workspace ' : 'The workspaces '} | ||
| <span className='text-[var(--text-primary)]'>{names(toDelete)}</span> and everything | ||
| in {toDelete.length === 1 ? 'it' : 'them'} will be deleted. | ||
| </p> | ||
| )} | ||
| {toTransfer.length > 0 && ( | ||
| <p className='text-[var(--text-secondary)] text-sm'> | ||
| Billing for <span className='text-[var(--text-primary)]'>{names(toTransfer)}</span>{' '} | ||
| moves to another admin. Nothing in {toTransfer.length === 1 ? 'it' : 'them'} changes. | ||
| </p> | ||
| )} | ||
| </div> | ||
| )} | ||
| {!isBlocked && ( | ||
| <ChipModalField | ||
| type='email' | ||
| title='Confirm your email' | ||
| value={confirmEmail} | ||
| onChange={setConfirmEmail} | ||
| placeholder={email} | ||
| autoComplete='off' | ||
| disabled={isPending || isPlanFetching} | ||
| required | ||
| /> | ||
| )} | ||
| <ChipModalError>{errorMessage}</ChipModalError> | ||
| </ChipConfirmModal> | ||
| ) | ||
| } | ||
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,54 @@ | ||
| import { useMutation, useQuery } from '@tanstack/react-query' | ||
| import { requestJson } from '@/lib/api/client/request' | ||
| import { | ||
| type AccountDeletionPlan, | ||
| type DeleteAccountBody, | ||
| deleteAccountContract, | ||
| getAccountDeletionPlanContract, | ||
| } from '@/lib/api/contracts/user' | ||
|
|
||
| export const accountDeletionKeys = { | ||
| all: ['account-deletion'] as const, | ||
| plan: () => [...accountDeletionKeys.all, 'plan'] as const, | ||
| } | ||
|
|
||
| /** | ||
| * Zero: the plan is a consent disclosure, so every dialog open must refetch — its | ||
| * blockers must reflect the account as it is right now, and a workspace that | ||
| * gained an admin a minute ago changes the answer. | ||
| * | ||
| * The dialog stays mounted while closed, so the previous open's plan is still in | ||
| * the cache and `isLoading` is false during that refetch. The dialog therefore | ||
| * holds its confirm on `isFetching`, not `isLoading`, until fresh data lands; | ||
| * `gcTime: 0` only evicts once the settings panel itself unmounts. | ||
| */ | ||
| export const ACCOUNT_DELETION_PLAN_STALE_TIME = 0 | ||
|
|
||
| async function fetchAccountDeletionPlan(signal?: AbortSignal): Promise<AccountDeletionPlan> { | ||
| const data = await requestJson(getAccountDeletionPlanContract, { signal }) | ||
| return data.plan | ||
| } | ||
|
|
||
| export function useAccountDeletionPlan(enabled: boolean) { | ||
| return useQuery({ | ||
| queryKey: accountDeletionKeys.plan(), | ||
| queryFn: ({ signal }) => fetchAccountDeletionPlan(signal), | ||
| enabled, | ||
| staleTime: ACCOUNT_DELETION_PLAN_STALE_TIME, | ||
| gcTime: 0, | ||
| retry: false, | ||
| }) | ||
| } | ||
|
|
||
| /** | ||
| * Succeeds exactly once per account: the session that authorized it is gone by | ||
| * the time the response lands, so there is no cache left to invalidate. The | ||
| * caller is responsible for clearing local state and sending the user to sign-in. | ||
| */ | ||
| export function useDeleteAccount() { | ||
| return useMutation({ | ||
| mutationFn: async (body: DeleteAccountBody) => { | ||
| await requestJson(deleteAccountContract, { body }) | ||
| }, | ||
| }) | ||
| } |
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.
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.