Fix email unconfirmed login flow with OTP resend and update email API field names
This commit is contained in:
@@ -1,5 +1,6 @@
|
||||
import { serve } from "https://deno.land/std@0.190.0/http/server.ts";
|
||||
import { createClient } from "https://esm.sh/@supabase/supabase-js@2";
|
||||
import { EmailTemplateRenderer } from "../shared/email-template-renderer.ts";
|
||||
|
||||
const corsHeaders = {
|
||||
"Access-Control-Allow-Origin": "*",
|
||||
@@ -82,6 +83,14 @@ serve(async (req: Request): Promise<Response> => {
|
||||
.select("*")
|
||||
.single();
|
||||
|
||||
// Get platform settings for brand_name
|
||||
const { data: platformSettings } = await supabase
|
||||
.from("platform_settings")
|
||||
.select("brand_name")
|
||||
.single();
|
||||
|
||||
const brandName = platformSettings?.brand_name || "ACCESS HUB";
|
||||
|
||||
let notifyError = null;
|
||||
|
||||
if (template && emailSettings?.api_token) {
|
||||
@@ -98,6 +107,7 @@ serve(async (req: Request): Promise<Response> => {
|
||||
jam_konsultasi: `${slot.start_time.substring(0, 5)} - ${slot.end_time.substring(0, 5)} WIB`,
|
||||
link_meet: slot.meet_link || "Akan diinformasikan",
|
||||
jenis_konsultasi: slot.topic_category,
|
||||
platform_name: brandName,
|
||||
};
|
||||
|
||||
// Process shortcodes in template
|
||||
@@ -110,15 +120,22 @@ serve(async (req: Request): Promise<Response> => {
|
||||
emailSubject = emailSubject.replace(regex, String(value));
|
||||
});
|
||||
|
||||
// Wrap with master template
|
||||
const fullHtml = EmailTemplateRenderer.render({
|
||||
subject: emailSubject,
|
||||
content: emailBody,
|
||||
brandName: brandName,
|
||||
});
|
||||
|
||||
// Send via send-email-v2 (Mailketing API)
|
||||
const { error: emailError } = await supabase.functions.invoke("send-email-v2", {
|
||||
body: {
|
||||
to: profile.email,
|
||||
recipient: profile.email,
|
||||
api_token: emailSettings.api_token,
|
||||
from_name: emailSettings.from_name || "Access Hub",
|
||||
from_name: emailSettings.from_name || brandName,
|
||||
from_email: emailSettings.from_email || "noreply@with.dwindi.com",
|
||||
subject: emailSubject,
|
||||
html_body: emailBody,
|
||||
content: fullHtml,
|
||||
},
|
||||
});
|
||||
|
||||
|
||||
97
supabase/functions/get-user-by-email/index.ts
Normal file
97
supabase/functions/get-user-by-email/index.ts
Normal file
@@ -0,0 +1,97 @@
|
||||
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 GetUserRequest {
|
||||
email: string;
|
||||
}
|
||||
|
||||
serve(async (req: Request) => {
|
||||
if (req.method === "OPTIONS") {
|
||||
return new Response(null, { headers: corsHeaders });
|
||||
}
|
||||
|
||||
try {
|
||||
const { email }: GetUserRequest = await req.json();
|
||||
|
||||
// Validate required fields
|
||||
if (!email) {
|
||||
return new Response(
|
||||
JSON.stringify({ success: false, message: "Missing required field: 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
|
||||
}
|
||||
});
|
||||
|
||||
console.log(`Looking up user with email: ${email}`);
|
||||
|
||||
// Get user by email from auth.users
|
||||
const { data: { users }, error } = await supabase.auth.admin.listUsers();
|
||||
|
||||
if (error) {
|
||||
console.error('Error listing users:', error);
|
||||
throw new Error(`Failed to lookup user: ${error.message}`);
|
||||
}
|
||||
|
||||
// Find user with matching email
|
||||
const user = users?.find(u => u.email === email);
|
||||
|
||||
if (!user) {
|
||||
console.log('User not found:', email);
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
success: false,
|
||||
message: "User not found",
|
||||
user_id: null
|
||||
}),
|
||||
{ status: 404, headers: { ...corsHeaders, "Content-Type": "application/json" } }
|
||||
);
|
||||
}
|
||||
|
||||
console.log('User found:', { id: user.id, email: user.email, emailConfirmed: user.email_confirmed_at });
|
||||
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
success: true,
|
||||
user_id: user.id,
|
||||
email_confirmed: !!user.email_confirmed_at,
|
||||
created_at: user.created_at
|
||||
}),
|
||||
{ status: 200, headers: { ...corsHeaders, "Content-Type": "application/json" } }
|
||||
);
|
||||
|
||||
} catch (error: any) {
|
||||
console.error("Error getting user by email:", error);
|
||||
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
success: false,
|
||||
message: error.message || "Failed to lookup user",
|
||||
user_id: null
|
||||
}),
|
||||
{ status: 500, headers: { ...corsHeaders, "Content-Type": "application/json" } }
|
||||
);
|
||||
}
|
||||
});
|
||||
@@ -84,6 +84,19 @@ serve(async (req: Request) => {
|
||||
throw new Error('Notification settings not configured');
|
||||
}
|
||||
|
||||
// Get platform settings for brand_name
|
||||
const { data: platformSettings, error: platformError } = await supabase
|
||||
.from('platform_settings')
|
||||
.select('brand_name')
|
||||
.single();
|
||||
|
||||
if (platformError) {
|
||||
console.error('Error fetching platform settings:', platformError);
|
||||
// Continue with fallback if platform settings not found
|
||||
}
|
||||
|
||||
const brandName = platformSettings?.brand_name || settings.platform_name || 'ACCESS HUB';
|
||||
|
||||
// Get email template
|
||||
console.log('Fetching email template with key: auth_email_verification');
|
||||
|
||||
@@ -110,7 +123,7 @@ serve(async (req: Request) => {
|
||||
|
||||
// Prepare template variables
|
||||
const templateVars = {
|
||||
platform_name: settings.platform_name || 'Platform',
|
||||
platform_name: brandName,
|
||||
nama: user.user_metadata?.name || user.email || 'Pengguna',
|
||||
email: email,
|
||||
otp_code: otpCode,
|
||||
@@ -135,7 +148,7 @@ serve(async (req: Request) => {
|
||||
const htmlBody = EmailTemplateRenderer.render({
|
||||
subject: subject,
|
||||
content: htmlContent,
|
||||
brandName: settings.platform_name || 'ACCESS HUB',
|
||||
brandName: brandName,
|
||||
});
|
||||
|
||||
// Send email via send-email-v2
|
||||
@@ -157,12 +170,12 @@ serve(async (req: Request) => {
|
||||
|
||||
// Log email details (truncate HTML body for readability)
|
||||
console.log('Email payload:', {
|
||||
to: email,
|
||||
from_name: settings.from_name || settings.platform_name || 'Admin',
|
||||
recipient: email,
|
||||
from_name: settings.from_name || brandName,
|
||||
from_email: settings.from_email || 'noreply@example.com',
|
||||
subject: subject,
|
||||
html_body_length: htmlBody.length,
|
||||
html_body_preview: htmlBody.substring(0, 200),
|
||||
content_length: htmlBody.length,
|
||||
content_preview: htmlBody.substring(0, 200),
|
||||
});
|
||||
|
||||
const emailResponse = await fetch(`${supabaseUrl}/functions/v1/send-email-v2`, {
|
||||
@@ -172,12 +185,12 @@ serve(async (req: Request) => {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
to: email,
|
||||
recipient: email,
|
||||
api_token: apiToken,
|
||||
from_name: settings.from_name || settings.platform_name || 'Admin',
|
||||
from_name: settings.from_name || brandName,
|
||||
from_email: settings.from_email || 'noreply@example.com',
|
||||
subject: subject,
|
||||
html_body: htmlBody,
|
||||
content: htmlBody,
|
||||
}),
|
||||
});
|
||||
|
||||
|
||||
@@ -143,12 +143,12 @@ serve(async (req: Request): Promise<Response> => {
|
||||
// Send via send-email-v2 (Mailketing API)
|
||||
const { error: emailError } = await supabase.functions.invoke("send-email-v2", {
|
||||
body: {
|
||||
to: profile.email,
|
||||
recipient: profile.email,
|
||||
api_token: smtpSettings.api_token,
|
||||
from_name: smtpSettings.from_name || platformSettings?.brand_name || "Access Hub",
|
||||
from_email: smtpSettings.from_email || "noreply@with.dwindi.com",
|
||||
subject: emailSubject,
|
||||
html_body: emailBody,
|
||||
content: emailBody,
|
||||
},
|
||||
});
|
||||
|
||||
|
||||
@@ -6,33 +6,35 @@ const corsHeaders = {
|
||||
};
|
||||
|
||||
interface EmailRequest {
|
||||
to: string;
|
||||
recipient: string;
|
||||
api_token: string;
|
||||
from_name: string;
|
||||
from_email: string;
|
||||
subject: string;
|
||||
html_body: string;
|
||||
content: string;
|
||||
}
|
||||
|
||||
// Send via Mailketing API
|
||||
async function sendViaMailketing(request: EmailRequest): Promise<{ success: boolean; message: string }> {
|
||||
const { to, api_token, from_name, from_email, subject, html_body } = request;
|
||||
const { recipient, api_token, from_name, from_email, subject, content } = request;
|
||||
|
||||
const formData = new FormData();
|
||||
formData.append('to', to);
|
||||
formData.append('from_name', from_name);
|
||||
formData.append('from_email', from_email);
|
||||
formData.append('subject', subject);
|
||||
formData.append('html_body', html_body);
|
||||
// Build form-encoded body (http_build_query format)
|
||||
const params = new URLSearchParams();
|
||||
params.append('api_token', api_token);
|
||||
params.append('from_name', from_name);
|
||||
params.append('from_email', from_email);
|
||||
params.append('recipient', recipient);
|
||||
params.append('subject', subject);
|
||||
params.append('content', content);
|
||||
|
||||
console.log(`Sending email via Mailketing to ${to}`);
|
||||
console.log(`Sending email via Mailketing to ${recipient}`);
|
||||
|
||||
const response = await fetch('https://api.mailketing.co/v1/send', {
|
||||
const response = await fetch('https://api.mailketing.co.id/api/v1/send', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Authorization': `Bearer ${api_token}`,
|
||||
'Content-Type': 'application/x-www-form-urlencoded',
|
||||
},
|
||||
body: formData,
|
||||
body: params.toString(),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
@@ -46,7 +48,7 @@ async function sendViaMailketing(request: EmailRequest): Promise<{ success: bool
|
||||
|
||||
return {
|
||||
success: true,
|
||||
message: result.message || 'Email sent successfully via Mailketing'
|
||||
message: result.response || 'Email sent successfully via Mailketing'
|
||||
};
|
||||
}
|
||||
|
||||
@@ -59,23 +61,23 @@ serve(async (req: Request): Promise<Response> => {
|
||||
const body: EmailRequest = await req.json();
|
||||
|
||||
// Validate required fields
|
||||
if (!body.to || !body.api_token || !body.from_name || !body.from_email || !body.subject || !body.html_body) {
|
||||
if (!body.recipient || !body.api_token || !body.from_name || !body.from_email || !body.subject || !body.content) {
|
||||
return new Response(
|
||||
JSON.stringify({ success: false, message: "Missing required fields: to, api_token, from_name, from_email, subject, html_body" }),
|
||||
JSON.stringify({ success: false, message: "Missing required fields: recipient, api_token, from_name, from_email, subject, content" }),
|
||||
{ status: 400, headers: { ...corsHeaders, "Content-Type": "application/json" } }
|
||||
);
|
||||
}
|
||||
|
||||
// Basic email validation
|
||||
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
||||
if (!emailRegex.test(body.to) || !emailRegex.test(body.from_email)) {
|
||||
if (!emailRegex.test(body.recipient) || !emailRegex.test(body.from_email)) {
|
||||
return new Response(
|
||||
JSON.stringify({ success: false, message: "Invalid email format" }),
|
||||
{ status: 400, headers: { ...corsHeaders, "Content-Type": "application/json" } }
|
||||
);
|
||||
}
|
||||
|
||||
console.log(`Attempting to send email to: ${body.to}`);
|
||||
console.log(`Attempting to send email to: ${body.recipient}`);
|
||||
console.log(`From: ${body.from_name} <${body.from_email}>`);
|
||||
console.log(`Subject: ${body.subject}`);
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { serve } from "https://deno.land/std@0.190.0/http/server.ts";
|
||||
import { createClient } from "https://esm.sh/@supabase/supabase-js@2";
|
||||
import { EmailTemplateRenderer } from "../shared/email-template-renderer.ts";
|
||||
|
||||
const corsHeaders = {
|
||||
"Access-Control-Allow-Origin": "*",
|
||||
@@ -246,7 +247,14 @@ serve(async (req: Request): Promise<Response> => {
|
||||
};
|
||||
|
||||
const subject = replaceVariables(template.subject, allVariables);
|
||||
const htmlBody = replaceVariables(template.body_html || template.body_text || "", allVariables);
|
||||
const htmlContent = replaceVariables(template.body_html || template.body_text || "", allVariables);
|
||||
|
||||
// Wrap with master template for consistent branding
|
||||
const htmlBody = EmailTemplateRenderer.render({
|
||||
subject: subject,
|
||||
content: htmlContent,
|
||||
brandName: settings.brand_name || "ACCESS HUB",
|
||||
});
|
||||
|
||||
const emailPayload: EmailPayload = {
|
||||
to: recipient_email,
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
-- ============================================================================
|
||||
-- Fix Auth OTP Email Template - Content Only (for master template wrapper)
|
||||
-- ============================================================================
|
||||
|
||||
-- Update auth_email_verification template to be content-only
|
||||
-- This will be wrapped by EmailTemplateRenderer with master template
|
||||
UPDATE notification_templates
|
||||
SET
|
||||
email_subject = 'Kode Verifikasi Email Anda - {platform_name}',
|
||||
email_body_html = '---
|
||||
<h1>🔐 Verifikasi Email</h1>
|
||||
<p>Halo <strong>{nama}</strong>, terima kasih telah mendaftar di <strong>{platform_name}</strong>! Gunakan kode OTP berikut untuk memverifikasi alamat email Anda:</p>
|
||||
|
||||
<div class="otp-box">{otp_code}</div>
|
||||
|
||||
<p>Kode ini akan kedaluwarsa dalam <strong>{expiry_minutes} menit</strong>.</p>
|
||||
|
||||
<h3>Cara menggunakan:</h3>
|
||||
<ol>
|
||||
<li>Salin kode 6 digit di atas</li>
|
||||
<li>Kembali ke halaman pendaftaran</li>
|
||||
<li>Masukkan kode tersebut pada form verifikasi</li>
|
||||
</ol>
|
||||
|
||||
<blockquote class="alert-info">
|
||||
<strong>Info:</strong> Jika Anda tidak merasa mendaftar di {platform_name}, abaikan email ini dengan aman.
|
||||
</blockquote>
|
||||
---'
|
||||
WHERE key = 'auth_email_verification';
|
||||
|
||||
-- Add comment documenting the change
|
||||
COMMENT ON COLUMN notification_templates.email_body_html IS
|
||||
'For templates wrapped with master template: Store ONLY content HTML (no <html>, <head>, <body> tags).
|
||||
Use {variable} placeholders for dynamic data. Content will be auto-styled by .tiptap-content CSS.';
|
||||
|
||||
-- Return success message
|
||||
DO $$
|
||||
BEGIN
|
||||
RAISE NOTICE 'Auth email template updated to content-only format for master template wrapper';
|
||||
END $$;
|
||||
@@ -37,14 +37,14 @@ export class EmailTemplateRenderer {
|
||||
-webkit-font-smoothing: antialiased;
|
||||
}
|
||||
|
||||
.email-content h1 {
|
||||
.tiptap-content h1 {
|
||||
font-size: 28px;
|
||||
font-weight: 800;
|
||||
margin: 0 0 20px 0;
|
||||
letter-spacing: -1px;
|
||||
line-height: 1.1;
|
||||
}
|
||||
.email-content h2 {
|
||||
.tiptap-content h2 {
|
||||
font-size: 20px;
|
||||
font-weight: 700;
|
||||
margin: 25px 0 15px 0;
|
||||
@@ -54,43 +54,43 @@ export class EmailTemplateRenderer {
|
||||
padding-bottom: 5px;
|
||||
display: inline-block;
|
||||
}
|
||||
.email-content h3 {
|
||||
.tiptap-content h3 {
|
||||
font-size: 18px;
|
||||
font-weight: 700;
|
||||
margin: 20px 0 10px 0;
|
||||
color: #333;
|
||||
}
|
||||
.email-content p {
|
||||
.tiptap-content p {
|
||||
font-size: 16px;
|
||||
line-height: 1.6;
|
||||
margin: 0 0 20px 0;
|
||||
color: #333;
|
||||
}
|
||||
|
||||
.email-content a {
|
||||
.tiptap-content a {
|
||||
color: #000000;
|
||||
text-decoration: underline;
|
||||
font-weight: 700;
|
||||
text-underline-offset: 3px;
|
||||
}
|
||||
|
||||
.email-content ul, .email-content ol {
|
||||
.tiptap-content ul, .tiptap-content ol {
|
||||
margin: 0 0 20px 0;
|
||||
padding-left: 20px;
|
||||
}
|
||||
.email-content li {
|
||||
.tiptap-content li {
|
||||
margin-bottom: 8px;
|
||||
font-size: 16px;
|
||||
padding-left: 5px;
|
||||
}
|
||||
|
||||
.email-content table {
|
||||
.tiptap-content table {
|
||||
width: 100%;
|
||||
border: 2px solid #000;
|
||||
margin-bottom: 25px;
|
||||
border-collapse: collapse;
|
||||
}
|
||||
.email-content th {
|
||||
.tiptap-content th {
|
||||
background-color: #000;
|
||||
color: #FFF;
|
||||
padding: 12px;
|
||||
@@ -100,13 +100,13 @@ export class EmailTemplateRenderer {
|
||||
font-weight: 700;
|
||||
border: 1px solid #000;
|
||||
}
|
||||
.email-content td {
|
||||
.tiptap-content td {
|
||||
padding: 12px;
|
||||
border: 1px solid #000;
|
||||
font-size: 15px;
|
||||
vertical-align: top;
|
||||
}
|
||||
.email-content tr:nth-child(even) td {
|
||||
.tiptap-content tr:nth-child(even) td {
|
||||
background-color: #F8F8F8;
|
||||
}
|
||||
|
||||
@@ -129,14 +129,14 @@ export class EmailTemplateRenderer {
|
||||
box-shadow: 2px 2px 0px 0px #000000;
|
||||
}
|
||||
|
||||
.email-content pre {
|
||||
.tiptap-content pre {
|
||||
background-color: #F4F4F5;
|
||||
border: 2px solid #000;
|
||||
padding: 15px;
|
||||
overflow-x: auto;
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
.email-content code {
|
||||
.tiptap-content code {
|
||||
font-family: 'Courier New', Courier, monospace;
|
||||
font-size: 14px;
|
||||
color: #E11D48;
|
||||
@@ -157,7 +157,7 @@ export class EmailTemplateRenderer {
|
||||
color: #000;
|
||||
}
|
||||
|
||||
.email-content blockquote {
|
||||
.tiptap-content blockquote {
|
||||
margin: 0 0 20px 0;
|
||||
padding: 15px 20px;
|
||||
border-left: 6px solid #000;
|
||||
@@ -205,7 +205,8 @@ export class EmailTemplateRenderer {
|
||||
|
||||
<tr>
|
||||
<td class="content-padding" style="padding: 40px 40px 60px 40px;">
|
||||
<div class="email-content">
|
||||
<!-- DYNAMIC CONTENT WRAPPER (.tiptap-content) -->
|
||||
<div class="tiptap-content">
|
||||
{{content}}
|
||||
</div>
|
||||
</td>
|
||||
|
||||
Reference in New Issue
Block a user