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

95.2% Statements 318/334
84.5% Branches 60/71
100% Functions 5/5
95.2% Lines 318/334

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 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 4671x                 9x 9x 9x   9x       9x 9x 9x 9x 9x 9x 9x         9x 9x 9x 9x   9x 9x   9x   9x 9x     9x 9x 9x 9x 9x 9x   9x 1x 1x 1x 1x 1x 1x 1x 1x 5x 5x 5x 5x 9x 3x 3x 3x 9x       8x 8x 8x 8x   8x 8x 8x 8x 8x   8x         8x 8x   8x   3x 3x 3x 3x 3x     4x 4x 4x       4x 4x           2x 2x 2x 2x 2x       2x 2x   2x           2x 2x 2x 2x   2x 1x 1x 1x 2x 2x       1x 1x   23x 23x 23x 23x   23x 2x 2x   23x 2x 2x   19x     19x 19x   19x   23x 1x 1x 1x 1x 1x 1x 1x 1x     23x 10x   10x   10x 1x 1x 1x 1x 1x 1x 1x   1x 1x 1x 1x 1x       9x   9x 9x     9x     10x 4x 4x 4x 4x 4x 4x   4x   2x 2x     2x   2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x   1x 2x     2x 2x 2x 2x 4x   4x 1x 1x 1x 1x 1x 1x 1x 1x 4x       10x       10x       10x   10x 10x 10x 10x 10x 10x 10x 10x       10x       10x 10x 10x     10x 6x 6x 6x   7x 7x   10x 1x   1x 1x 1x 1x 1x 1x 1x 1x 1x 1x   10x 4x 4x     10x     10x     4x     4x   4x   4x 4x 4x 4x 4x 4x 4x   4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 10x 3x   3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 10x     7x   7x   7x 7x 7x 7x 7x   23x 1x     1x     1x   1x 1x 1x 1x 1x   23x 1x 1x 1x 1x 1x     5x     5x     5x   5x 5x 5x 5x 5x 5x 5x 5x 5x 23x 23x 23x 23x 23x 1x 1x 1x 23x         9x 9x 9x   9x 9x 9x 9x 9x   9x 8x 8x 8x 8x 8x   8x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 8x 9x       9x  
import { NextRequest, NextResponse } from 'next/server';
import { createClient } from '@/lib/supabase/server';
import { createClient as createAdminClient, User } from '@supabase/supabase-js';
import { formatPhoneNumber } from '@/lib/auth/otp';
import { checkRateLimit, incrementRateLimit, clearRateLimit } from '@/lib/auth/rate-limit';
import { logSuccessfulLogin, logFailedLogin, getClientInfo, hashIP } from '@/lib/auth/login-events';
import { checkVerificationCode, isTwilioConfigured } from '@/lib/twilio/verify';
 
// Create admin client for user management after Twilio verification
function getAdminClient() {
  const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL;
  const serviceRoleKey = process.env.SUPABASE_SERVICE_ROLE_KEY;
 
  if (!supabaseUrl || !serviceRoleKey) {
    throw new Error('Supabase admin credentials not configured');
  }
 
  return createAdminClient(supabaseUrl, serviceRoleKey, {
    auth: {
      autoRefreshToken: false,
      persistSession: false,
    },
  });
}
 
/**
 * Find existing user by phone number using multiple strategies
 */
async function findUserByPhone(
  adminClient: ReturnType<typeof getAdminClient>,
  formattedPhone: string
): Promise<User | null> {
  // Try multiple phone format variations
  const phoneVariations = [
    formattedPhone,
    // Without + prefix
    formattedPhone.replace('+', ''),
    // With spaces removed
    formattedPhone.replace(/\s/g, ''),
  ];
 
  // Strategy 1: Use RPC function (most reliable if migration is applied)
  for (const phoneVariant of phoneVariations) {
    try {
      console.log('Attempting to find user via RPC for phone:', phoneVariant);
      const { data: userId, error: rpcError } = await adminClient.rpc('get_user_by_phone', {
        phone_number: phoneVariant,
      });
 
      if (!rpcError && userId) {
        console.log('RPC returned user ID:', userId);
        const { data: userData, error: getUserError } =
          await adminClient.auth.admin.getUserById(userId);
        if (!getUserError && userData?.user) {
          console.log('Found user via RPC:', userData.user.id);
          return userData.user;
        }
      }
      if (rpcError) {
        console.log('RPC error (function may not exist):', rpcError.message);
        break; // RPC function doesn't exist, no point trying other variations
      }
    } catch (rpcErr) {
      console.log('RPC call failed:', rpcErr);
      break;
    }
  }
 
  // Strategy 2: Paginated search through all users
  // This is a fallback when RPC is not available
  console.log('RPC not available or failed, searching via listUsers...');
  let page = 1;
  const perPage = 1000; // Use larger page size for efficiency
  const maxPages = 20; // Limit to prevent infinite loops
 
  while (page <= maxPages) {
    const { data, error } = await adminClient.auth.admin.listUsers({
      page,
      perPage,
    });
 
    if (error) {
      console.error('Error listing users:', error);
      break;
    }
 
    const users = data?.users || [];
    console.log(`Page ${page}: checking ${users.length} users`);
 
    for (const u of users) {
      // Check against all phone variations
      if (u.phone && phoneVariations.some((pv) => u.phone === pv)) {
        console.log('Found user via listUsers:', u.id);
        return u;
      }
    }
 
    // If we got fewer users than requested, we've reached the end
    if (users.length < perPage) {
      break;
    }
    page++;
  }
 
  return null;
}
 
/**
 * Fallback: Find user by phone via profiles table
 * This is used when direct auth lookup fails but we know the phone exists
 */
async function findUserByPhoneViaProfiles(
  adminClient: ReturnType<typeof getAdminClient>,
  formattedPhone: string
): Promise<User | null> {
  console.log('Attempting fallback: finding user via profiles for phone:', formattedPhone);
 
  // Query the database directly to find user_id from auth.users
  // Using the admin client's raw SQL capability
  try {
    const { data, error } = await adminClient.from('profiles').select('user_id').limit(1000);
 
    if (error) {
      console.error('Error querying profiles:', error);
      return null;
    }
 
    // For each profile, get the user and check their phone
    for (const profile of data || []) {
      const { data: userData, error: getUserError } = await adminClient.auth.admin.getUserById(
        profile.user_id
      );
 
      if (!getUserError && userData?.user?.phone === formattedPhone) {
        console.log('Found user via profiles fallback:', userData.user.id);
        return userData.user;
      }
    }
  } catch (err) {
    console.error('Profiles fallback failed:', err);
  }
 
  return null;
}
 
export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const { phone, token, countryCode = '+91' } = body;
 
    if (!phone || !token) {
      return NextResponse.json({ error: 'Phone and OTP code 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 verification attempts. Please request a new OTP.',
          blocked_until: rateLimitResult.blocked_until,
        },
        { status: 429 }
      );
    }
 
    // Use direct Twilio Verify if configured
    if (isTwilioConfigured()) {
      console.log('Using direct Twilio Verify for verification:', formattedPhone);
 
      const twilioResult = await checkVerificationCode(formattedPhone, token);
 
      if (!twilioResult.success || !twilioResult.valid) {
        await incrementRateLimit(formattedPhone, 'phone');
        await logFailedLogin(
          null,
          'phone_otp',
          request.headers,
          twilioResult.error || 'Invalid OTP'
        );
 
        return NextResponse.json(
          { error: twilioResult.error || 'Invalid or expired OTP' },
          { status: 401 }
        );
      }
 
      // OTP verified successfully via Twilio
      // Now we need to create/get user in Supabase and establish session
      console.log('Twilio OTP verified, finding or creating user...');
 
      try {
        const adminClient = getAdminClient();
 
        // Step 1: Check if user already exists with this phone
        let user = await findUserByPhone(adminClient, formattedPhone);
 
        // Step 2: If no existing user, create a new one
        if (!user) {
          console.log('No existing user found, creating new user for phone:', formattedPhone);
          const { data: newUser, error: createError } = await adminClient.auth.admin.createUser({
            phone: formattedPhone,
            phone_confirm: true,
            email_confirm: false,
          });
 
          if (createError) {
            // If phone_exists error, try fallback lookup via profiles
            if (createError.code === 'phone_exists') {
              console.log('Phone exists error - trying fallback lookup via profiles...');
 
              // Try the profiles-based fallback
              user = await findUserByPhoneViaProfiles(adminClient, formattedPhone);
 
              if (!user) {
                console.error(
                  'CRITICAL: Phone exists but all lookup methods failed. Data integrity issue.'
                );
                return NextResponse.json(
                  {
                    error:
                      'Unable to complete login. Please try again or contact support if the issue persists.',
                    code: 'USER_LOOKUP_FAILED',
                  },
                  { status: 500 }
                );
              }
 
              console.log('Found user via fallback:', user.id);
            } else {
              throw createError;
            }
          } else {
            user = newUser.user;
            console.log('Created new user:', user.id);
          }
        } else {
          // Confirm phone if not already confirmed
          if (!user.phone_confirmed_at) {
            console.log('Confirming phone for existing user:', user.id);
            const { data: updatedUser } = await adminClient.auth.admin.updateUserById(user.id, {
              phone_confirm: true,
            });
            if (updatedUser?.user) {
              user = updatedUser.user;
            }
          }
        }
 
        // Step 3: Set up credentials for session creation
        // For phone-only users, set up email and password for session creation
        const hasRealEmail = !!(user.email && !user.email.endsWith('@proofid.internal'));
 
        // Generate a unique password for this session that meets Supabase requirements:
        // Must contain lowercase, uppercase, and numbers
        const sessionPassword = `PhoneSession${Date.now()}X${crypto.randomUUID().toUpperCase()}`;
 
        // For users with real emails, we need to use their existing email
        // For phone-only users, we create a placeholder email
        const sessionEmail = hasRealEmail ? user.email! : `phone_${user.id}@proofid.internal`;
 
        console.log(
          'Setting up user for session creation:',
          user.id,
          'hasRealEmail:',
          hasRealEmail,
          'sessionEmail:',
          sessionEmail
        );
 
        // Update user with the session password
        // We set the email only if user doesn't have a real email
        const updatePayload: {
          password: string;
          email?: string;
          email_confirm?: boolean;
        } = {
          password: sessionPassword,
        };
 
        // Only set email for phone-only users
        if (!hasRealEmail) {
          updatePayload.email = sessionEmail;
          updatePayload.email_confirm = true; // Confirm placeholder email so signIn works
        }
 
        const { data: updatedUser, error: updateError } =
          await adminClient.auth.admin.updateUserById(user.id, updatePayload);
 
        if (updateError) {
          console.error('Error updating user for session:', updateError);
          // Return a more specific error for debugging
          return NextResponse.json({
            success: true,
            verification: {
              verified: true,
              phone: formattedPhone,
            },
            sessionError: `Phone verified but session setup failed: ${updateError.message}`,
            provider: 'twilio_verify',
          });
        }
 
        if (updatedUser?.user) {
          user = updatedUser.user;
        }
 
        // Use the correct email for session (the one actually set on the user)
        const finalEmail = user.email || sessionEmail;
 
        // Clear rate limits on success
        await Promise.all([clearRateLimit(formattedPhone, 'phone'), clearRateLimit(ipHash, 'ip')]);
 
        // Log successful login
        await logSuccessfulLogin(user.id, 'phone_otp', request.headers);
 
        // Create phone verification badge
        await createPhoneVerificationBadge(user.id, formattedPhone);
 
        console.log('Twilio verification complete, returning session credentials');
 
        return NextResponse.json({
          success: true,
          user: {
            id: user.id,
            phone: user.phone,
            email: finalEmail,
          },
          // Include credentials for client-side session creation
          sessionCredentials: {
            email: finalEmail,
            password: sessionPassword,
          },
          verification: {
            verified: true,
            phone: formattedPhone,
          },
          provider: 'twilio_verify',
        });
      } catch (adminError) {
        console.error('Admin operation failed:', adminError);
        // Still return success for OTP verification, but indicate session creation failed
        return NextResponse.json({
          success: true,
          verification: {
            verified: true,
            phone: formattedPhone,
          },
          sessionError: 'Phone verified but automatic login failed. Please try signing in again.',
          provider: 'twilio_verify',
        });
      }
    }
 
    // Fallback to Supabase Auth (if Twilio not configured)
    console.log('Using Supabase Auth for OTP verification:', formattedPhone);
 
    const supabase = await createClient();
 
    const { data, error } = await supabase.auth.verifyOtp({
      phone: formattedPhone,
      token,
      type: 'sms',
    });
 
    if (error) {
      console.error('OTP verification error:', error);
 
      // Increment rate limit on failure
      await incrementRateLimit(formattedPhone, 'phone');
 
      // Log failed attempt
      await logFailedLogin(null, 'phone_otp', request.headers, error.message);
 
      return NextResponse.json(
        { error: 'Invalid or expired OTP. Please try again.' },
        { status: 401 }
      );
    }
 
    if (!data.user) {
      return NextResponse.json(
        { error: 'Verification failed. Please try again.' },
        { status: 401 }
      );
    }
 
    // Clear rate limits on success
    await Promise.all([clearRateLimit(formattedPhone, 'phone'), clearRateLimit(ipHash, 'ip')]);
 
    // Log successful login
    await logSuccessfulLogin(data.user.id, 'phone_otp', request.headers);
 
    // Create phone verification badge
    await createPhoneVerificationBadge(data.user.id, formattedPhone);
 
    return NextResponse.json({
      success: true,
      user: {
        id: data.user.id,
        phone: data.user.phone,
        email: data.user.email,
      },
      session: {
        access_token: data.session?.access_token,
        refresh_token: data.session?.refresh_token,
      },
      provider: 'supabase',
    });
  } catch (error) {
    console.error('Verify OTP API error:', error);
    return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
  }
}
 
/**
 * Helper to create phone verification badge for user
 */
async function createPhoneVerificationBadge(userId: string, _phone: string) {
  try {
    const supabase = await createClient();
 
    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 (badgeError) {
    // Don't fail the verification if badge creation fails
    console.error('Failed to create phone verification badge:', badgeError);
  }
}