All files / app/auth/callback route.ts

37.03% Statements 100/270
78.78% Branches 26/33
100% Functions 1/1
37.03% Lines 100/270

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 3581x         1x   12x 12x 12x 12x 12x         12x   1x 1x 1x 1x 1x   12x 10x 10x   10x   9x 9x 9x   9x   8x 8x 8x 8x 8x     8x 1x 1x       7x 8x     8x 8x   8x 8x 8x 8x 8x 8x 8x   8x 6x 6x 6x 6x 6x 6x 6x   6x 6x 6x 6x   6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x   5x 5x 6x 6x   6x 5x 6x     6x 6x 1x 1x 8x 1x 1x     7x 7x 7x 7x 7x   8x 1x 1x     8x 8x 8x     1x 1x 10x     2x 2x   12x                                                                                                                                                                                                                                                                                                                                                                                                                                                   2x 2x  
import { NextResponse } from 'next/server';
import { createClient } from '@/lib/supabase/server';
import { createAdminClient } from '@/lib/supabase/admin';
 
// Force dynamic - never cache this route
export const dynamic = 'force-dynamic';
 
export async function GET(request: Request) {
  const { searchParams, origin } = new URL(request.url);
  const code = searchParams.get('code');
  const redirect = searchParams.get('redirect') || '/dashboard';
  const type = searchParams.get('type'); // Supabase sends type for email_change
 
  // Handle email change confirmations (first step of double confirmation)
  // When type=email_change but no code, it means user confirmed from old email
  // and needs to confirm from new email
  if (type === 'email_change' && !code) {
    // Redirect to login with the hash message preserved
    const message = encodeURIComponent(
      'Confirmation link accepted. Please proceed to confirm link sent to the other email'
    );
    return NextResponse.redirect(`${origin}/login#message=${message}`);
  }
 
  if (code) {
    const supabase = await createClient();
    const { error } = await supabase.auth.exchangeCodeForSession(code);
 
    if (!error) {
      // Check if user has completed onboarding
      const {
        data: { user },
      } = await supabase.auth.getUser();
 
      if (user) {
        // Check if user has a profile
        const { data: profile } = await supabase
          .from('profiles')
          .select('id')
          .eq('user_id', user.id)
          .single();
 
        // If no profile, redirect to onboarding
        if (!profile) {
          return NextResponse.redirect(`${origin}/onboarding`);
        }
 
        // Create email verification badge if email is confirmed AND it's a real email (not placeholder)
        // Use admin client to bypass RLS for badge creation
        const isRealEmail = user.email && !user.email.endsWith('@proofid.internal');
        let emailJustVerified = false;
 
        // Detect if user signed in via Google OAuth
        const authProvider = user.app_metadata?.provider || 'email';
        const isGoogleAuth = authProvider === 'google';
 
        console.log('[Auth Callback] Email verification check:', {
          email: user.email,
          email_confirmed_at: user.email_confirmed_at,
          isRealEmail,
          hasProfile: !!profile,
          authProvider,
        });
 
        if (user.email_confirmed_at && profile && isRealEmail) {
          try {
            const supabaseAdmin = createAdminClient();
            const { data: emailVerificationType, error: typeError } = await supabaseAdmin
              .from('verification_types')
              .select('id')
              .eq('code', 'email')
              .single();
 
            console.log('[Auth Callback] Verification type lookup:', {
              found: !!emailVerificationType,
              error: typeError?.message,
            });
 
            if (emailVerificationType) {
              const { error: upsertError } = await supabaseAdmin.from('user_verifications').upsert(
                {
                  user_id: user.id,
                  profile_id: profile.id,
                  verification_type_id: emailVerificationType.id,
                  status: 'verified',
                  verified_at: user.email_confirmed_at,
                  completed_at: user.email_confirmed_at,
                  meta: isGoogleAuth ? { provider: 'google' } : {},
                },
                {
                  onConflict: 'user_id,verification_type_id',
                }
              );
 
              console.log('[Auth Callback] Badge upsert result:', {
                success: !upsertError,
                error: upsertError?.message,
              });
 
              if (!upsertError) {
                emailJustVerified = true;
              } else {
                console.error('[Auth Callback] Badge upsert failed:', upsertError);
              }
            }
          } catch (badgeError) {
            console.error('[Auth Callback] Failed to create email verification badge:', badgeError);
          }
        } else {
          console.log('[Auth Callback] Skipping badge creation - conditions not met');
        }
 
        // Check onboarding status
        const { data: userData } = await supabase
          .from('users')
          .select('onboarding_status')
          .eq('id', user.id)
          .single();
 
        if (userData?.onboarding_status !== 'completed') {
          return NextResponse.redirect(`${origin}/onboarding`);
        }
 
        // Add email_verified param if email was just verified
        const redirectUrl = emailJustVerified ? `${redirect}?email_verified=true` : redirect;
        return NextResponse.redirect(`${origin}${redirectUrl}`);
      }
 
      // Successful auth, redirect to intended destination
      return NextResponse.redirect(`${origin}${redirect}`);
    }
  }
 
  // Check for token_hash which indicates email confirmation without code exchange
  const tokenHash = searchParams.get('token_hash');
  const tokenType = searchParams.get('type');
 
  if (tokenHash && tokenType) {
    // This is likely a Supabase email confirmation that uses token hash
    // Verify the token and redirect appropriately
    const supabase = await createClient();
    const { error } = await supabase.auth.verifyOtp({
      token_hash: tokenHash,
      type: tokenType as 'email' | 'email_change' | 'signup' | 'recovery' | 'invite',
    });
 
    console.log('[Auth Callback] verifyOtp result:', { error: error?.message, tokenType });
 
    if (!error) {
      // Successfully verified - check user state
      const {
        data: { user },
      } = await supabase.auth.getUser();
 
      const newEmail = (user as { new_email?: string })?.new_email;
      const isPlaceholderEmail = user?.email?.endsWith('@proofid.internal');
 
      console.log('[Auth Callback] User after verifyOtp:', {
        email: user?.email,
        new_email: newEmail,
        email_confirmed_at: user?.email_confirmed_at,
        isPlaceholder: isPlaceholderEmail,
        tokenType,
      });
 
      // For email_change: If user has placeholder email and new_email is pending,
      // complete the change via admin API (phone users can't confirm from placeholder)
      if (tokenType === 'email_change' && user && isPlaceholderEmail && newEmail) {
        try {
          const supabaseAdmin = createAdminClient();
 
          // Update user's email directly (they've confirmed ownership of new email)
          const { error: updateError } = await supabaseAdmin.auth.admin.updateUserById(user.id, {
            email: newEmail,
            email_confirm: true,
          });
 
          console.log('[Auth Callback] Admin email update (success path):', {
            success: !updateError,
            error: updateError?.message,
            newEmail,
          });
 
          if (!updateError) {
            // Create email verification badge
            const { data: profile } = await supabaseAdmin
              .from('profiles')
              .select('id')
              .eq('user_id', user.id)
              .single();
 
            if (profile) {
              const { data: emailVerificationType } = await supabaseAdmin
                .from('verification_types')
                .select('id')
                .eq('code', 'email')
                .single();
 
              if (emailVerificationType) {
                await supabaseAdmin.from('user_verifications').upsert(
                  {
                    user_id: user.id,
                    profile_id: profile.id,
                    verification_type_id: emailVerificationType.id,
                    status: 'verified',
                    verified_at: new Date().toISOString(),
                    completed_at: new Date().toISOString(),
                  },
                  {
                    onConflict: 'user_id,verification_type_id',
                  }
                );
              }
            }
 
            // Redirect to settings/verification/email with success
            return NextResponse.redirect(
              `${origin}/settings/verification/email?email_verified=true`
            );
          }
        } catch (adminError) {
          console.error('[Auth Callback] Admin email update failed:', adminError);
        }
      }
 
      if (user) {
        // Check if user has a profile
        const { data: profile } = await supabase
          .from('profiles')
          .select('id')
          .eq('user_id', user.id)
          .single();
 
        // Create email verification badge if email is confirmed AND it's a real email
        // Use admin client to bypass RLS for badge creation
        const isRealEmail = user.email && !user.email.endsWith('@proofid.internal');
        if (user.email_confirmed_at && profile && isRealEmail) {
          try {
            const supabaseAdmin = createAdminClient();
            const { data: emailVerificationType } = await supabaseAdmin
              .from('verification_types')
              .select('id')
              .eq('code', 'email')
              .single();
 
            if (emailVerificationType) {
              await supabaseAdmin.from('user_verifications').upsert(
                {
                  user_id: user.id,
                  profile_id: profile.id,
                  verification_type_id: emailVerificationType.id,
                  status: 'verified',
                  verified_at: user.email_confirmed_at,
                  completed_at: user.email_confirmed_at,
                },
                {
                  onConflict: 'user_id,verification_type_id',
                }
              );
            }
          } catch (badgeError) {
            console.error('Failed to create email verification badge:', badgeError);
          }
        }
      }
 
      // Redirect to dashboard with success message
      return NextResponse.redirect(`${origin}${redirect}?email_verified=true`);
    }
 
    // If it's email_change type and verifyOtp failed, check if this is first step of double confirmation
    // For phone-based users with placeholder emails, we need to complete the change using admin API
    if (tokenType === 'email_change') {
      const supabase = await createClient();
      const {
        data: { user },
      } = await supabase.auth.getUser();
 
      console.log('[Auth Callback] Email change - checking user state:', {
        email: user?.email,
        new_email: (user as { new_email?: string })?.new_email,
        isPlaceholder: user?.email?.endsWith('@proofid.internal'),
      });
 
      // Check if user has a placeholder email and a pending new_email
      const newEmail = (user as { new_email?: string })?.new_email;
      const isPlaceholderEmail = user?.email?.endsWith('@proofid.internal');
 
      if (user && isPlaceholderEmail && newEmail) {
        // Phone-based user trying to add real email - complete the change via admin API
        // since the placeholder email can't receive confirmation
        try {
          const supabaseAdmin = createAdminClient();
 
          // Update user's email directly (they've confirmed ownership of new email)
          const { error: updateError } = await supabaseAdmin.auth.admin.updateUserById(user.id, {
            email: newEmail,
            email_confirm: true,
          });
 
          console.log('[Auth Callback] Admin email update result:', {
            success: !updateError,
            error: updateError?.message,
            newEmail,
          });
 
          if (!updateError) {
            // Create email verification badge
            const { data: profile } = await supabaseAdmin
              .from('profiles')
              .select('id')
              .eq('user_id', user.id)
              .single();
 
            if (profile) {
              const { data: emailVerificationType } = await supabaseAdmin
                .from('verification_types')
                .select('id')
                .eq('code', 'email')
                .single();
 
              if (emailVerificationType) {
                await supabaseAdmin.from('user_verifications').upsert(
                  {
                    user_id: user.id,
                    profile_id: profile.id,
                    verification_type_id: emailVerificationType.id,
                    status: 'verified',
                    verified_at: new Date().toISOString(),
                    completed_at: new Date().toISOString(),
                  },
                  {
                    onConflict: 'user_id,verification_type_id',
                  }
                );
              }
            }
 
            // Redirect to dashboard with success
            return NextResponse.redirect(`${origin}${redirect}?email_verified=true`);
          }
        } catch (adminError) {
          console.error('[Auth Callback] Admin email update failed:', adminError);
        }
      }
 
      // Normal double-opt-in flow - user needs to confirm from other email
      const message = encodeURIComponent(
        'Confirmation link accepted. Please check your new email for the final confirmation link.'
      );
      return NextResponse.redirect(`${origin}/login#message=${message}`);
    }
  }
 
  // No code or token_hash - redirect to login without error (might be incomplete flow)
  return NextResponse.redirect(`${origin}/login`);
}