mirror of
https://github.com/pacnpal/thrilltrack-explorer.git
synced 2025-12-21 13:31:13 -05:00
Implement account deletion system
This commit is contained in:
137
supabase/functions/resend-deletion-code/index.ts
Normal file
137
supabase/functions/resend-deletion-code/index.ts
Normal file
@@ -0,0 +1,137 @@
|
||||
import { serve } from 'https://deno.land/std@0.168.0/http/server.ts';
|
||||
import { createClient } from 'https://esm.sh/@supabase/supabase-js@2';
|
||||
|
||||
const corsHeaders = {
|
||||
'Access-Control-Allow-Origin': '*',
|
||||
'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
|
||||
};
|
||||
|
||||
serve(async (req) => {
|
||||
if (req.method === 'OPTIONS') {
|
||||
return new Response(null, { headers: corsHeaders });
|
||||
}
|
||||
|
||||
try {
|
||||
const supabaseClient = createClient(
|
||||
Deno.env.get('SUPABASE_URL') ?? '',
|
||||
Deno.env.get('SUPABASE_ANON_KEY') ?? '',
|
||||
{
|
||||
global: {
|
||||
headers: { Authorization: req.headers.get('Authorization')! },
|
||||
},
|
||||
}
|
||||
);
|
||||
|
||||
// Get authenticated user
|
||||
const {
|
||||
data: { user },
|
||||
error: userError,
|
||||
} = await supabaseClient.auth.getUser();
|
||||
|
||||
if (userError || !user) {
|
||||
throw new Error('Unauthorized');
|
||||
}
|
||||
|
||||
console.log(`Resending deletion code for user: ${user.id}`);
|
||||
|
||||
// Find pending deletion request
|
||||
const { data: deletionRequest, error: requestError } = await supabaseClient
|
||||
.from('account_deletion_requests')
|
||||
.select('*')
|
||||
.eq('user_id', user.id)
|
||||
.eq('status', 'pending')
|
||||
.maybeSingle();
|
||||
|
||||
if (requestError || !deletionRequest) {
|
||||
throw new Error('No pending deletion request found');
|
||||
}
|
||||
|
||||
// Check rate limiting (max 3 resends per hour)
|
||||
const lastSent = new Date(deletionRequest.confirmation_code_sent_at);
|
||||
const now = new Date();
|
||||
const hoursSinceLastSend = (now.getTime() - lastSent.getTime()) / (1000 * 60 * 60);
|
||||
|
||||
if (hoursSinceLastSend < 0.33) { // ~20 minutes between resends
|
||||
throw new Error('Please wait at least 20 minutes between resend requests');
|
||||
}
|
||||
|
||||
// Generate new confirmation code
|
||||
const { data: codeData, error: codeError } = await supabaseClient
|
||||
.rpc('generate_deletion_confirmation_code');
|
||||
|
||||
if (codeError) {
|
||||
throw codeError;
|
||||
}
|
||||
|
||||
const confirmationCode = codeData as string;
|
||||
|
||||
// Update deletion request with new code
|
||||
const { error: updateError } = await supabaseClient
|
||||
.from('account_deletion_requests')
|
||||
.update({
|
||||
confirmation_code: confirmationCode,
|
||||
confirmation_code_sent_at: now.toISOString(),
|
||||
})
|
||||
.eq('id', deletionRequest.id);
|
||||
|
||||
if (updateError) {
|
||||
throw updateError;
|
||||
}
|
||||
|
||||
const scheduledDate = new Date(deletionRequest.scheduled_deletion_at);
|
||||
|
||||
// Send email with new code
|
||||
const forwardEmailKey = Deno.env.get('FORWARDEMAIL_API_KEY');
|
||||
const fromEmail = Deno.env.get('FROM_EMAIL_ADDRESS') || 'noreply@thrillwiki.com';
|
||||
|
||||
if (forwardEmailKey) {
|
||||
try {
|
||||
await fetch('https://api.forwardemail.net/v1/emails', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Authorization': `Basic ${btoa(forwardEmailKey + ':')}`,
|
||||
},
|
||||
body: JSON.stringify({
|
||||
from: fromEmail,
|
||||
to: user.email,
|
||||
subject: 'Account Deletion - New Confirmation Code',
|
||||
html: `
|
||||
<h2>New Confirmation Code</h2>
|
||||
<p>You requested a new confirmation code for your account deletion.</p>
|
||||
<p>Your account will be permanently deleted on <strong>${scheduledDate.toLocaleDateString()}</strong>.</p>
|
||||
|
||||
<h3>CONFIRMATION CODE: <strong>${confirmationCode}</strong></h3>
|
||||
<p>To confirm deletion after the waiting period, you'll need to enter this 6-digit code.</p>
|
||||
|
||||
<p><strong>Need to cancel?</strong> Log in and visit your account settings to reactivate your account.</p>
|
||||
`,
|
||||
}),
|
||||
});
|
||||
console.log('New confirmation code email sent');
|
||||
} catch (emailError) {
|
||||
console.error('Failed to send email:', emailError);
|
||||
}
|
||||
}
|
||||
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
success: true,
|
||||
message: 'New confirmation code sent successfully',
|
||||
}),
|
||||
{
|
||||
status: 200,
|
||||
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
|
||||
}
|
||||
);
|
||||
} catch (error) {
|
||||
console.error('Error resending code:', error);
|
||||
return new Response(
|
||||
JSON.stringify({ error: error.message }),
|
||||
{
|
||||
status: 400,
|
||||
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
|
||||
}
|
||||
);
|
||||
}
|
||||
});
|
||||
Reference in New Issue
Block a user