mirror of
https://github.com/pacnpal/thrilltrack-explorer.git
synced 2025-12-24 00:51:12 -05:00
Implement account deletion system
This commit is contained in:
129
supabase/functions/cancel-account-deletion/index.ts
Normal file
129
supabase/functions/cancel-account-deletion/index.ts
Normal file
@@ -0,0 +1,129 @@
|
||||
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 { cancellation_reason } = await req.json();
|
||||
|
||||
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(`Cancelling deletion request 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');
|
||||
}
|
||||
|
||||
// Cancel deletion request
|
||||
const { error: updateError } = await supabaseClient
|
||||
.from('account_deletion_requests')
|
||||
.update({
|
||||
status: 'cancelled',
|
||||
cancelled_at: new Date().toISOString(),
|
||||
cancellation_reason: cancellation_reason || 'User cancelled',
|
||||
})
|
||||
.eq('id', deletionRequest.id);
|
||||
|
||||
if (updateError) {
|
||||
throw updateError;
|
||||
}
|
||||
|
||||
// Reactivate profile
|
||||
const { error: profileError } = await supabaseClient
|
||||
.from('profiles')
|
||||
.update({
|
||||
deactivated: false,
|
||||
deactivated_at: null,
|
||||
deactivation_reason: null,
|
||||
})
|
||||
.eq('user_id', user.id);
|
||||
|
||||
if (profileError) {
|
||||
throw profileError;
|
||||
}
|
||||
|
||||
// Send cancellation email
|
||||
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 Cancelled',
|
||||
html: `
|
||||
<h2>Account Deletion Cancelled</h2>
|
||||
<p>Your account deletion request has been cancelled on ${new Date().toLocaleDateString()}.</p>
|
||||
<p>Your account has been reactivated and you can continue using all features.</p>
|
||||
<p>Welcome back!</p>
|
||||
`,
|
||||
}),
|
||||
});
|
||||
console.log('Cancellation confirmation email sent');
|
||||
} catch (emailError) {
|
||||
console.error('Failed to send email:', emailError);
|
||||
}
|
||||
}
|
||||
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
success: true,
|
||||
message: 'Account deletion cancelled successfully',
|
||||
}),
|
||||
{
|
||||
status: 200,
|
||||
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
|
||||
}
|
||||
);
|
||||
} catch (error) {
|
||||
console.error('Error cancelling deletion:', error);
|
||||
return new Response(
|
||||
JSON.stringify({ error: error.message }),
|
||||
{
|
||||
status: 400,
|
||||
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
|
||||
}
|
||||
);
|
||||
}
|
||||
});
|
||||
189
supabase/functions/confirm-account-deletion/index.ts
Normal file
189
supabase/functions/confirm-account-deletion/index.ts
Normal file
@@ -0,0 +1,189 @@
|
||||
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 { confirmation_code } = await req.json();
|
||||
|
||||
if (!confirmation_code) {
|
||||
throw new Error('Confirmation code is required');
|
||||
}
|
||||
|
||||
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(`Confirming deletion for user: ${user.id}`);
|
||||
|
||||
// Find 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');
|
||||
}
|
||||
|
||||
// Verify confirmation code
|
||||
if (deletionRequest.confirmation_code !== confirmation_code) {
|
||||
throw new Error('Invalid confirmation code');
|
||||
}
|
||||
|
||||
// Check if 14 days have passed
|
||||
const scheduledDate = new Date(deletionRequest.scheduled_deletion_at);
|
||||
const now = new Date();
|
||||
|
||||
if (now < scheduledDate) {
|
||||
const daysRemaining = Math.ceil((scheduledDate.getTime() - now.getTime()) / (1000 * 60 * 60 * 24));
|
||||
throw new Error(`You must wait ${daysRemaining} more day(s) before confirming deletion`);
|
||||
}
|
||||
|
||||
// Use service role client for admin operations
|
||||
const supabaseAdmin = createClient(
|
||||
Deno.env.get('SUPABASE_URL') ?? '',
|
||||
Deno.env.get('SUPABASE_SERVICE_ROLE_KEY') ?? ''
|
||||
);
|
||||
|
||||
console.log('Starting deletion process...');
|
||||
|
||||
// Delete reviews (CASCADE will handle review_photos)
|
||||
const { error: reviewsError } = await supabaseAdmin
|
||||
.from('reviews')
|
||||
.delete()
|
||||
.eq('user_id', user.id);
|
||||
|
||||
if (reviewsError) {
|
||||
console.error('Error deleting reviews:', reviewsError);
|
||||
}
|
||||
|
||||
// Anonymize submissions and photos
|
||||
const { error: anonymizeError } = await supabaseAdmin
|
||||
.rpc('anonymize_user_submissions', { target_user_id: user.id });
|
||||
|
||||
if (anonymizeError) {
|
||||
console.error('Error anonymizing submissions:', anonymizeError);
|
||||
}
|
||||
|
||||
// Delete user roles
|
||||
const { error: rolesError } = await supabaseAdmin
|
||||
.from('user_roles')
|
||||
.delete()
|
||||
.eq('user_id', user.id);
|
||||
|
||||
if (rolesError) {
|
||||
console.error('Error deleting user roles:', rolesError);
|
||||
}
|
||||
|
||||
// Delete profile
|
||||
const { error: profileError } = await supabaseAdmin
|
||||
.from('profiles')
|
||||
.delete()
|
||||
.eq('user_id', user.id);
|
||||
|
||||
if (profileError) {
|
||||
console.error('Error deleting profile:', profileError);
|
||||
throw profileError;
|
||||
}
|
||||
|
||||
// Update deletion request status
|
||||
const { error: updateError } = await supabaseAdmin
|
||||
.from('account_deletion_requests')
|
||||
.update({
|
||||
status: 'completed',
|
||||
completed_at: new Date().toISOString(),
|
||||
})
|
||||
.eq('id', deletionRequest.id);
|
||||
|
||||
if (updateError) {
|
||||
console.error('Error updating deletion request:', updateError);
|
||||
}
|
||||
|
||||
// Delete auth user (this should cascade delete the deletion request)
|
||||
const { error: authError } = await supabaseAdmin.auth.admin.deleteUser(user.id);
|
||||
|
||||
if (authError) {
|
||||
console.error('Error deleting auth user:', authError);
|
||||
throw authError;
|
||||
}
|
||||
|
||||
// Send confirmation email
|
||||
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 Confirmed',
|
||||
html: `
|
||||
<h2>Account Deletion Confirmed</h2>
|
||||
<p>Your account has been permanently deleted on ${new Date().toLocaleDateString()}.</p>
|
||||
<p>Your profile and reviews have been removed, but your contributions to the database remain preserved.</p>
|
||||
<p>Thank you for being part of our community.</p>
|
||||
`,
|
||||
}),
|
||||
});
|
||||
console.log('Deletion confirmation email sent');
|
||||
} catch (emailError) {
|
||||
console.error('Failed to send email:', emailError);
|
||||
}
|
||||
}
|
||||
|
||||
console.log('Account deletion completed successfully');
|
||||
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
success: true,
|
||||
message: 'Account deleted successfully',
|
||||
}),
|
||||
{
|
||||
status: 200,
|
||||
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
|
||||
}
|
||||
);
|
||||
} catch (error) {
|
||||
console.error('Error confirming deletion:', error);
|
||||
return new Response(
|
||||
JSON.stringify({ error: error.message }),
|
||||
{
|
||||
status: 400,
|
||||
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
|
||||
}
|
||||
);
|
||||
}
|
||||
});
|
||||
159
supabase/functions/process-scheduled-deletions/index.ts
Normal file
159
supabase/functions/process-scheduled-deletions/index.ts
Normal file
@@ -0,0 +1,159 @@
|
||||
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 {
|
||||
// Use service role for admin operations
|
||||
const supabaseAdmin = createClient(
|
||||
Deno.env.get('SUPABASE_URL') ?? '',
|
||||
Deno.env.get('SUPABASE_SERVICE_ROLE_KEY') ?? ''
|
||||
);
|
||||
|
||||
console.log('Processing scheduled account deletions...');
|
||||
|
||||
// Find pending deletion requests that are past their scheduled date
|
||||
const { data: pendingDeletions, error: fetchError } = await supabaseAdmin
|
||||
.from('account_deletion_requests')
|
||||
.select('*')
|
||||
.eq('status', 'pending')
|
||||
.lt('scheduled_deletion_at', new Date().toISOString());
|
||||
|
||||
if (fetchError) {
|
||||
throw fetchError;
|
||||
}
|
||||
|
||||
if (!pendingDeletions || pendingDeletions.length === 0) {
|
||||
console.log('No deletions to process');
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
success: true,
|
||||
message: 'No deletions to process',
|
||||
processed: 0,
|
||||
}),
|
||||
{
|
||||
status: 200,
|
||||
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
console.log(`Found ${pendingDeletions.length} deletion(s) to process`);
|
||||
|
||||
let successCount = 0;
|
||||
let errorCount = 0;
|
||||
|
||||
for (const deletion of pendingDeletions) {
|
||||
try {
|
||||
console.log(`Processing deletion for user: ${deletion.user_id}`);
|
||||
|
||||
// Get user email for confirmation email
|
||||
const { data: userData } = await supabaseAdmin.auth.admin.getUserById(deletion.user_id);
|
||||
const userEmail = userData?.user?.email;
|
||||
|
||||
// Delete reviews (CASCADE will handle review_photos)
|
||||
await supabaseAdmin
|
||||
.from('reviews')
|
||||
.delete()
|
||||
.eq('user_id', deletion.user_id);
|
||||
|
||||
// Anonymize submissions and photos
|
||||
await supabaseAdmin
|
||||
.rpc('anonymize_user_submissions', { target_user_id: deletion.user_id });
|
||||
|
||||
// Delete user roles
|
||||
await supabaseAdmin
|
||||
.from('user_roles')
|
||||
.delete()
|
||||
.eq('user_id', deletion.user_id);
|
||||
|
||||
// Delete profile
|
||||
await supabaseAdmin
|
||||
.from('profiles')
|
||||
.delete()
|
||||
.eq('user_id', deletion.user_id);
|
||||
|
||||
// Update deletion request status
|
||||
await supabaseAdmin
|
||||
.from('account_deletion_requests')
|
||||
.update({
|
||||
status: 'completed',
|
||||
completed_at: new Date().toISOString(),
|
||||
})
|
||||
.eq('id', deletion.id);
|
||||
|
||||
// Delete auth user
|
||||
await supabaseAdmin.auth.admin.deleteUser(deletion.user_id);
|
||||
|
||||
// Send final confirmation email if we have the email
|
||||
if (userEmail) {
|
||||
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: userEmail,
|
||||
subject: 'Account Deletion Completed',
|
||||
html: `
|
||||
<h2>Account Deletion Completed</h2>
|
||||
<p>Your account has been automatically deleted as scheduled on ${new Date().toLocaleDateString()}.</p>
|
||||
<p>Your profile and reviews have been removed, but your contributions to the database remain preserved.</p>
|
||||
<p>Thank you for being part of our community.</p>
|
||||
`,
|
||||
}),
|
||||
});
|
||||
} catch (emailError) {
|
||||
console.error('Failed to send confirmation email:', emailError);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
successCount++;
|
||||
console.log(`Successfully deleted account for user: ${deletion.user_id}`);
|
||||
} catch (error) {
|
||||
errorCount++;
|
||||
console.error(`Failed to delete account for user ${deletion.user_id}:`, error);
|
||||
}
|
||||
}
|
||||
|
||||
console.log(`Processed ${successCount} deletion(s) successfully, ${errorCount} error(s)`);
|
||||
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
success: true,
|
||||
message: `Processed ${successCount} deletion(s)`,
|
||||
processed: successCount,
|
||||
errors: errorCount,
|
||||
}),
|
||||
{
|
||||
status: 200,
|
||||
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
|
||||
}
|
||||
);
|
||||
} catch (error) {
|
||||
console.error('Error processing scheduled deletions:', error);
|
||||
return new Response(
|
||||
JSON.stringify({ error: error.message }),
|
||||
{
|
||||
status: 500,
|
||||
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
|
||||
}
|
||||
);
|
||||
}
|
||||
});
|
||||
181
supabase/functions/request-account-deletion/index.ts
Normal file
181
supabase/functions/request-account-deletion/index.ts
Normal file
@@ -0,0 +1,181 @@
|
||||
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(`Processing deletion request for user: ${user.id}`);
|
||||
|
||||
// Check for existing pending deletion request
|
||||
const { data: existingRequest } = await supabaseClient
|
||||
.from('account_deletion_requests')
|
||||
.select('*')
|
||||
.eq('user_id', user.id)
|
||||
.eq('status', 'pending')
|
||||
.maybeSingle();
|
||||
|
||||
if (existingRequest) {
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
error: 'You already have a pending deletion request',
|
||||
request: existingRequest,
|
||||
}),
|
||||
{
|
||||
status: 400,
|
||||
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
// Generate confirmation code
|
||||
const { data: codeData, error: codeError } = await supabaseClient
|
||||
.rpc('generate_deletion_confirmation_code');
|
||||
|
||||
if (codeError) {
|
||||
throw codeError;
|
||||
}
|
||||
|
||||
const confirmationCode = codeData as string;
|
||||
const scheduledDeletionAt = new Date();
|
||||
scheduledDeletionAt.setDate(scheduledDeletionAt.getDate() + 14);
|
||||
|
||||
// Create deletion request
|
||||
const { data: deletionRequest, error: requestError } = await supabaseClient
|
||||
.from('account_deletion_requests')
|
||||
.insert({
|
||||
user_id: user.id,
|
||||
confirmation_code: confirmationCode,
|
||||
confirmation_code_sent_at: new Date().toISOString(),
|
||||
scheduled_deletion_at: scheduledDeletionAt.toISOString(),
|
||||
status: 'pending',
|
||||
})
|
||||
.select()
|
||||
.single();
|
||||
|
||||
if (requestError) {
|
||||
throw requestError;
|
||||
}
|
||||
|
||||
// Deactivate profile
|
||||
const { error: profileError } = await supabaseClient
|
||||
.from('profiles')
|
||||
.update({
|
||||
deactivated: true,
|
||||
deactivated_at: new Date().toISOString(),
|
||||
deactivation_reason: 'User requested account deletion',
|
||||
})
|
||||
.eq('user_id', user.id);
|
||||
|
||||
if (profileError) {
|
||||
throw profileError;
|
||||
}
|
||||
|
||||
// Send confirmation email
|
||||
const emailPayload = {
|
||||
to: user.email,
|
||||
subject: 'Account Deletion Requested - Confirmation Code Inside',
|
||||
html: `
|
||||
<h2>Account Deletion Requested</h2>
|
||||
<p>Hello,</p>
|
||||
<p>We received a request to delete your account on ${new Date().toLocaleDateString()}.</p>
|
||||
|
||||
<h3>IMPORTANT INFORMATION:</h3>
|
||||
<p>Your account has been deactivated and will be permanently deleted on <strong>${scheduledDeletionAt.toLocaleDateString()}</strong> (14 days from now).</p>
|
||||
|
||||
<h4>What will be DELETED:</h4>
|
||||
<ul>
|
||||
<li>✗ Your profile information (username, bio, avatar, etc.)</li>
|
||||
<li>✗ Your reviews and ratings</li>
|
||||
<li>✗ Your personal preferences and settings</li>
|
||||
</ul>
|
||||
|
||||
<h4>What will be PRESERVED:</h4>
|
||||
<ul>
|
||||
<li>✓ Your database submissions (park creations, ride additions, edits)</li>
|
||||
<li>✓ Photos you've uploaded (will be shown as "Submitted by [deleted user]")</li>
|
||||
<li>✓ Edit history and contributions</li>
|
||||
</ul>
|
||||
|
||||
<h3>CONFIRMATION CODE: <strong>${confirmationCode}</strong></h3>
|
||||
<p>To confirm deletion after the 14-day 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 at any time during the next 14 days.</p>
|
||||
`,
|
||||
};
|
||||
|
||||
// Send via ForwardEmail API
|
||||
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: emailPayload.to,
|
||||
subject: emailPayload.subject,
|
||||
html: emailPayload.html,
|
||||
}),
|
||||
});
|
||||
console.log('Deletion confirmation email sent');
|
||||
} catch (emailError) {
|
||||
console.error('Failed to send email:', emailError);
|
||||
}
|
||||
}
|
||||
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
success: true,
|
||||
message: 'Account deletion request created successfully',
|
||||
scheduled_deletion_at: scheduledDeletionAt.toISOString(),
|
||||
request_id: deletionRequest.id,
|
||||
}),
|
||||
{
|
||||
status: 200,
|
||||
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
|
||||
}
|
||||
);
|
||||
} catch (error) {
|
||||
console.error('Error processing deletion request:', error);
|
||||
return new Response(
|
||||
JSON.stringify({ error: error.message }),
|
||||
{
|
||||
status: 400,
|
||||
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
|
||||
}
|
||||
);
|
||||
}
|
||||
});
|
||||
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' },
|
||||
}
|
||||
);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,106 @@
|
||||
-- Create account deletion status enum
|
||||
CREATE TYPE account_deletion_status AS ENUM ('pending', 'confirmed', 'cancelled', 'completed');
|
||||
|
||||
-- Create account deletion requests table
|
||||
CREATE TABLE account_deletion_requests (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
user_id UUID NOT NULL REFERENCES auth.users(id) ON DELETE CASCADE,
|
||||
requested_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
|
||||
scheduled_deletion_at TIMESTAMP WITH TIME ZONE NOT NULL,
|
||||
confirmation_code TEXT NOT NULL,
|
||||
confirmation_code_sent_at TIMESTAMP WITH TIME ZONE,
|
||||
status account_deletion_status NOT NULL DEFAULT 'pending',
|
||||
cancelled_at TIMESTAMP WITH TIME ZONE,
|
||||
completed_at TIMESTAMP WITH TIME ZONE,
|
||||
cancellation_reason TEXT,
|
||||
created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
|
||||
updated_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW()
|
||||
);
|
||||
|
||||
-- Add unique constraint for active deletions
|
||||
CREATE UNIQUE INDEX unique_active_deletion_per_user
|
||||
ON account_deletion_requests(user_id)
|
||||
WHERE status = 'pending';
|
||||
|
||||
-- Add index for scheduled deletions
|
||||
CREATE INDEX idx_account_deletions_scheduled
|
||||
ON account_deletion_requests(scheduled_deletion_at)
|
||||
WHERE status = 'pending';
|
||||
|
||||
-- Enable RLS
|
||||
ALTER TABLE account_deletion_requests ENABLE ROW LEVEL SECURITY;
|
||||
|
||||
-- RLS Policies
|
||||
CREATE POLICY "Users can view their own deletion requests"
|
||||
ON account_deletion_requests FOR SELECT
|
||||
USING (auth.uid() = user_id);
|
||||
|
||||
CREATE POLICY "Users can insert their own deletion requests"
|
||||
ON account_deletion_requests FOR INSERT
|
||||
WITH CHECK (auth.uid() = user_id);
|
||||
|
||||
CREATE POLICY "Users can update their own deletion requests"
|
||||
ON account_deletion_requests FOR UPDATE
|
||||
USING (auth.uid() = user_id);
|
||||
|
||||
CREATE POLICY "Admins can view all deletion requests"
|
||||
ON account_deletion_requests FOR SELECT
|
||||
USING (is_moderator(auth.uid()));
|
||||
|
||||
-- Add deactivation columns to profiles
|
||||
ALTER TABLE profiles
|
||||
ADD COLUMN deactivated BOOLEAN NOT NULL DEFAULT false,
|
||||
ADD COLUMN deactivated_at TIMESTAMP WITH TIME ZONE,
|
||||
ADD COLUMN deactivation_reason TEXT;
|
||||
|
||||
-- Index for deactivated profiles
|
||||
CREATE INDEX idx_profiles_deactivated ON profiles(deactivated) WHERE deactivated = true;
|
||||
|
||||
-- Update profile RLS to hide deactivated profiles
|
||||
CREATE POLICY "Hide deactivated profiles from public"
|
||||
ON profiles FOR SELECT
|
||||
USING (
|
||||
NOT deactivated OR auth.uid() = user_id OR is_moderator(auth.uid())
|
||||
);
|
||||
|
||||
-- Helper function to generate confirmation code
|
||||
CREATE OR REPLACE FUNCTION generate_deletion_confirmation_code()
|
||||
RETURNS TEXT
|
||||
LANGUAGE plpgsql
|
||||
SECURITY DEFINER
|
||||
SET search_path = public
|
||||
AS $$
|
||||
DECLARE
|
||||
code TEXT;
|
||||
BEGIN
|
||||
code := LPAD(FLOOR(RANDOM() * 1000000)::TEXT, 6, '0');
|
||||
RETURN code;
|
||||
END;
|
||||
$$;
|
||||
|
||||
-- Helper function to anonymize user data
|
||||
CREATE OR REPLACE FUNCTION anonymize_user_submissions(target_user_id UUID)
|
||||
RETURNS VOID
|
||||
LANGUAGE plpgsql
|
||||
SECURITY DEFINER
|
||||
SET search_path = public
|
||||
AS $$
|
||||
BEGIN
|
||||
-- Nullify user_id in content_submissions to preserve submissions
|
||||
UPDATE content_submissions
|
||||
SET user_id = NULL
|
||||
WHERE user_id = target_user_id;
|
||||
|
||||
-- Nullify submitted_by in photos to preserve photos
|
||||
UPDATE photos
|
||||
SET submitted_by = NULL,
|
||||
photographer_credit = '[Deleted User]'
|
||||
WHERE submitted_by = target_user_id;
|
||||
END;
|
||||
$$;
|
||||
|
||||
-- Add trigger for updated_at on account_deletion_requests
|
||||
CREATE TRIGGER update_account_deletion_requests_updated_at
|
||||
BEFORE UPDATE ON account_deletion_requests
|
||||
FOR EACH ROW
|
||||
EXECUTE FUNCTION update_updated_at_column();
|
||||
Reference in New Issue
Block a user