Files
thrilltrack-explorer/supabase/functions/cancel-email-change/index.ts
2025-10-01 16:03:04 +00:00

145 lines
4.4 KiB
TypeScript

import { createClient } from 'https://esm.sh/@supabase/supabase-js@2.57.4';
const corsHeaders = {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
};
Deno.serve(async (req) => {
// Handle CORS preflight requests
if (req.method === 'OPTIONS') {
return new Response(null, { headers: corsHeaders });
}
try {
// Create admin client with service role key
const supabaseAdmin = createClient(
Deno.env.get('SUPABASE_URL') ?? '',
Deno.env.get('SUPABASE_SERVICE_ROLE_KEY') ?? '',
{
auth: {
autoRefreshToken: false,
persistSession: false
}
}
);
// Get the user from the authorization header
const authHeader = req.headers.get('Authorization');
if (!authHeader) {
throw new Error('No authorization header');
}
const token = authHeader.replace('Bearer ', '');
const { data: { user }, error: userError } = await supabaseAdmin.auth.getUser(token);
if (userError || !user) {
throw new Error('Unauthorized');
}
console.log(`Cancelling email change for user ${user.id}`, {
currentEmail: user.email,
newEmail: user.new_email
});
// Direct database manipulation to clear email change fields
// Use service role to directly query and update auth.users table
const { error: sqlError } = await supabaseAdmin
.from('auth.users')
.update({
email_change: null,
email_change_sent_at: null,
email_change_confirm_status: 0,
email_change_token_current: null,
email_change_token_new: null
})
.eq('id', user.id);
if (sqlError) {
console.error('Error clearing email change fields via SQL:', sqlError);
// Fallback: Try using the two-step email update trick
console.log('Attempting fallback method with temporary email...');
try {
const tempEmail = `temp_${Date.now()}_${user.email}`;
const { error: tempError } = await supabaseAdmin.auth.admin.updateUserById(
user.id,
{ email: tempEmail, email_confirm: true }
);
if (tempError) throw tempError;
const { error: revertError } = await supabaseAdmin.auth.admin.updateUserById(
user.id,
{ email: user.email, email_confirm: true }
);
if (revertError) throw revertError;
console.log('Fallback method succeeded');
} catch (fallbackError) {
console.error('Fallback method also failed:', fallbackError);
throw new Error('Unable to cancel email change: ' + fallbackError.message);
}
}
// Verify the change was successful by getting the updated user
const { data: { user: verifiedUser }, error: verifyError } = await supabaseAdmin.auth.admin.getUserById(user.id);
if (verifyError) {
console.error('Error verifying email change cancellation:', verifyError);
}
console.log(`Successfully cancelled email change for user ${user.id}`, {
verifiedEmail: verifiedUser?.email,
verifiedNewEmail: verifiedUser?.new_email
});
// Log the cancellation in admin_audit_log
const { error: auditError } = await supabaseAdmin
.from('admin_audit_log')
.insert({
admin_user_id: user.id,
target_user_id: user.id,
action: 'email_change_cancelled',
details: {
cancelled_at: new Date().toISOString(),
current_email: user.email,
},
});
if (auditError) {
console.error('Error logging audit:', auditError);
// Don't fail the request if audit logging fails
}
return new Response(
JSON.stringify({
success: true,
message: 'Email change cancelled successfully',
user: {
id: verifiedUser?.id ?? user.id,
email: verifiedUser?.email ?? user.email,
new_email: verifiedUser?.new_email ?? null,
},
}),
{
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
status: 200,
}
);
} catch (error) {
console.error('Error in cancel-email-change function:', error);
return new Response(
JSON.stringify({
success: false,
error: error.message,
}),
{
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
status: 400,
}
);
}
});