Implement account deletion system

This commit is contained in:
gpt-engineer-app[bot]
2025-10-12 14:17:54 +00:00
parent 21ba87a664
commit 3a38b47108
10 changed files with 1429 additions and 50 deletions

View File

@@ -0,0 +1,282 @@
import { useState } from 'react';
import { AlertDialog, AlertDialogContent, AlertDialogHeader, AlertDialogTitle, AlertDialogDescription, AlertDialogFooter } from '@/components/ui/alert-dialog';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Checkbox } from '@/components/ui/checkbox';
import { Alert, AlertDescription } from '@/components/ui/alert';
import { supabase } from '@/integrations/supabase/client';
import { useToast } from '@/hooks/use-toast';
import { Loader2, AlertTriangle, Info } from 'lucide-react';
interface AccountDeletionDialogProps {
open: boolean;
onOpenChange: (open: boolean) => void;
userEmail: string;
onDeletionRequested: () => void;
}
export function AccountDeletionDialog({ open, onOpenChange, userEmail, onDeletionRequested }: AccountDeletionDialogProps) {
const [step, setStep] = useState<'warning' | 'confirm' | 'code'>('warning');
const [loading, setLoading] = useState(false);
const [confirmationCode, setConfirmationCode] = useState('');
const [codeReceived, setCodeReceived] = useState(false);
const [scheduledDate, setScheduledDate] = useState<string>('');
const { toast } = useToast();
const handleRequestDeletion = async () => {
setLoading(true);
try {
const { data, error } = await supabase.functions.invoke('request-account-deletion', {
body: {},
});
if (error) throw error;
setScheduledDate(data.scheduled_deletion_at);
setStep('code');
onDeletionRequested();
toast({
title: 'Deletion Requested',
description: 'Check your email for the confirmation code.',
});
} catch (error: any) {
toast({
variant: 'destructive',
title: 'Error',
description: error.message || 'Failed to request account deletion',
});
} finally {
setLoading(false);
}
};
const handleConfirmDeletion = async () => {
if (!confirmationCode || confirmationCode.length !== 6) {
toast({
variant: 'destructive',
title: 'Invalid Code',
description: 'Please enter a 6-digit confirmation code',
});
return;
}
setLoading(true);
try {
const { error } = await supabase.functions.invoke('confirm-account-deletion', {
body: { confirmation_code: confirmationCode },
});
if (error) throw error;
toast({
title: 'Account Deleted',
description: 'Your account has been permanently deleted.',
});
// Sign out and redirect
await supabase.auth.signOut();
window.location.href = '/';
} catch (error: any) {
toast({
variant: 'destructive',
title: 'Error',
description: error.message || 'Failed to confirm deletion',
});
} finally {
setLoading(false);
}
};
const handleResendCode = async () => {
setLoading(true);
try {
const { error } = await supabase.functions.invoke('resend-deletion-code', {
body: {},
});
if (error) throw error;
toast({
title: 'Code Resent',
description: 'A new confirmation code has been sent to your email.',
});
} catch (error: any) {
toast({
variant: 'destructive',
title: 'Error',
description: error.message || 'Failed to resend code',
});
} finally {
setLoading(false);
}
};
const handleClose = () => {
setStep('warning');
setConfirmationCode('');
setCodeReceived(false);
onOpenChange(false);
};
return (
<AlertDialog open={open} onOpenChange={handleClose}>
<AlertDialogContent className="max-w-2xl">
<AlertDialogHeader>
<AlertDialogTitle className="flex items-center gap-2 text-destructive">
<AlertTriangle className="w-5 h-5" />
Delete Account
</AlertDialogTitle>
<AlertDialogDescription className="text-left space-y-4">
{step === 'warning' && (
<>
<Alert>
<Info className="w-4 h-4" />
<AlertDescription>
This action will permanently delete your account after a 2-week waiting period. Please read carefully.
</AlertDescription>
</Alert>
<div className="space-y-3">
<div>
<h4 className="font-semibold text-foreground mb-2">What will be DELETED:</h4>
<ul className="space-y-1 text-sm">
<li> Your profile information (username, bio, avatar, etc.)</li>
<li> Your reviews and ratings</li>
<li> Your personal preferences and settings</li>
</ul>
</div>
<div>
<h4 className="font-semibold text-foreground mb-2">What will be PRESERVED:</h4>
<ul className="space-y-1 text-sm">
<li> Your database submissions (park creations, ride additions, edits)</li>
<li> Photos you've uploaded (shown as "Submitted by [deleted user]")</li>
<li>✓ Edit history and contributions</li>
</ul>
</div>
<Alert variant="destructive">
<AlertDescription>
<strong>2-Week Waiting Period:</strong> Your account will be deactivated immediately, but you'll have 14 days to cancel before permanent deletion. You'll receive a confirmation code via email.
</AlertDescription>
</Alert>
</div>
</>
)}
{step === 'confirm' && (
<Alert variant="destructive">
<AlertDescription>
Are you absolutely sure? This will deactivate your account immediately and schedule it for permanent deletion in 2 weeks.
</AlertDescription>
</Alert>
)}
{step === 'code' && (
<div className="space-y-4">
<Alert>
<Info className="w-4 h-4" />
<AlertDescription>
Your account has been deactivated and will be deleted on{' '}
<strong>{scheduledDate ? new Date(scheduledDate).toLocaleDateString() : '14 days from now'}</strong>.
</AlertDescription>
</Alert>
<p className="text-sm">
A 6-digit confirmation code has been sent to <strong>{userEmail}</strong>.
</p>
<div className="space-y-4">
<div className="space-y-2">
<Label htmlFor="confirmationCode">Confirmation Code</Label>
<Input
id="confirmationCode"
type="text"
placeholder="000000"
maxLength={6}
value={confirmationCode}
onChange={(e) => setConfirmationCode(e.target.value.replace(/\D/g, ''))}
className="text-center text-2xl tracking-widest"
/>
</div>
<div className="flex items-center space-x-2">
<Checkbox
id="codeReceived"
checked={codeReceived}
onCheckedChange={(checked) => setCodeReceived(checked === true)}
/>
<Label htmlFor="codeReceived" className="text-sm font-normal cursor-pointer">
I have received the code in my email
</Label>
</div>
<Button
variant="outline"
onClick={handleResendCode}
disabled={loading}
className="w-full"
>
{loading ? <Loader2 className="w-4 h-4 animate-spin" /> : 'Resend Code'}
</Button>
</div>
<Alert>
<AlertDescription className="text-xs">
Note: You cannot confirm deletion until the 2-week period has passed. You can cancel at any time during this period.
</AlertDescription>
</Alert>
</div>
)}
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
{step === 'warning' && (
<>
<Button variant="outline" onClick={handleClose}>
Cancel
</Button>
<Button variant="destructive" onClick={() => setStep('confirm')}>
Continue
</Button>
</>
)}
{step === 'confirm' && (
<>
<Button variant="outline" onClick={() => setStep('warning')}>
Go Back
</Button>
<Button
variant="destructive"
onClick={handleRequestDeletion}
disabled={loading}
>
{loading ? <Loader2 className="w-4 h-4 animate-spin mr-2" /> : null}
Request Deletion
</Button>
</>
)}
{step === 'code' && (
<>
<Button variant="outline" onClick={handleClose}>
Close
</Button>
<Button
variant="destructive"
onClick={handleConfirmDeletion}
disabled={loading || !codeReceived || confirmationCode.length !== 6}
>
{loading ? <Loader2 className="w-4 h-4 animate-spin mr-2" /> : null}
Confirm Deletion
</Button>
</>
)}
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
);
}

View File

@@ -1,4 +1,4 @@
import { useState } from 'react';
import { useState, useEffect } from 'react';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';
@@ -21,6 +21,8 @@ import { EmailChangeDialog } from './EmailChangeDialog';
import { Badge } from '@/components/ui/badge';
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert';
import { toast as sonnerToast } from 'sonner';
import { AccountDeletionDialog } from './AccountDeletionDialog';
import { DeletionStatusBanner } from './DeletionStatusBanner';
const profileSchema = z.object({
username: z.string().min(3).max(30).regex(/^[a-zA-Z0-9_-]+$/),
@@ -44,6 +46,8 @@ export function AccountProfileTab() {
const [cancellingEmail, setCancellingEmail] = useState(false);
const [avatarUrl, setAvatarUrl] = useState<string>(profile?.avatar_url || '');
const [avatarImageId, setAvatarImageId] = useState<string>(profile?.avatar_image_id || '');
const [showDeletionDialog, setShowDeletionDialog] = useState(false);
const [deletionRequest, setDeletionRequest] = useState<any>(null);
const form = useForm<ProfileFormData>({
resolver: zodResolver(profileSchema),
@@ -57,6 +61,26 @@ export function AccountProfileTab() {
}
});
// Check for existing deletion request on mount
useEffect(() => {
const checkDeletionRequest = async () => {
if (!user?.id) return;
const { data, error } = await supabase
.from('account_deletion_requests')
.select('*')
.eq('user_id', user.id)
.eq('status', 'pending')
.maybeSingle();
if (!error && data) {
setDeletionRequest(data);
}
};
checkDeletionRequest();
}, [user?.id]);
const onSubmit = async (data: ProfileFormData) => {
if (!user) return;
@@ -200,30 +224,36 @@ export function AccountProfileTab() {
}
};
const handleDeleteAccount = async () => {
if (!user) return;
try {
// This would typically involve multiple steps:
// 1. Anonymize or delete user data
// 2. Delete the auth user
// For now, we'll just show a message
toast({
title: 'Account deletion requested',
description: 'Please contact support to complete account deletion.',
variant: 'destructive'
});
} catch (error: any) {
toast({
title: 'Error',
description: error.message || 'Failed to delete account',
variant: 'destructive'
});
const handleDeletionRequested = async () => {
// Refresh deletion request data
const { data, error } = await supabase
.from('account_deletion_requests')
.select('*')
.eq('user_id', user!.id)
.eq('status', 'pending')
.maybeSingle();
if (!error && data) {
setDeletionRequest(data);
}
};
const handleDeletionCancelled = () => {
setDeletionRequest(null);
};
const isDeactivated = (profile as any)?.deactivated || false;
return (
<div className="space-y-8">
{/* Deletion Status Banner */}
{deletionRequest && (
<DeletionStatusBanner
scheduledDate={deletionRequest.scheduled_deletion_at}
onCancelled={handleDeletionCancelled}
/>
)}
{/* Profile Picture */}
<div className="space-y-4">
<h3 className="text-lg font-medium">Profile Picture</h3>
@@ -257,6 +287,7 @@ export function AccountProfileTab() {
id="username"
{...form.register('username')}
placeholder="Enter your username"
disabled={isDeactivated}
/>
{form.formState.errors.username && (
<p className="text-sm text-destructive">
@@ -325,9 +356,14 @@ export function AccountProfileTab() {
</div>
</div>
<Button type="submit" disabled={loading}>
<Button type="submit" disabled={loading || isDeactivated}>
{loading ? 'Saving...' : 'Save Changes'}
</Button>
{isDeactivated && (
<p className="text-sm text-muted-foreground">
Your account is deactivated. Profile editing is disabled.
</p>
)}
</form>
<Separator />
@@ -440,39 +476,36 @@ export function AccountProfileTab() {
<CardHeader>
<CardTitle className="text-destructive">Danger Zone</CardTitle>
<CardDescription>
These actions cannot be undone. Please be careful.
Permanently delete your account with a 2-week waiting period
</CardDescription>
</CardHeader>
<CardContent>
<AlertDialog open={showDeleteDialog} onOpenChange={setShowDeleteDialog}>
<AlertDialogTrigger asChild>
<Button variant="destructive" className="w-fit">
<Trash2 className="w-4 h-4 mr-2" />
Delete Account
</Button>
</AlertDialogTrigger>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Are you absolutely sure?</AlertDialogTitle>
<AlertDialogDescription>
This action cannot be undone. This will permanently delete your account
and remove all your data from our servers, including your reviews,
ride credits, and profile information.
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction
onClick={handleDeleteAccount}
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
>
Yes, delete my account
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
<CardContent className="space-y-4">
<div className="flex items-center justify-between">
<div className="space-y-1">
<p className="text-sm font-medium">Delete Account</p>
<p className="text-sm text-muted-foreground">
Your profile and reviews will be deleted, but your contributions (submissions, photos) will be preserved
</p>
</div>
<Button
variant="destructive"
onClick={() => setShowDeletionDialog(true)}
disabled={!!deletionRequest}
>
<Trash2 className="w-4 h-4 mr-2" />
{deletionRequest ? 'Deletion Pending' : 'Delete Account'}
</Button>
</div>
</CardContent>
</Card>
{/* Account Deletion Dialog */}
<AccountDeletionDialog
open={showDeletionDialog}
onOpenChange={setShowDeletionDialog}
userEmail={user?.email || ''}
onDeletionRequested={handleDeletionRequested}
/>
</div>
);
}

View File

@@ -0,0 +1,90 @@
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert';
import { Button } from '@/components/ui/button';
import { supabase } from '@/integrations/supabase/client';
import { useToast } from '@/hooks/use-toast';
import { AlertTriangle, Loader2 } from 'lucide-react';
import { useState } from 'react';
interface DeletionStatusBannerProps {
scheduledDate: string;
onCancelled: () => void;
}
export function DeletionStatusBanner({ scheduledDate, onCancelled }: DeletionStatusBannerProps) {
const [loading, setLoading] = useState(false);
const { toast } = useToast();
const calculateDaysRemaining = () => {
const scheduled = new Date(scheduledDate);
const now = new Date();
const diffTime = scheduled.getTime() - now.getTime();
const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
return Math.max(0, diffDays);
};
const handleCancelDeletion = async () => {
setLoading(true);
try {
const { error } = await supabase.functions.invoke('cancel-account-deletion', {
body: { cancellation_reason: 'User cancelled from settings' },
});
if (error) throw error;
toast({
title: 'Deletion Cancelled',
description: 'Your account has been reactivated.',
});
onCancelled();
} catch (error: any) {
toast({
variant: 'destructive',
title: 'Error',
description: error.message || 'Failed to cancel deletion',
});
} finally {
setLoading(false);
}
};
const daysRemaining = calculateDaysRemaining();
const formattedDate = new Date(scheduledDate).toLocaleDateString('en-US', {
weekday: 'long',
year: 'numeric',
month: 'long',
day: 'numeric',
});
return (
<Alert variant="destructive" className="mb-6">
<AlertTriangle className="w-4 h-4" />
<AlertTitle>Account Deletion Scheduled</AlertTitle>
<AlertDescription className="space-y-2">
<p>
Your account is scheduled for permanent deletion on <strong>{formattedDate}</strong>.
</p>
<p className="text-sm">
{daysRemaining > 0 ? (
<>
<strong>{daysRemaining}</strong> day{daysRemaining !== 1 ? 's' : ''} remaining to cancel.
</>
) : (
'You can now confirm deletion with your confirmation code.'
)}
</p>
<div className="flex gap-2 mt-3">
<Button
variant="outline"
size="sm"
onClick={handleCancelDeletion}
disabled={loading}
>
{loading ? <Loader2 className="w-4 h-4 animate-spin mr-2" /> : null}
Cancel Deletion
</Button>
</div>
</AlertDescription>
</Alert>
);
}