mirror of
https://github.com/pacnpal/thrilltrack-explorer.git
synced 2025-12-21 13:51:12 -05:00
Migrate Admin Admin Functions to wrapEdgeFunction
Migrate Phase 3 administrative functions to use the wrapEdgeFunction wrapper: - cancel-account-deletion - cancel-email-change - create-novu-subscriber - update-novu-subscriber - trigger-notification - remove-novu-subscriber - manage-moderator-topic - migrate-novu-users - sync-all-moderators-to-topic - update-novu-preferences - notify-system-announcement This update standardizes error handling, tracing, auth, and logging across admin endpoints, removes manual serve/CORS boilerplate, and prepares for consistent monitoring and testing.
This commit is contained in:
@@ -1,17 +1,15 @@
|
|||||||
import { serve } from 'https://deno.land/std@0.168.0/http/server.ts';
|
|
||||||
import { createClient } from 'https://esm.sh/@supabase/supabase-js@2';
|
import { createClient } from 'https://esm.sh/@supabase/supabase-js@2';
|
||||||
import { corsHeaders } from '../_shared/cors.ts';
|
import { corsHeaders } from '../_shared/cors.ts';
|
||||||
import { edgeLogger, startRequest, endRequest } from '../_shared/logger.ts';
|
import { edgeLogger } from '../_shared/logger.ts';
|
||||||
import { formatEdgeError } from '../_shared/errorFormatter.ts';
|
import { createEdgeFunction } from '../_shared/edgeFunctionWrapper.ts';
|
||||||
|
|
||||||
serve(async (req) => {
|
export default createEdgeFunction(
|
||||||
const tracking = startRequest();
|
{
|
||||||
|
name: 'cancel-account-deletion',
|
||||||
if (req.method === 'OPTIONS') {
|
requireAuth: true,
|
||||||
return new Response(null, { headers: corsHeaders });
|
corsHeaders: corsHeaders
|
||||||
}
|
},
|
||||||
|
async (req, context) => {
|
||||||
try {
|
|
||||||
const { cancellation_reason } = await req.json();
|
const { cancellation_reason } = await req.json();
|
||||||
|
|
||||||
const supabaseClient = createClient(
|
const supabaseClient = createClient(
|
||||||
@@ -24,23 +22,14 @@ serve(async (req) => {
|
|||||||
}
|
}
|
||||||
);
|
);
|
||||||
|
|
||||||
// Get authenticated user
|
context.span.setAttribute('action', 'cancel_deletion');
|
||||||
const {
|
edgeLogger.info('Cancelling deletion request', { action: 'cancel_deletion', userId: context.userId, requestId: context.requestId });
|
||||||
data: { user },
|
|
||||||
error: userError,
|
|
||||||
} = await supabaseClient.auth.getUser();
|
|
||||||
|
|
||||||
if (userError || !user) {
|
|
||||||
throw new Error('Unauthorized');
|
|
||||||
}
|
|
||||||
|
|
||||||
edgeLogger.info('Cancelling deletion request', { action: 'cancel_deletion', userId: user.id, requestId: tracking.requestId });
|
|
||||||
|
|
||||||
// Find pending or confirmed deletion request
|
// Find pending or confirmed deletion request
|
||||||
const { data: deletionRequest, error: requestError } = await supabaseClient
|
const { data: deletionRequest, error: requestError } = await supabaseClient
|
||||||
.from('account_deletion_requests')
|
.from('account_deletion_requests')
|
||||||
.select('*')
|
.select('*')
|
||||||
.eq('user_id', user.id)
|
.eq('user_id', context.userId)
|
||||||
.in('status', ['pending', 'confirmed'])
|
.in('status', ['pending', 'confirmed'])
|
||||||
.maybeSingle();
|
.maybeSingle();
|
||||||
|
|
||||||
@@ -81,7 +70,7 @@ serve(async (req) => {
|
|||||||
deactivated_at: null,
|
deactivated_at: null,
|
||||||
deactivation_reason: null,
|
deactivation_reason: null,
|
||||||
})
|
})
|
||||||
.eq('user_id', user.id);
|
.eq('user_id', context.userId);
|
||||||
|
|
||||||
if (profileError) {
|
if (profileError) {
|
||||||
throw profileError;
|
throw profileError;
|
||||||
@@ -90,8 +79,9 @@ serve(async (req) => {
|
|||||||
// Send cancellation email
|
// Send cancellation email
|
||||||
const forwardEmailKey = Deno.env.get('FORWARDEMAIL_API_KEY');
|
const forwardEmailKey = Deno.env.get('FORWARDEMAIL_API_KEY');
|
||||||
const fromEmail = Deno.env.get('FROM_EMAIL_ADDRESS') || 'noreply@thrillwiki.com';
|
const fromEmail = Deno.env.get('FROM_EMAIL_ADDRESS') || 'noreply@thrillwiki.com';
|
||||||
|
const userEmail = (await supabaseClient.auth.getUser()).data.user?.email;
|
||||||
|
|
||||||
if (forwardEmailKey) {
|
if (forwardEmailKey && userEmail) {
|
||||||
try {
|
try {
|
||||||
await fetch('https://api.forwardemail.net/v1/emails', {
|
await fetch('https://api.forwardemail.net/v1/emails', {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
@@ -101,7 +91,7 @@ serve(async (req) => {
|
|||||||
},
|
},
|
||||||
body: JSON.stringify({
|
body: JSON.stringify({
|
||||||
from: fromEmail,
|
from: fromEmail,
|
||||||
to: user.email,
|
to: userEmail,
|
||||||
subject: 'Account Deletion Cancelled',
|
subject: 'Account Deletion Cancelled',
|
||||||
html: `
|
html: `
|
||||||
<h2>Account Deletion Cancelled</h2>
|
<h2>Account Deletion Cancelled</h2>
|
||||||
@@ -112,35 +102,23 @@ serve(async (req) => {
|
|||||||
`,
|
`,
|
||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
edgeLogger.info('Cancellation confirmation email sent', { action: 'cancel_deletion_email', userId: user.id, requestId: tracking.requestId });
|
edgeLogger.info('Cancellation confirmation email sent', { action: 'cancel_deletion_email', userId: context.userId, requestId: context.requestId });
|
||||||
} catch (emailError) {
|
} catch (emailError) {
|
||||||
edgeLogger.error('Failed to send email', { action: 'cancel_deletion_email', userId: user.id, requestId: tracking.requestId });
|
edgeLogger.error('Failed to send email', { action: 'cancel_deletion_email', userId: context.userId, requestId: context.requestId });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const duration = endRequest(tracking);
|
edgeLogger.info('Deletion cancelled successfully', { action: 'cancel_deletion_success', userId: context.userId, requestId: context.requestId });
|
||||||
edgeLogger.info('Deletion cancelled successfully', { action: 'cancel_deletion_success', userId: user.id, requestId: tracking.requestId, duration });
|
|
||||||
|
|
||||||
return new Response(
|
return new Response(
|
||||||
JSON.stringify({
|
JSON.stringify({
|
||||||
success: true,
|
success: true,
|
||||||
message: 'Account deletion cancelled successfully',
|
message: 'Account deletion cancelled successfully',
|
||||||
requestId: tracking.requestId
|
|
||||||
}),
|
}),
|
||||||
{
|
{
|
||||||
status: 200,
|
status: 200,
|
||||||
headers: { ...corsHeaders, 'Content-Type': 'application/json', 'X-Request-ID': tracking.requestId },
|
headers: { 'Content-Type': 'application/json' },
|
||||||
}
|
|
||||||
);
|
|
||||||
} catch (error) {
|
|
||||||
const duration = endRequest(tracking);
|
|
||||||
edgeLogger.error('Error cancelling deletion', { action: 'cancel_deletion_error', error: formatEdgeError(error), requestId: tracking.requestId, duration });
|
|
||||||
return new Response(
|
|
||||||
JSON.stringify({ error: error.message, requestId: tracking.requestId }),
|
|
||||||
{
|
|
||||||
status: 400,
|
|
||||||
headers: { ...corsHeaders, 'Content-Type': 'application/json', 'X-Request-ID': tracking.requestId },
|
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
});
|
);
|
||||||
|
|||||||
@@ -1,36 +1,21 @@
|
|||||||
import { createClient } from 'https://esm.sh/@supabase/supabase-js@2.57.4';
|
import { createClient } from 'https://esm.sh/@supabase/supabase-js@2.57.4';
|
||||||
import { corsHeaders } from '../_shared/cors.ts';
|
import { corsHeaders } from '../_shared/cors.ts';
|
||||||
import { edgeLogger, startRequest, endRequest } from '../_shared/logger.ts';
|
import { edgeLogger } from '../_shared/logger.ts';
|
||||||
import { formatEdgeError } from '../_shared/errorFormatter.ts';
|
import { createEdgeFunction } from '../_shared/edgeFunctionWrapper.ts';
|
||||||
|
|
||||||
Deno.serve(async (req) => {
|
export default createEdgeFunction(
|
||||||
const tracking = startRequest();
|
{
|
||||||
|
name: 'cancel-email-change',
|
||||||
// Handle CORS preflight requests
|
requireAuth: true,
|
||||||
if (req.method === 'OPTIONS') {
|
corsHeaders: corsHeaders
|
||||||
return new Response(null, {
|
},
|
||||||
headers: {
|
async (req, context) => {
|
||||||
...corsHeaders,
|
context.span.setAttribute('action', 'cancel_email_change');
|
||||||
'X-Request-ID': tracking.requestId
|
edgeLogger.info('Cancelling email change for user', {
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
// Get the user from the authorization header
|
|
||||||
const authHeader = req.headers.get('Authorization');
|
|
||||||
if (!authHeader) {
|
|
||||||
const duration = endRequest(tracking);
|
|
||||||
edgeLogger.error('Missing authorization header', {
|
|
||||||
action: 'cancel_email_change',
|
action: 'cancel_email_change',
|
||||||
requestId: tracking.requestId,
|
requestId: context.requestId,
|
||||||
duration
|
userId: context.userId
|
||||||
});
|
});
|
||||||
throw new Error('No authorization header provided. Please ensure you are logged in.');
|
|
||||||
}
|
|
||||||
|
|
||||||
// Extract the JWT token from the Authorization header
|
|
||||||
const token = authHeader.replace('Bearer ', '');
|
|
||||||
|
|
||||||
// SECURITY: Service Role Key Usage
|
// SECURITY: Service Role Key Usage
|
||||||
// ---------------------------------
|
// ---------------------------------
|
||||||
@@ -38,7 +23,7 @@ Deno.serve(async (req) => {
|
|||||||
// This is required because:
|
// This is required because:
|
||||||
// 1. The cancel_user_email_change() database function has SECURITY DEFINER privileges
|
// 1. The cancel_user_email_change() database function has SECURITY DEFINER privileges
|
||||||
// 2. It needs to modify auth.users table which is not accessible with regular user tokens
|
// 2. It needs to modify auth.users table which is not accessible with regular user tokens
|
||||||
// 3. User authentication is still verified via JWT token (passed to getUser())
|
// 3. User authentication is verified via the wrapper's requireAuth
|
||||||
// Scope: Limited to cancelling the authenticated user's own email change
|
// Scope: Limited to cancelling the authenticated user's own email change
|
||||||
const supabaseUrl = Deno.env.get('SUPABASE_URL');
|
const supabaseUrl = Deno.env.get('SUPABASE_URL');
|
||||||
const supabaseServiceKey = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY');
|
const supabaseServiceKey = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY');
|
||||||
@@ -54,50 +39,28 @@ Deno.serve(async (req) => {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
// Verify the user's JWT token by passing it explicitly to getUser()
|
|
||||||
// Note: verify_jwt = true in config.toml means Supabase has already validated the JWT
|
|
||||||
const { data: { user }, error: authError } = await supabaseAdmin.auth.getUser(token);
|
|
||||||
|
|
||||||
if (authError || !user) {
|
|
||||||
const duration = endRequest(tracking);
|
|
||||||
edgeLogger.error('Auth verification failed', {
|
|
||||||
action: 'cancel_email_change',
|
|
||||||
requestId: tracking.requestId,
|
|
||||||
duration,
|
|
||||||
error: authError
|
|
||||||
});
|
|
||||||
throw new Error('Invalid session token. Please refresh the page and try again.');
|
|
||||||
}
|
|
||||||
|
|
||||||
const userId = user.id;
|
|
||||||
edgeLogger.info('Cancelling email change for user', {
|
|
||||||
action: 'cancel_email_change',
|
|
||||||
requestId: tracking.requestId,
|
|
||||||
userId
|
|
||||||
});
|
|
||||||
|
|
||||||
// Call the database function to clear email change fields
|
// Call the database function to clear email change fields
|
||||||
// This function has SECURITY DEFINER privileges to access auth.users
|
// This function has SECURITY DEFINER privileges to access auth.users
|
||||||
const { data: cancelled, error: cancelError } = await supabaseAdmin
|
const { data: cancelled, error: cancelError } = await supabaseAdmin
|
||||||
.rpc('cancel_user_email_change', { _user_id: userId });
|
.rpc('cancel_user_email_change', { _user_id: context.userId });
|
||||||
|
|
||||||
if (cancelError || !cancelled) {
|
if (cancelError || !cancelled) {
|
||||||
edgeLogger.error('Error cancelling email change', {
|
edgeLogger.error('Error cancelling email change', {
|
||||||
error: cancelError?.message,
|
error: cancelError?.message,
|
||||||
userId,
|
userId: context.userId,
|
||||||
requestId: tracking.requestId
|
requestId: context.requestId
|
||||||
});
|
});
|
||||||
throw new Error('Unable to cancel email change: ' + (cancelError?.message || 'Unknown error'));
|
throw new Error('Unable to cancel email change: ' + (cancelError?.message || 'Unknown error'));
|
||||||
}
|
}
|
||||||
|
|
||||||
edgeLogger.info('Successfully cancelled email change', { userId, requestId: tracking.requestId });
|
edgeLogger.info('Successfully cancelled email change', { userId: context.userId, requestId: context.requestId });
|
||||||
|
|
||||||
// Log the cancellation in admin_audit_log
|
// Log the cancellation in admin_audit_log
|
||||||
const { error: auditError } = await supabaseAdmin
|
const { error: auditError } = await supabaseAdmin
|
||||||
.from('admin_audit_log')
|
.from('admin_audit_log')
|
||||||
.insert({
|
.insert({
|
||||||
admin_user_id: userId,
|
admin_user_id: context.userId,
|
||||||
target_user_id: userId,
|
target_user_id: context.userId,
|
||||||
action: 'email_change_cancelled',
|
action: 'email_change_cancelled',
|
||||||
details: {
|
details: {
|
||||||
cancelled_at: new Date().toISOString(),
|
cancelled_at: new Date().toISOString(),
|
||||||
@@ -107,17 +70,15 @@ Deno.serve(async (req) => {
|
|||||||
if (auditError) {
|
if (auditError) {
|
||||||
edgeLogger.error('Error logging audit', {
|
edgeLogger.error('Error logging audit', {
|
||||||
error: auditError.message,
|
error: auditError.message,
|
||||||
requestId: tracking.requestId
|
requestId: context.requestId
|
||||||
});
|
});
|
||||||
// Don't fail the request if audit logging fails
|
// Don't fail the request if audit logging fails
|
||||||
}
|
}
|
||||||
|
|
||||||
const duration = endRequest(tracking);
|
|
||||||
edgeLogger.info('Successfully cancelled email change', {
|
edgeLogger.info('Successfully cancelled email change', {
|
||||||
action: 'cancel_email_change',
|
action: 'cancel_email_change',
|
||||||
requestId: tracking.requestId,
|
requestId: context.requestId,
|
||||||
userId,
|
userId: context.userId
|
||||||
duration
|
|
||||||
});
|
});
|
||||||
|
|
||||||
return new Response(
|
return new Response(
|
||||||
@@ -125,43 +86,17 @@ Deno.serve(async (req) => {
|
|||||||
success: true,
|
success: true,
|
||||||
message: 'Email change cancelled successfully',
|
message: 'Email change cancelled successfully',
|
||||||
user: {
|
user: {
|
||||||
id: userId,
|
id: context.userId,
|
||||||
email: null,
|
email: null,
|
||||||
new_email: null,
|
new_email: null,
|
||||||
},
|
},
|
||||||
requestId: tracking.requestId,
|
|
||||||
}),
|
}),
|
||||||
{
|
{
|
||||||
headers: {
|
headers: {
|
||||||
...corsHeaders,
|
'Content-Type': 'application/json'
|
||||||
'Content-Type': 'application/json',
|
|
||||||
'X-Request-ID': tracking.requestId
|
|
||||||
},
|
},
|
||||||
status: 200,
|
status: 200,
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
} catch (error) {
|
|
||||||
const duration = endRequest(tracking);
|
|
||||||
edgeLogger.error('Error in cancel-email-change function', {
|
|
||||||
action: 'cancel_email_change',
|
|
||||||
requestId: tracking.requestId,
|
|
||||||
duration,
|
|
||||||
error: formatEdgeError(error)
|
|
||||||
});
|
|
||||||
return new Response(
|
|
||||||
JSON.stringify({
|
|
||||||
success: false,
|
|
||||||
error: error instanceof Error ? error.message : 'An unknown error occurred',
|
|
||||||
requestId: tracking.requestId,
|
|
||||||
}),
|
|
||||||
{
|
|
||||||
headers: {
|
|
||||||
...corsHeaders,
|
|
||||||
'Content-Type': 'application/json',
|
|
||||||
'X-Request-ID': tracking.requestId
|
|
||||||
},
|
|
||||||
status: 400,
|
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|||||||
Reference in New Issue
Block a user