Files
meet-hub/supabase/functions/send-auth-otp/index.ts
dwindown bd3841b716 Add master template wrapper to OTP emails
- Add EmailTemplateRenderer class to send-auth-otp edge function
- Wrap OTP email content in master template with brutalist design
- Email now includes proper header, footer, and styling
- No changes needed to checkout flow (uses auth page for registration)

Benefits:
- Professional branded emails with ACCESS HUB header
- Consistent brutalist design across all emails
- Responsive layout
- Better email client compatibility
2026-01-02 15:19:41 +07:00

470 lines
16 KiB
TypeScript

import { serve } from "https://deno.land/std@0.190.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",
};
interface SendOTPRequest {
user_id: string;
email: string;
}
// Email Template Renderer (Master Template)
interface EmailTemplateData {
subject: string;
content: string;
brandName?: string;
brandLogo?: string;
}
class EmailTemplateRenderer {
private static readonly MASTER_TEMPLATE = `
<!DOCTYPE html>
<html lang="id">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{{subject}}</title>
<style>
body, table, td, a { -webkit-text-size-adjust: 100%; -ms-text-size-adjust: 100%; }
table, td { mso-table-lspace: 0pt; mso-table-rspace: 0pt; }
img { -ms-interpolation-mode: bicubic; border: 0; height: auto; line-height: 100%; outline: none; text-decoration: none; }
table { border-collapse: collapse !important; }
body { height: 100% !important; margin: 0 !important; padding: 0 !important; width: 100% !important; background-color: #FFFFFF; }
:root {
--color-black: #000000;
--color-white: #FFFFFF;
--color-gray: #F4F4F5;
--color-success: #00A651;
--color-danger: #E11D48;
--border-thick: 2px solid #000000;
--border-thin: 1px solid #000000;
--shadow-hard: 4px 4px 0px 0px #000000;
}
body {
font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
color: #000000;
-webkit-font-smoothing: antialiased;
}
.email-content h1 {
font-size: 28px;
font-weight: 800;
margin: 0 0 20px 0;
letter-spacing: -1px;
line-height: 1.1;
}
.email-content h2 {
font-size: 20px;
font-weight: 700;
margin: 25px 0 15px 0;
text-transform: uppercase;
letter-spacing: 0.5px;
border-bottom: 2px solid #000;
padding-bottom: 5px;
display: inline-block;
}
.email-content h3 {
font-size: 18px;
font-weight: 700;
margin: 20px 0 10px 0;
color: #333;
}
.email-content p {
font-size: 16px;
line-height: 1.6;
margin: 0 0 20px 0;
color: #333;
}
.email-content a {
color: #000000;
text-decoration: underline;
font-weight: 700;
text-underline-offset: 3px;
}
.email-content ul, .email-content ol {
margin: 0 0 20px 0;
padding-left: 20px;
}
.email-content li {
margin-bottom: 8px;
font-size: 16px;
padding-left: 5px;
}
.email-content table {
width: 100%;
border: 2px solid #000;
margin-bottom: 25px;
border-collapse: collapse;
}
.email-content th {
background-color: #000;
color: #FFF;
padding: 12px;
text-align: left;
font-size: 14px;
text-transform: uppercase;
font-weight: 700;
border: 1px solid #000;
}
.email-content td {
padding: 12px;
border: 1px solid #000;
font-size: 15px;
vertical-align: top;
}
.email-content tr:nth-child(even) td {
background-color: #F8F8F8;
}
.btn {
display: inline-block;
background-color: #000;
color: #FFF !important;
padding: 14px 28px;
font-weight: 700;
text-transform: uppercase;
text-decoration: none !important;
font-size: 16px;
border: 2px solid #000;
box-shadow: 4px 4px 0px 0px #000000;
margin: 10px 0;
transition: all 0.1s;
}
.btn:hover {
transform: translate(2px, 2px);
box-shadow: 2px 2px 0px 0px #000000;
}
.email-content pre {
background-color: #F4F4F5;
border: 2px solid #000;
padding: 15px;
overflow-x: auto;
margin-bottom: 20px;
}
.email-content code {
font-family: 'Courier New', Courier, monospace;
font-size: 14px;
color: #E11D48;
background-color: #F4F4F5;
padding: 2px 4px;
}
.otp-box {
background-color: #F4F4F5;
border: 2px dashed #000;
padding: 20px;
text-align: center;
margin: 20px 0;
letter-spacing: 5px;
font-family: 'Courier New', Courier, monospace;
font-size: 32px;
font-weight: 700;
color: #000;
}
.email-content blockquote {
margin: 0 0 20px 0;
padding: 15px 20px;
border-left: 6px solid #000;
background-color: #F9F9F9;
font-style: italic;
font-weight: 500;
}
.alert-success { background-color: #E6F4EA; border-left-color: #00A651; color: #005A2B; }
.alert-danger { background-color: #FFE4E6; border-left-color: #E11D48; color: #881337; }
.alert-info { background-color: #E3F2FD; border-left-color: #1976D2; color: #0D47A1; }
@media screen and (max-width: 600px) {
.email-container { width: 100% !important; border-left: 0 !important; border-right: 0 !important; }
.content-padding { padding: 30px 20px !important; }
}
</style>
</head>
<body style="margin: 0; padding: 0; background-color: #FFFFFF;">
<table border="0" cellpadding="0" cellspacing="0" width="100%" style="background-color: #FFFFFF;">
<tr>
<td align="center" style="padding: 40px 0;">
<table border="0" cellpadding="0" cellspacing="0" width="600" class="email-container" style="background-color: #FFFFFF; border: 2px solid #000000; width: 600px; min-width: 320px;">
<tr>
<td align="left" style="background-color: #000000; padding: 25px 40px; border-bottom: 2px solid #000000;">
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr>
<td align="left">
<div style="font-family: 'Helvetica Neue', sans-serif; font-size: 24px; font-weight: 900; color: #FFFFFF; letter-spacing: -1px; text-transform: uppercase;">
{{brandName}}
</div>
</td>
<td align="right">
<div style="font-family: monospace; font-size: 12px; color: #888;">
NOTIF #{{timestamp}}
</div>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td class="content-padding" style="padding: 40px 40px 60px 40px;">
<div class="email-content">
{{content}}
</div>
</td>
</tr>
<tr>
<td style="padding: 30px 40px; border-top: 2px solid #000000; background-color: #F4F4F5; color: #000;">
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr>
<td align="left" style="font-size: 12px; line-height: 18px; font-family: monospace; color: #555;">
<p style="margin: 0 0 10px 0; font-weight: bold;">{{brandName}}</p>
<p style="margin: 0 0 15px 0;">Email ini dikirim otomatis. Jangan membalas email ini.</p>
<p style="margin: 0;">
<a href="#" style="color: #000; text-decoration: underline;">Ubah Preferensi</a> &nbsp;|&nbsp;
<a href="#" style="color: #000; text-decoration: underline;">Unsubscribe</a>
</p>
</td>
</tr>
</table>
</td>
</tr>
</table>
</td>
</tr>
</table>
</body>
</html>
`;
static render(data: EmailTemplateData): string {
let html = this.MASTER_TEMPLATE;
html = html.replace(/{{subject}}/g, data.subject || 'Notification');
html = html.replace(/{{brandName}}/g, data.brandName || 'ACCESS HUB');
html = html.replace(/{{brandLogo}}/g, data.brandLogo || '');
html = html.replace(/{{timestamp}}/g, Date.now().toString().slice(-6));
html = html.replace(/{{content}}/g, data.content);
return html;
}
}
// Generate 6-digit OTP code
function generateOTP(): string {
return Math.floor(100000 + Math.random() * 900000).toString();
}
serve(async (req: Request) => {
if (req.method === "OPTIONS") {
return new Response(null, { headers: corsHeaders });
}
try {
const { user_id, email }: SendOTPRequest = await req.json();
// Validate required fields
if (!user_id || !email) {
return new Response(
JSON.stringify({ success: false, message: "Missing required fields: user_id, email" }),
{ status: 400, headers: { ...corsHeaders, "Content-Type": "application/json" } }
);
}
// Basic email validation
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (!emailRegex.test(email)) {
return new Response(
JSON.stringify({ success: false, message: "Invalid email format" }),
{ status: 400, headers: { ...corsHeaders, "Content-Type": "application/json" } }
);
}
// Initialize Supabase client with service role
const supabaseUrl = Deno.env.get('SUPABASE_URL')!;
const supabaseServiceKey = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!;
const supabase = createClient(supabaseUrl, supabaseServiceKey, {
auth: {
autoRefreshToken: false,
persistSession: false
}
});
// Generate OTP code
const otpCode = generateOTP();
const expiresAt = new Date(Date.now() + 15 * 60 * 1000); // 15 minutes from now
console.log(`Generating OTP for user ${user_id}, email ${email}`);
// Store OTP in database
const { error: otpError } = await supabase
.from('auth_otps')
.insert({
user_id,
email,
otp_code: otpCode,
expires_at: expiresAt.toISOString(),
});
if (otpError) {
console.error('Error storing OTP:', otpError);
throw new Error(`Failed to store OTP: ${otpError.message}`);
}
// Get notification settings
const { data: settings, error: settingsError } = await supabase
.from('notification_settings')
.select('*')
.single();
if (settingsError || !settings) {
console.error('Error fetching notification settings:', settingsError);
throw new Error('Notification settings not configured');
}
// Get email template
console.log('Fetching email template with key: auth_email_verification');
const { data: template, error: templateError } = await supabase
.from('notification_templates')
.select('*')
.eq('key', 'auth_email_verification')
.single();
console.log('Template query result:', { template, templateError });
if (templateError || !template) {
console.error('Error fetching email template:', templateError);
throw new Error('Email template not found. Please create template with key: auth_email_verification');
}
// Get user data from auth.users
const { data: { user }, error: userError } = await supabase.auth.admin.getUserById(user_id);
if (userError || !user) {
console.error('Error fetching user:', userError);
throw new Error('User not found');
}
// Prepare template variables
const templateVars = {
platform_name: settings.platform_name || 'Platform',
nama: user.user_metadata?.name || user.email || 'Pengguna',
email: email,
otp_code: otpCode,
expiry_minutes: '15',
confirmation_link: '', // Not used for OTP
year: new Date().getFullYear().toString(),
};
// Process shortcodes in subject
let subject = template.email_subject;
Object.entries(templateVars).forEach(([key, value]) => {
subject = subject.replace(new RegExp(`{${key}}`, 'g'), value);
});
// Process shortcodes in HTML body content
let htmlContent = template.email_body_html;
Object.entries(templateVars).forEach(([key, value]) => {
htmlContent = htmlContent.replace(new RegExp(`{${key}}`, 'g'), value);
});
// Wrap in master template
const htmlBody = EmailTemplateRenderer.render({
subject: subject,
content: htmlContent,
brandName: settings.platform_name || 'ACCESS HUB',
});
// Send email via send-email-v2
console.log(`Sending OTP email to ${email}`);
console.log('Settings:', {
hasMailketingToken: !!settings.mailketing_api_token,
hasApiToken: !!settings.api_token,
hasFromName: !!settings.from_name,
hasFromEmail: !!settings.from_email,
platformName: settings.platform_name,
});
// Use api_token (not mailketing_api_token)
const apiToken = settings.api_token || settings.mailketing_api_token;
if (!apiToken) {
throw new Error('API token not found in notification_settings');
}
// Log email details (truncate HTML body for readability)
console.log('Email payload:', {
to: email,
from_name: settings.from_name || settings.platform_name || 'Admin',
from_email: settings.from_email || 'noreply@example.com',
subject: subject,
html_body_length: htmlBody.length,
html_body_preview: htmlBody.substring(0, 200),
});
const emailResponse = await fetch(`${supabaseUrl}/functions/v1/send-email-v2`, {
method: 'POST',
headers: {
'Authorization': `Bearer ${supabaseServiceKey}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
to: email,
api_token: apiToken,
from_name: settings.from_name || settings.platform_name || 'Admin',
from_email: settings.from_email || 'noreply@example.com',
subject: subject,
html_body: htmlBody,
}),
});
if (!emailResponse.ok) {
const errorText = await emailResponse.text();
console.error('Email send error:', emailResponse.status, errorText);
throw new Error(`Failed to send email: ${emailResponse.status} ${errorText}`);
}
const emailResult = await emailResponse.json();
console.log('Email sent successfully:', emailResult);
// Note: notification_logs table doesn't exist, skipping logging
return new Response(
JSON.stringify({
success: true,
message: 'OTP sent successfully'
}),
{ status: 200, headers: { ...corsHeaders, "Content-Type": "application/json" } }
);
} catch (error: any) {
console.error("Error sending OTP:", error);
// Note: notification_logs table doesn't exist, skipping error logging
return new Response(
JSON.stringify({
success: false,
message: error.message || "Failed to send OTP"
}),
{ status: 500, headers: { ...corsHeaders, "Content-Type": "application/json" } }
);
}
});