feat(settings): let users delete their account
Build, Test & Push Frontend / quality-check (push) Successful in 16s
Build, Test & Push Frontend / docker (push) Successful in 26s

This commit is contained in:
lobo committed 2026-09-27 11:46:22 +02:00
1 parent cfceca5e5e
commit 46587dfb5c
8 files changed
+374 -2

No files matched your search

+112
View File
@@ -0,0 +1,112 @@
import {useState} from 'react';
import {useNavigate} from 'react-router-dom';
import {useTranslation} from 'react-i18next';
import {Loader2, Trash2} from 'lucide-react';
import {toast} from 'sonner';
import {Button} from '@/components/ui/button';
import {Card, CardContent, CardHeader, CardTitle} from '@/components/ui/card';
import {
Dialog,
DialogClose,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
DialogTrigger,
} from '@/components/ui/dialog';
import {Input} from '@/components/ui/input';
import {Label} from '@/components/ui/label';
import {useResetAppearance} from '../context/PreferencesContext.jsx';
import useSessionExpired from '../hooks/useSessionExpired.js';
import {deleteAccount} from '../utils/account.js';
import {clearSession} from '../utils/auth.js';
const sameEmail = (typed, email) => !!email && typed.trim().toLowerCase() === email.toLowerCase();
/**
* "Delete my account": Auth blocks the account at once and removes it after 30 days. The user types the own
* email against a misclick and the password against a borrowed session.
*/
export default function DeleteAccountCard({email}) {
const {t} = useTranslation();
const navigate = useNavigate();
const resetAppearance = useResetAppearance();
const expireSession = useSessionExpired();
const [typedEmail, setTypedEmail] = useState('');
const [password, setPassword] = useState('');
const [busy, setBusy] = useState(false);
const confirm = async () => {
setBusy(true);
try {
const response = await deleteAccount(password);
if (response.status === 204) {
clearSession();
resetAppearance();
toast.success(t('SETTINGS.DELETE_ACCOUNT.DONE'));
navigate('/', {replace: true});
return;
}
if (response.status === 401) {
expireSession();
} else if (response.status === 403) {
toast.error(t('SETTINGS.DELETE_ACCOUNT.WRONG_PASSWORD'));
} else if (response.status === 429) {
const minutes = Math.ceil(Number(response.headers.get('Retry-After') ?? 900) / 60);
toast.error(t('SETTINGS.DELETE_ACCOUNT.TOO_MANY', {minutes}));
} else {
toast.error(t('SETTINGS.DELETE_ACCOUNT.ERROR'));
}
} catch (err) {
console.error('Delete account error:', err);
toast.error(t('INFO.ERROR.NETWORK_FAILURE'));
}
setBusy(false);
};
return (
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2"><Trash2 className="size-4 text-destructive"/>{t('SETTINGS.DELETE_ACCOUNT.TITLE')}</CardTitle>
</CardHeader>
<CardContent className="space-y-3">
<p className="text-sm text-muted-foreground">{t('SETTINGS.DELETE_ACCOUNT.EXPLAIN')}</p>
<Dialog onOpenChange={(open) => { if (!open) { setTypedEmail(''); setPassword(''); } }}>
<DialogTrigger asChild>
<Button type="button" variant="outline" className="border-destructive text-destructive">
<Trash2/>{t('SETTINGS.DELETE_ACCOUNT.BUTTON')}
</Button>
</DialogTrigger>
<DialogContent>
<DialogHeader>
<DialogTitle>{t('SETTINGS.DELETE_ACCOUNT.DIALOG_TITLE')}</DialogTitle>
<DialogDescription>{t('SETTINGS.DELETE_ACCOUNT.EXPLAIN')}</DialogDescription>
</DialogHeader>
<div className="space-y-2">
<Label htmlFor="deleteEmail">{t('SETTINGS.DELETE_ACCOUNT.TYPE_EMAIL')}</Label>
<Input id="deleteEmail" type="email" autoComplete="off" value={typedEmail}
onChange={(event) => setTypedEmail(event.target.value)}/>
</div>
<div className="space-y-2">
<Label htmlFor="deletePassword">{t('SETTINGS.DELETE_ACCOUNT.PASSWORD')}</Label>
<Input id="deletePassword" type="password" autoComplete="current-password" value={password}
onChange={(event) => setPassword(event.target.value)}/>
</div>
<DialogFooter>
<DialogClose asChild>
<Button type="button" variant="outline">{t('SETTINGS.DELETE_ACCOUNT.CANCEL')}</Button>
</DialogClose>
<Button type="button" variant="destructive" onClick={confirm}
disabled={busy || !password || !sameEmail(typedEmail, email)}>
{busy ? <Loader2 className="animate-spin"/> : <Trash2/>}
{t('SETTINGS.DELETE_ACCOUNT.CONFIRM')}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</CardContent>
</Card>
);
}
+110
View File
@@ -0,0 +1,110 @@
// @vitest-environment jsdom
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
import {cleanup, fireEvent, render, screen, waitFor} from '@testing-library/react';
import {MemoryRouter, Route, Routes} from 'react-router-dom';
import {toast} from 'sonner';
import DeleteAccountCard from './DeleteAccountCard.jsx';
vi.mock('react-i18next', () => import('../test/i18n-mock.js'));
vi.mock('sonner', () => ({toast: {success: vi.fn(), error: vi.fn()}}));
const EMAIL = 'player@example.com';
const answer = (status, headers = {}) => ({ok: status < 300, status, headers: new Headers(headers), json: async () => ({})});
const renderCard = () => render(
<MemoryRouter initialEntries={['/settings']}>
<Routes>
<Route path="/settings" element={<DeleteAccountCard email={EMAIL}/>}/>
<Route path="/" element={<p>landing</p>}/>
<Route path="/login" element={<p>login</p>}/>
</Routes>
</MemoryRouter>);
const openAndFill = (email, password) => {
fireEvent.click(screen.getByRole('button', {name: 'SETTINGS.DELETE_ACCOUNT.BUTTON'}));
fireEvent.change(screen.getByLabelText('SETTINGS.DELETE_ACCOUNT.TYPE_EMAIL'), {target: {value: email}});
fireEvent.change(screen.getByLabelText('SETTINGS.DELETE_ACCOUNT.PASSWORD'), {target: {value: password}});
};
const confirmButton = () => screen.getByRole('button', {name: 'SETTINGS.DELETE_ACCOUNT.CONFIRM'});
describe('DeleteAccountCard', () => {
beforeEach(() => {
localStorage.setItem('tbp_session', '1');
globalThis.fetch = vi.fn(async () => answer(204));
});
afterEach(() => {
cleanup();
localStorage.clear();
vi.clearAllMocks();
});
it('asks for the own email and a password before it deletes', () => {
renderCard();
openAndFill('someone@else.com', 'secret');
expect(confirmButton().disabled).toBe(true);
fireEvent.change(screen.getByLabelText('SETTINGS.DELETE_ACCOUNT.TYPE_EMAIL'), {target: {value: ' Player@Example.com '}});
expect(confirmButton().disabled).toBe(false);
});
it('sends the password, ends the session and goes to the landing page', async () => {
renderCard();
openAndFill(EMAIL, 'secret');
fireEvent.click(confirmButton());
expect(await screen.findByText('landing')).toBeTruthy();
const [url, init] = fetch.mock.calls[0];
expect(url).toMatch(/\/api\/users\/me$/);
expect(init.method).toBe('DELETE');
expect(JSON.parse(init.body)).toEqual({password: 'secret'});
expect(localStorage.getItem('tbp_session')).toBeNull();
expect(toast.success).toHaveBeenCalledWith('SETTINGS.DELETE_ACCOUNT.DONE');
});
it('keeps the dialog open on a wrong password', async () => {
fetch.mockResolvedValue(answer(403));
renderCard();
openAndFill(EMAIL, 'wrong');
fireEvent.click(confirmButton());
await waitFor(() => expect(toast.error).toHaveBeenCalledWith('SETTINGS.DELETE_ACCOUNT.WRONG_PASSWORD'));
expect(confirmButton()).toBeTruthy();
expect(localStorage.getItem('tbp_session')).toBe('1');
});
it('shows the lock message after too many wrong passwords', async () => {
fetch.mockResolvedValue(answer(429, {'Retry-After': '900'}));
renderCard();
openAndFill(EMAIL, 'wrong');
fireEvent.click(confirmButton());
await waitFor(() => expect(toast.error).toHaveBeenCalledWith('SETTINGS.DELETE_ACCOUNT.TOO_MANY'));
});
it('opens the login page when the session is gone', async () => {
fetch.mockResolvedValue(answer(401));
renderCard();
openAndFill(EMAIL, 'secret');
fireEvent.click(confirmButton());
expect(await screen.findByText('login')).toBeTruthy();
});
it('shows the network error when Auth does not answer', async () => {
fetch.mockRejectedValue(new TypeError('Failed to fetch'));
renderCard();
openAndFill(EMAIL, 'secret');
fireEvent.click(confirmButton());
await waitFor(() => expect(toast.error).toHaveBeenCalledWith('INFO.ERROR.NETWORK_FAILURE'));
});
});
+106
View File
@@ -0,0 +1,106 @@
import * as React from "react"
import { XIcon } from "lucide-react"
import { Dialog as DialogPrimitive } from "radix-ui"
import { cn } from "@/lib/utils"
function Dialog({
...props
}) {
return <DialogPrimitive.Root data-slot="dialog" {...props} />
}
function DialogTrigger({
...props
}) {
return <DialogPrimitive.Trigger data-slot="dialog-trigger" {...props} />
}
function DialogClose({
...props
}) {
return <DialogPrimitive.Close data-slot="dialog-close" {...props} />
}
function DialogContent({
className,
children,
...props
}) {
return (
<DialogPrimitive.Portal>
<DialogPrimitive.Overlay
data-slot="dialog-overlay"
className="fixed inset-0 z-50 bg-black/50 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0"
/>
<DialogPrimitive.Content
data-slot="dialog-content"
className={cn(
"fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border bg-background p-6 shadow-lg sm:max-w-lg",
className
)}
{...props}>
{children}
<DialogPrimitive.Close
className="absolute top-4 right-4 rounded-xs opacity-70 transition-opacity hover:opacity-100 focus:outline-hidden focus-visible:ring-2 focus-visible:ring-ring">
<XIcon className="size-4" />
<span className="sr-only">Close</span>
</DialogPrimitive.Close>
</DialogPrimitive.Content>
</DialogPrimitive.Portal>
)
}
function DialogHeader({
className,
...props
}) {
return <div data-slot="dialog-header" className={cn("flex flex-col gap-2 text-left", className)} {...props} />
}
function DialogFooter({
className,
...props
}) {
return (
<div
data-slot="dialog-footer"
className={cn("flex flex-col-reverse gap-2 sm:flex-row sm:justify-end", className)}
{...props} />
)
}
function DialogTitle({
className,
...props
}) {
return (
<DialogPrimitive.Title
data-slot="dialog-title"
className={cn("text-lg leading-none font-semibold", className)}
{...props} />
)
}
function DialogDescription({
className,
...props
}) {
return (
<DialogPrimitive.Description
data-slot="dialog-description"
className={cn("text-sm text-muted-foreground", className)}
{...props} />
)
}
export {
Dialog,
DialogClose,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
DialogTrigger,
}