From 06d68454565ded12e085e73590bdb9d119e482cf Mon Sep 17 00:00:00 2001 From: dwindown Date: Fri, 2 Jan 2026 14:31:23 +0700 Subject: [PATCH] Fix API token mapping and add extensive debug logging MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Fixed api_token vs mailketing_api_token column mapping - Added comprehensive debug logging to send-auth-otp - Added fallback logic for missing settings fields - Improved error messages for troubleshooting 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Sonnet 4.5 --- check_template.sh | 20 +++ deploy-auth-functions.sh | 18 ++ supabase/functions/send-auth-otp/index.ts | 32 +++- .../20250102000003_fix_auth_otps_fk.sql | 26 +++ .../20250102000004_insert_auth_template.sql | 157 ++++++++++++++++++ 5 files changed, 249 insertions(+), 4 deletions(-) create mode 100755 check_template.sh create mode 100755 deploy-auth-functions.sh create mode 100644 supabase/migrations/20250102000003_fix_auth_otps_fk.sql create mode 100644 supabase/migrations/20250102000004_insert_auth_template.sql diff --git a/check_template.sh b/check_template.sh new file mode 100755 index 0000000..945c765 --- /dev/null +++ b/check_template.sh @@ -0,0 +1,20 @@ +#!/bin/bash + +# Test query to check if template exists and what's in the table +# Run this in your Supabase SQL editor or via psql + +echo "=== Check if template exists ===" +cat << 'SQL' +-- Check if template exists +SELECT key, name, is_active +FROM notification_templates +WHERE key = 'auth_email_verification'; + +-- Check all templates +SELECT key, name, is_active +FROM notification_templates +ORDER BY key; + +-- Check table structure +\d notification_templates; +SQL diff --git a/deploy-auth-functions.sh b/deploy-auth-functions.sh new file mode 100755 index 0000000..2bba4be --- /dev/null +++ b/deploy-auth-functions.sh @@ -0,0 +1,18 @@ +#!/bin/bash + +# Deploy Auth OTP Edge Functions to Self-Hosted Supabase + +SUPABASE_URL="https://lovable.backoffice.biz.id" +SERVICE_ROLE_KEY="eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJzdXBhYmFzZSIsImlhdCI6MTc2NjAzNzEyMCwiZXhwIjo0OTIxNzEwNzIwLCJyb2xlIjoic2VydmljZV9yb2xlIn0.t6D9VwaukYGq4c_VbW1bkd3ZkKgldpCKRR13nN14XXc" + +echo "Deploying send-auth-otp..." + +curl -X POST "${SUPABASE_URL}/functions/v1/send-auth-otp" \ + -H "Authorization: Bearer ${SERVICE_ROLE_KEY}" \ + -H "Content-Type: application/json" \ + -d '{"user_id":"test","email":"test@test.com"}' \ + -v + +echo "" +echo "If you see a response above, the function is deployed." +echo "If you see 404, the function needs to be deployed manually to your Supabase instance." diff --git a/supabase/functions/send-auth-otp/index.ts b/supabase/functions/send-auth-otp/index.ts index 894b404..11b60c8 100644 --- a/supabase/functions/send-auth-otp/index.ts +++ b/supabase/functions/send-auth-otp/index.ts @@ -44,7 +44,12 @@ serve(async (req: Request) => { // 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); + const supabase = createClient(supabaseUrl, supabaseServiceKey, { + auth: { + autoRefreshToken: false, + persistSession: false + } + }); // Generate OTP code const otpCode = generateOTP(); @@ -79,12 +84,16 @@ serve(async (req: Request) => { } // 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'); @@ -123,6 +132,21 @@ serve(async (req: Request) => { // 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, + allSettings: JSON.stringify(settings) + }); + + // 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'); + } const emailResponse = await fetch(`${supabaseUrl}/functions/v1/send-email-v2`, { method: 'POST', @@ -132,9 +156,9 @@ serve(async (req: Request) => { }, body: JSON.stringify({ to: email, - api_token: settings.mailketing_api_token, - from_name: settings.from_name, - from_email: settings.from_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, }), diff --git a/supabase/migrations/20250102000003_fix_auth_otps_fk.sql b/supabase/migrations/20250102000003_fix_auth_otps_fk.sql new file mode 100644 index 0000000..ec8710f --- /dev/null +++ b/supabase/migrations/20250102000003_fix_auth_otps_fk.sql @@ -0,0 +1,26 @@ +-- ============================================================================ +-- Fix auth_otps foreign key constraint +-- ============================================================================ + +-- Drop the foreign key constraint since unconfirmed users might not be fully accessible +DO $$ +BEGIN + IF EXISTS ( + SELECT 1 FROM pg_constraint + WHERE conname = 'auth_otps_user_id_fkey' + ) THEN + ALTER TABLE auth_otps DROP CONSTRAINT auth_otps_user_id_fkey; + END IF; +END $$; + +-- Add a check constraint to ensure user_id is a valid UUID +ALTER TABLE auth_otps ADD CONSTRAINT auth_otps_user_id_valid + CHECK (user_id::text ~ '[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}'::text); + +COMMENT ON TABLE auth_otps IS 'Stores OTP codes for email verification. No FK constraint to handle unconfirmed users.'; + +-- Return success message +DO $$ +BEGIN + RAISE NOTICE 'Foreign key constraint removed from auth_otps table'; +END $$; diff --git a/supabase/migrations/20250102000004_insert_auth_template.sql b/supabase/migrations/20250102000004_insert_auth_template.sql new file mode 100644 index 0000000..7a75d64 --- /dev/null +++ b/supabase/migrations/20250102000004_insert_auth_template.sql @@ -0,0 +1,157 @@ +-- ============================================================================ +-- Insert Auth Email Verification Template (Fixed) +-- ============================================================================ + +-- First, let's see what columns the table actually has +-- This will help us insert correctly + +-- Check if template exists +DO $$ +DECLARE + template_count int; +BEGIN + SELECT COUNT(*) INTO template_count + FROM notification_templates + WHERE key = 'auth_email_verification'; + + IF template_count = 0 THEN + -- Template doesn't exist, insert it + INSERT INTO notification_templates ( + key, + name, + is_active, + email_subject, + email_body_html + ) VALUES ( + 'auth_email_verification', + 'Verifikasi Email - OTP', + true, + 'Kode Verifikasi Email Anda - {platform_name}', + '--- + + + + + + Verifikasi Email + + + +
+
+

🔐 Verifikasi Email

+
+ +
+

Halo {nama},

+ +

+ Terima kasih telah mendaftar di {platform_name}! + Gunakan kode OTP berikut untuk memverifikasi alamat email Anda: +

+ +
+
{otp_code}
+
⏰ Berlaku selama {expiry_minutes} menit
+
+ +
+ Cara menggunakan:
+ 1. Salin kode 6 digit di atas
+ 2. Kembali ke halaman pendaftaran
+ 3. Masukkan kode tersebut pada form verifikasi +
+ +

+ Jika Anda tidak merasa mendaftar di {platform_name}, + abaikan email ini dengan aman. +

+
+ + +
+ + +---' + ); + + RAISE NOTICE 'Auth email verification template inserted successfully'; + ELSE + RAISE NOTICE 'Template already exists, skipping insertion'; + END IF; +END $$;