mirror of
https://github.com/pacnpal/thrilltrack-explorer.git
synced 2025-12-22 01:51:12 -05:00
Migrate Phase 2 admin edges
Migrate five admin/moderator edge functions (merge-contact-tickets, send-escalation-notification, notify-moderators-report, notify-moderators-submission, send-password-added-email) to use createEdgeFunction wrapper. Remove manual CORS, auth, service-client setup, logging, and error handling. Implement handler with EdgeFunctionContext, apply appropriate wrapper config (requireAuth, requiredRoles/useServiceRole, corsEnabled, enableTracing, rateLimitTier). Replace edgeLogger with span events, maintain core business logic and retry/email integration patterns.
This commit is contained in:
@@ -1,7 +1,7 @@
|
||||
import { serve } from 'https://deno.land/std@0.168.0/http/server.ts';
|
||||
import { createClient } from 'https://esm.sh/@supabase/supabase-js@2';
|
||||
import { createEdgeFunction, type EdgeFunctionContext } from '../_shared/edgeFunctionWrapper.ts';
|
||||
import { corsHeaders } from '../_shared/cors.ts';
|
||||
import { edgeLogger, startRequest, endRequest, logSpanToDatabase, startSpan, endSpan } from '../_shared/logger.ts';
|
||||
import { addSpanEvent } from '../_shared/logger.ts';
|
||||
|
||||
interface EmailRequest {
|
||||
email: string;
|
||||
@@ -9,217 +9,131 @@ interface EmailRequest {
|
||||
username?: string;
|
||||
}
|
||||
|
||||
serve(async (req) => {
|
||||
const tracking = startRequest();
|
||||
|
||||
if (req.method === 'OPTIONS') {
|
||||
return new Response(null, {
|
||||
headers: {
|
||||
...corsHeaders,
|
||||
'X-Request-ID': tracking.requestId
|
||||
}
|
||||
});
|
||||
const handler = async (req: Request, { user, span, requestId }: EdgeFunctionContext) => {
|
||||
const { email, displayName, username }: EmailRequest = await req.json();
|
||||
|
||||
if (!email) {
|
||||
throw new Error('Email is required');
|
||||
}
|
||||
|
||||
try {
|
||||
const supabaseClient = createClient(
|
||||
Deno.env.get('SUPABASE_URL') ?? '',
|
||||
Deno.env.get('SUPABASE_ANON_KEY') ?? '',
|
||||
{
|
||||
global: {
|
||||
headers: { Authorization: req.headers.get('Authorization')! },
|
||||
},
|
||||
}
|
||||
);
|
||||
addSpanEvent(span, 'sending_password_email', { userId: user.id, email });
|
||||
|
||||
const { data: { user }, error: userError } = await supabaseClient.auth.getUser();
|
||||
const recipientName = displayName || username || 'there';
|
||||
const siteUrl = Deno.env.get('SITE_URL') || 'https://thrillwiki.com';
|
||||
|
||||
if (userError || !user) {
|
||||
const duration = endRequest(tracking);
|
||||
edgeLogger.error('Authentication failed', {
|
||||
action: 'send_password_email',
|
||||
requestId: tracking.requestId,
|
||||
duration
|
||||
});
|
||||
|
||||
// Persist error to database
|
||||
const authErrorSpan = startSpan('send-password-added-email-auth-error', 'SERVER');
|
||||
endSpan(authErrorSpan, 'error', userError);
|
||||
logSpanToDatabase(authErrorSpan, tracking.requestId);
|
||||
throw new Error('Unauthorized');
|
||||
}
|
||||
|
||||
const { email, displayName, username }: EmailRequest = await req.json();
|
||||
|
||||
if (!email) {
|
||||
throw new Error('Email is required');
|
||||
}
|
||||
|
||||
edgeLogger.info('Sending password added email', {
|
||||
action: 'send_password_email',
|
||||
requestId: tracking.requestId,
|
||||
userId: user.id,
|
||||
email
|
||||
});
|
||||
|
||||
const recipientName = displayName || username || 'there';
|
||||
const siteUrl = Deno.env.get('SITE_URL') || 'https://thrillwiki.com';
|
||||
|
||||
const emailHTML = `
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<style>
|
||||
body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; line-height: 1.6; color: #333; }
|
||||
.container { max-width: 600px; margin: 0 auto; padding: 20px; }
|
||||
.header { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 30px; text-align: center; border-radius: 8px 8px 0 0; }
|
||||
.content { background: white; padding: 30px; border: 1px solid #e0e0e0; border-top: none; border-radius: 0 0 8px 8px; }
|
||||
.button { display: inline-block; background: #667eea; color: white; padding: 12px 30px; text-decoration: none; border-radius: 6px; margin: 20px 0; }
|
||||
.security-notice { background: #fff3cd; border-left: 4px solid #ffc107; padding: 15px; margin: 20px 0; border-radius: 4px; }
|
||||
.footer { text-align: center; margin-top: 30px; padding-top: 20px; border-top: 1px solid #e0e0e0; color: #666; font-size: 12px; }
|
||||
ul { line-height: 1.8; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="container">
|
||||
<div class="header">
|
||||
<h1>Password Successfully Added</h1>
|
||||
</div>
|
||||
<div class="content">
|
||||
<p>Hi ${recipientName},</p>
|
||||
|
||||
<p>Great news! A password has been successfully added to your ThrillWiki account (<strong>${email}</strong>).</p>
|
||||
|
||||
<h3>✅ What This Means</h3>
|
||||
<p>You now have an additional way to access your account. You can sign in using:</p>
|
||||
<ul>
|
||||
<li>Your email address and the password you just created</li>
|
||||
<li>Any social login methods you've connected (Google, Discord, etc.)</li>
|
||||
</ul>
|
||||
|
||||
<h3>🔐 Complete Your Setup</h3>
|
||||
<p><strong>Important:</strong> To complete your password setup, you need to confirm your email address.</p>
|
||||
|
||||
<ol style="padding-left: 20px; margin: 15px 0; line-height: 1.8;">
|
||||
<li style="margin-bottom: 8px;">Check your inbox for a <strong>confirmation email</strong> from ThrillWiki</li>
|
||||
<li style="margin-bottom: 8px;">Click the confirmation link in that email</li>
|
||||
<li style="margin-bottom: 8px;">Return to the sign-in page and log in with your email and password</li>
|
||||
</ol>
|
||||
|
||||
<a href="${siteUrl}/auth?email=${encodeURIComponent(email)}&message=complete-password-setup" class="button">
|
||||
Go to Sign In Page
|
||||
</a>
|
||||
|
||||
<p style="margin-top: 15px; font-size: 14px; color: #666;">
|
||||
<strong>Note:</strong> You must confirm your email before you can sign in with your password.
|
||||
</p>
|
||||
|
||||
<div class="security-notice">
|
||||
<strong>⚠️ Security Notice</strong><br>
|
||||
If you didn't add a password to your account, please contact our support team immediately at <strong>support@thrillwiki.com</strong>
|
||||
</div>
|
||||
|
||||
<p>Thanks for being part of the ThrillWiki community!</p>
|
||||
|
||||
<p>
|
||||
Best regards,<br>
|
||||
The ThrillWiki Team
|
||||
</p>
|
||||
</div>
|
||||
<div class="footer">
|
||||
<p>© ${new Date().getFullYear()} ThrillWiki. All rights reserved.</p>
|
||||
<p>This is an automated security notification. Please do not reply to this email.</p>
|
||||
</div>
|
||||
const emailHTML = `
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<style>
|
||||
body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; line-height: 1.6; color: #333; }
|
||||
.container { max-width: 600px; margin: 0 auto; padding: 20px; }
|
||||
.header { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 30px; text-align: center; border-radius: 8px 8px 0 0; }
|
||||
.content { background: white; padding: 30px; border: 1px solid #e0e0e0; border-top: none; border-radius: 0 0 8px 8px; }
|
||||
.button { display: inline-block; background: #667eea; color: white; padding: 12px 30px; text-decoration: none; border-radius: 6px; margin: 20px 0; }
|
||||
.security-notice { background: #fff3cd; border-left: 4px solid #ffc107; padding: 15px; margin: 20px 0; border-radius: 4px; }
|
||||
.footer { text-align: center; margin-top: 30px; padding-top: 20px; border-top: 1px solid #e0e0e0; color: #666; font-size: 12px; }
|
||||
ul { line-height: 1.8; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="container">
|
||||
<div class="header">
|
||||
<h1>Password Successfully Added</h1>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
`;
|
||||
<div class="content">
|
||||
<p>Hi ${recipientName},</p>
|
||||
|
||||
<p>Great news! A password has been successfully added to your ThrillWiki account (<strong>${email}</strong>).</p>
|
||||
|
||||
<h3>✅ What This Means</h3>
|
||||
<p>You now have an additional way to access your account. You can sign in using:</p>
|
||||
<ul>
|
||||
<li>Your email address and the password you just created</li>
|
||||
<li>Any social login methods you've connected (Google, Discord, etc.)</li>
|
||||
</ul>
|
||||
|
||||
<h3>🔐 Complete Your Setup</h3>
|
||||
<p><strong>Important:</strong> To complete your password setup, you need to confirm your email address.</p>
|
||||
|
||||
<ol style="padding-left: 20px; margin: 15px 0; line-height: 1.8;">
|
||||
<li style="margin-bottom: 8px;">Check your inbox for a <strong>confirmation email</strong> from ThrillWiki</li>
|
||||
<li style="margin-bottom: 8px;">Click the confirmation link in that email</li>
|
||||
<li style="margin-bottom: 8px;">Return to the sign-in page and log in with your email and password</li>
|
||||
</ol>
|
||||
|
||||
<a href="${siteUrl}/auth?email=${encodeURIComponent(email)}&message=complete-password-setup" class="button">
|
||||
Go to Sign In Page
|
||||
</a>
|
||||
|
||||
<p style="margin-top: 15px; font-size: 14px; color: #666;">
|
||||
<strong>Note:</strong> You must confirm your email before you can sign in with your password.
|
||||
</p>
|
||||
|
||||
<div class="security-notice">
|
||||
<strong>⚠️ Security Notice</strong><br>
|
||||
If you didn't add a password to your account, please contact our support team immediately at <strong>support@thrillwiki.com</strong>
|
||||
</div>
|
||||
|
||||
<p>Thanks for being part of the ThrillWiki community!</p>
|
||||
|
||||
<p>
|
||||
Best regards,<br>
|
||||
The ThrillWiki Team
|
||||
</p>
|
||||
</div>
|
||||
<div class="footer">
|
||||
<p>© ${new Date().getFullYear()} ThrillWiki. All rights reserved.</p>
|
||||
<p>This is an automated security notification. Please do not reply to this email.</p>
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
`;
|
||||
|
||||
const forwardEmailKey = Deno.env.get('FORWARDEMAIL_API_KEY');
|
||||
const fromEmail = Deno.env.get('FROM_EMAIL_ADDRESS') || 'noreply@thrillwiki.com';
|
||||
const forwardEmailKey = Deno.env.get('FORWARDEMAIL_API_KEY');
|
||||
const fromEmail = Deno.env.get('FROM_EMAIL_ADDRESS') || 'noreply@thrillwiki.com';
|
||||
|
||||
if (!forwardEmailKey) {
|
||||
edgeLogger.error('FORWARDEMAIL_API_KEY not configured', { requestId: tracking.requestId });
|
||||
throw new Error('Email service not configured');
|
||||
}
|
||||
|
||||
const emailResponse = 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: email,
|
||||
subject: 'Password Added to Your ThrillWiki Account',
|
||||
html: emailHTML,
|
||||
}),
|
||||
});
|
||||
|
||||
if (!emailResponse.ok) {
|
||||
const errorText = await emailResponse.text();
|
||||
edgeLogger.error('ForwardEmail API error', {
|
||||
requestId: tracking.requestId,
|
||||
status: emailResponse.status,
|
||||
errorText
|
||||
});
|
||||
throw new Error(`Failed to send email: ${emailResponse.statusText}`);
|
||||
}
|
||||
|
||||
const duration = endRequest(tracking);
|
||||
edgeLogger.info('Password addition email sent successfully', {
|
||||
action: 'send_password_email',
|
||||
requestId: tracking.requestId,
|
||||
userId: user.id,
|
||||
email,
|
||||
duration
|
||||
});
|
||||
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
success: true,
|
||||
message: 'Password addition email sent successfully',
|
||||
requestId: tracking.requestId,
|
||||
}),
|
||||
{
|
||||
status: 200,
|
||||
headers: {
|
||||
...corsHeaders,
|
||||
'Content-Type': 'application/json',
|
||||
'X-Request-ID': tracking.requestId
|
||||
},
|
||||
}
|
||||
);
|
||||
|
||||
} catch (error) {
|
||||
const duration = endRequest(tracking);
|
||||
edgeLogger.error('Error in send-password-added-email function', {
|
||||
action: 'send_password_email',
|
||||
requestId: tracking.requestId,
|
||||
duration,
|
||||
error: error instanceof Error ? error.message : 'Unknown error'
|
||||
});
|
||||
|
||||
// Persist error to database for monitoring
|
||||
const errorSpan = startSpan('send-password-added-email-error', 'SERVER');
|
||||
endSpan(errorSpan, 'error', error);
|
||||
logSpanToDatabase(errorSpan, tracking.requestId);
|
||||
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : 'Unknown error',
|
||||
requestId: tracking.requestId,
|
||||
}),
|
||||
{
|
||||
status: 500,
|
||||
headers: {
|
||||
...corsHeaders,
|
||||
'Content-Type': 'application/json',
|
||||
'X-Request-ID': tracking.requestId
|
||||
},
|
||||
}
|
||||
);
|
||||
if (!forwardEmailKey) {
|
||||
addSpanEvent(span, 'email_config_missing', {});
|
||||
throw new Error('Email service not configured');
|
||||
}
|
||||
});
|
||||
|
||||
const emailResponse = 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: email,
|
||||
subject: 'Password Added to Your ThrillWiki Account',
|
||||
html: emailHTML,
|
||||
}),
|
||||
});
|
||||
|
||||
if (!emailResponse.ok) {
|
||||
const errorText = await emailResponse.text();
|
||||
addSpanEvent(span, 'email_send_failed', {
|
||||
status: emailResponse.status,
|
||||
error: errorText
|
||||
});
|
||||
throw new Error(`Failed to send email: ${emailResponse.statusText}`);
|
||||
}
|
||||
|
||||
addSpanEvent(span, 'email_sent_successfully', { email });
|
||||
|
||||
return {
|
||||
success: true,
|
||||
message: 'Password addition email sent successfully',
|
||||
};
|
||||
};
|
||||
|
||||
serve(createEdgeFunction({
|
||||
name: 'send-password-added-email',
|
||||
requireAuth: true,
|
||||
corsHeaders,
|
||||
enableTracing: true,
|
||||
logRequests: true,
|
||||
}, handler));
|
||||
|
||||
Reference in New Issue
Block a user