Fix email unconfirmed login flow with OTP resend and update email API field names

This commit is contained in:
dwindown
2026-01-02 19:33:51 +07:00
parent 8f46c5cfd9
commit eee6339074
13 changed files with 668 additions and 65 deletions

View File

@@ -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,
},
});

View 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" } }
);
}
});

View File

@@ -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,
}),
});

View File

@@ -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,
},
});

View File

@@ -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}`);

View File

@@ -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,