All files / app/api/auth/phone/verify-update route.ts

78.39% Statements 127/162
79.31% Branches 23/29
100% Functions 3/3
78.39% Lines 127/162

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 2281x                       9x 9x 9x     8x 8x 8x 8x   9x 1x 1x   7x 7x   9x 2x 2x   9x 1x 1x   4x     4x 4x   4x 9x 1x 1x 1x 1x 1x     9x 2x   2x   2x 1x 1x 1x 1x 1x 1x     1x 1x   2x       1x 1x 1x   1x 1x 1x 1x   2x                                                           1x     1x     1x   1x 1x 1x 1x 1x 1x 1x     1x   1x 1x 1x 1x 1x   9x             1x     1x 1x 9x 1x 1x 1x 1x 1x     1x   1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 9x             2x 2x 2x         2x 2x 2x 2x         2x 2x 2x 2x 2x 2x 2x 2x 2x 2x   2x 2x 2x 2x 2x 2x   2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x     2x  
import { NextRequest, NextResponse } from 'next/server';
import { createClient } from '@/lib/supabase/server';
import { createClient as createAdminClient } from '@supabase/supabase-js';
import { formatPhoneNumber } from '@/lib/auth/otp';
import { checkRateLimit, incrementRateLimit, clearRateLimit } from '@/lib/auth/rate-limit';
import { getClientInfo, hashIP } from '@/lib/auth/login-events';
import { checkVerificationCode, isTwilioConfigured } from '@/lib/twilio/verify';
 
/**
 * Verify OTP and update phone number for authenticated users
 * Step 2: Confirm phone update with OTP
 */
export async function POST(request: NextRequest) {
  try {
    const supabase = await createClient();
 
    // Get current user
    const {
      data: { user },
      error: userError,
    } = await supabase.auth.getUser();
 
    if (userError || !user) {
      return NextResponse.json({ error: 'Not authenticated' }, { status: 401 });
    }
 
    const body = await request.json();
    const { phone, countryCode = '+91', token } = body;
 
    if (!phone || !token) {
      return NextResponse.json({ error: 'Phone and OTP are required' }, { status: 400 });
    }
 
    if (token.length !== 6 || !/^\d+$/.test(token)) {
      return NextResponse.json({ error: 'OTP must be 6 digits' }, { status: 400 });
    }
 
    const formattedPhone = formatPhoneNumber(phone, countryCode);
 
    // Check rate limit
    const { ipAddress } = getClientInfo(request.headers);
    const ipHash = hashIP(ipAddress);
 
    const rateLimitResult = await checkRateLimit(formattedPhone, 'phone', 'otp_verify');
    if (!rateLimitResult.allowed) {
      return NextResponse.json(
        { error: 'Too many attempts. Please request a new OTP.' },
        { status: 429 }
      );
    }
 
    // Use direct Twilio Verify if configured
    if (isTwilioConfigured()) {
      console.log('Using Twilio Verify for phone update verification:', formattedPhone);
 
      const twilioResult = await checkVerificationCode(formattedPhone, token);
 
      if (!twilioResult.success || !twilioResult.valid) {
        await incrementRateLimit(formattedPhone, 'phone');
        return NextResponse.json(
          { error: twilioResult.error || 'Invalid or expired OTP' },
          { status: 401 }
        );
      }
 
      // OTP verified via Twilio - update user's phone in Supabase
      const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL;
      const serviceRoleKey = process.env.SUPABASE_SERVICE_ROLE_KEY;
 
      if (!supabaseUrl || !serviceRoleKey) {
        return NextResponse.json({ error: 'Server configuration error' }, { status: 500 });
      }
 
      const adminClient = createAdminClient(supabaseUrl, serviceRoleKey, {
        auth: { autoRefreshToken: false, persistSession: false },
      });
 
      const { error: updateError } = await adminClient.auth.admin.updateUserById(user.id, {
        phone: formattedPhone,
        phone_confirm: true,
      });
 
      if (updateError) {
        console.error('Failed to update phone in Supabase:', {
          error: updateError,
          code: updateError.code,
          message: updateError.message,
          status: updateError.status,
          userId: user.id,
          phone: formattedPhone,
        });
 
        // Provide more specific error messages based on error type
        let errorMessage = 'Failed to update phone number';
        if (
          updateError.message?.includes('duplicate') ||
          updateError.message?.includes('already')
        ) {
          errorMessage = 'This phone number is already registered to another account';
        } else if (
          updateError.message?.includes('invalid') ||
          updateError.message?.includes('format')
        ) {
          errorMessage = 'Invalid phone number format. Please check and try again.';
        } else if (updateError.status === 401 || updateError.status === 403) {
          errorMessage = 'Server authorization error. Please contact support.';
        }
 
        return NextResponse.json({ error: errorMessage }, { status: 500 });
      }
 
      // Clear rate limits
      await Promise.all([clearRateLimit(formattedPhone, 'phone'), clearRateLimit(ipHash, 'ip')]);
 
      // Sync phone to public.users table (auth.users doesn't trigger public.users update)
      await syncPhoneToPublicUsers(adminClient, user.id, formattedPhone);
 
      // Update verification badge
      await updatePhoneVerificationBadge(supabase, user.id);
 
      return NextResponse.json({
        success: true,
        message: 'Phone number updated successfully',
        phone: formattedPhone,
        provider: 'twilio_verify',
      });
    }
 
    // Fallback: Use Supabase verifyOtp
    console.log('Using Supabase for phone update verification:', formattedPhone);
 
    const { error: verifyError } = await supabase.auth.verifyOtp({
      phone: formattedPhone,
      token,
      type: 'phone_change',
    });
 
    if (verifyError) {
      console.error('Phone update verification error:', verifyError);
      await incrementRateLimit(formattedPhone, 'phone');
      return NextResponse.json({ error: 'Invalid or expired OTP' }, { status: 401 });
    }
 
    // Clear rate limits
    await Promise.all([clearRateLimit(formattedPhone, 'phone'), clearRateLimit(ipHash, 'ip')]);
 
    // Sync phone to public.users table
    const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL;
    const serviceRoleKey = process.env.SUPABASE_SERVICE_ROLE_KEY;
    if (supabaseUrl && serviceRoleKey) {
      const adminClientForSync = createAdminClient(supabaseUrl, serviceRoleKey, {
        auth: { autoRefreshToken: false, persistSession: false },
      });
      await syncPhoneToPublicUsers(adminClientForSync, user.id, formattedPhone);
    }
 
    // Update verification badge
    await updatePhoneVerificationBadge(supabase, user.id);
 
    return NextResponse.json({
      success: true,
      message: 'Phone number updated successfully',
      phone: formattedPhone,
      provider: 'supabase',
    });
  } catch (error) {
    console.error('Phone update verification API error:', error);
    return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
  }
}
 
/**
 * Helper to sync phone to public.users table
 * This is needed because auth.users updates don't automatically sync to public.users
 */
// eslint-disable-next-line @typescript-eslint/no-explicit-any
async function syncPhoneToPublicUsers(adminClient: any, userId: string, phone: string) {
  try {
    const { error } = await adminClient.from('users').update({ phone }).eq('id', userId);
 
    if (error) {
      console.error('Failed to sync phone to public.users:', error);
    }
  } catch (error) {
    console.error('Error syncing phone to public.users:', error);
  }
}
 
/**
 * Helper to update phone verification badge
 */
async function updatePhoneVerificationBadge(
  supabase: Awaited<ReturnType<typeof createClient>>,
  userId: string
) {
  try {
    const { data: profile } = await supabase
      .from('profiles')
      .select('id')
      .eq('user_id', userId)
      .single();
 
    if (profile) {
      const { data: phoneVerificationType } = await supabase
        .from('verification_types')
        .select('id')
        .eq('code', 'phone')
        .single();
 
      if (phoneVerificationType) {
        await supabase.from('user_verifications').upsert(
          {
            user_id: userId,
            profile_id: profile.id,
            verification_type_id: phoneVerificationType.id,
            status: 'verified',
            verified_at: new Date().toISOString(),
            completed_at: new Date().toISOString(),
          },
          { onConflict: 'user_id,verification_type_id' }
        );
      }
    }
  } catch (error) {
    console.error('Failed to update phone verification badge:', error);
  }
}