Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
204 changes: 86 additions & 118 deletions src/pages/api/auth/login.ts
Original file line number Diff line number Diff line change
@@ -1,128 +1,96 @@
import type { APIRoute } from 'astro';
import { isFeatureEnabled } from '@/features/featureFlags';
import { createSupabaseServerInstance } from '@/db/supabase.client';
import { verifyCaptcha } from '@/services/captcha';
import { CF_CAPTCHA_SECRET_KEY } from 'astro:env/server';

export const POST: APIRoute = async ({ request, cookies }) => {
// Check if auth feature is enabled
if (!isFeatureEnabled('auth')) {
return new Response(JSON.stringify({ error: 'Authentication is currently disabled' }), {
status: 403,
});
}

try {
const { email, password, captchaToken } = (await request.json()) as {
email: string;
password: string;
captchaToken: string;
};

if (!email || !password || !captchaToken) {
return new Response(
JSON.stringify({ error: 'Email, password, and captcha token are required' }),
{
status: 400,
},
);
}

// Verify captcha on backend
const requestorIp = request.headers.get('cf-connecting-ip') || '';
const captchaResult = await verifyCaptcha(CF_CAPTCHA_SECRET_KEY, captchaToken, requestorIp);

if (!captchaResult.success) {
return new Response(
JSON.stringify({
error: 'Security verification failed. Please try again.',
errorCodes: captchaResult['error-codes'],
}),
{ status: 400 },
);
}

const supabase = createSupabaseServerInstance({ cookies, headers: request.headers });

const { data, error } = await supabase.auth.signInWithPassword({
email,
password,
});

if (error) {
// Check if error is due to unconfirmed email
if (error.message.toLowerCase().includes('email not confirmed')) {
// Auto-resend verification email
const requestorIp = request.headers.get('cf-connecting-ip') || '';

// Check rate limit first
const { data: rateLimitResult, error: rateLimitError } = await supabase.rpc(
'check_and_log_verification_request',
{
p_email: email.toLowerCase(),
p_ip_address: requestorIp,
},
);
import { withFeatureFlag } from '../guards/withFeatureFlag';
import { withCaptcha } from '../guards/withCaptcha';
import { successResponse, errorResponse, validationError } from '../utils/apiResponse';
import { createServerClient, getClientIp, getOrigin } from '../utils/supabaseHelpers';

export const POST: APIRoute = withFeatureFlag(
'auth',
withCaptcha<{ email: string; password: string; captchaToken: string }>(
async ({ body, request, cookies }) => {
const { email, password } = body;

if (!email || !password) {
return validationError('Email and password are required');
}

if (rateLimitError) {
console.error('Rate limit check error:', rateLimitError);
return new Response(
JSON.stringify({
error:
'Your email address has not been verified. Please check your email or request a new verification link.',
type: 'email_not_confirmed',
email: email,
}),
{ status: 400 },
const supabase = createServerClient({ cookies, headers: request.headers });

const { data, error } = await supabase.auth.signInWithPassword({
email,
password,
});

if (error) {
// Check if error is due to unconfirmed email
if (error.message.toLowerCase().includes('email not confirmed')) {
// Auto-resend verification email
const requestorIp = getClientIp(request);

// Check rate limit first
const { data: rateLimitResult, error: rateLimitCheckError } = await supabase.rpc(
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Quality: Excellent error handling! The automatic verification email resend logic when login fails due to unconfirmed email is a great UX improvement. However, this logic is quite complex (60+ lines).

Recommendation: Consider extracting this into a reusable helper function like handleUnconfirmedEmail() in src/pages/api/utils/ to:

  1. Reduce complexity in the route handler
  2. Allow reuse if other endpoints need similar logic
  3. Make unit testing easier

'check_and_log_verification_request',
{
p_email: email.toLowerCase(),
p_ip_address: requestorIp,
},
);
}

// Check if rate limited
if (rateLimitResult && !rateLimitResult.allowed) {
const retryAfter = rateLimitResult.retry_after || 3600;
const minutes = Math.ceil(retryAfter / 60);

return new Response(
JSON.stringify({
error: `Your email is not verified. We've already sent verification emails recently. You can request another email in ${minutes} minute${minutes > 1 ? 's' : ''}.`,
type: 'email_not_confirmed_rate_limited',
if (rateLimitCheckError) {
console.error('Rate limit check error:', rateLimitCheckError);
return errorResponse(
'Your email address has not been verified. Please check your email or request a new verification link.',
400,
{
type: 'email_not_confirmed',
email: email,
},
);
}

// Check if rate limited
if (rateLimitResult && !rateLimitResult.allowed) {
const retryAfter = rateLimitResult.retry_after || 3600;
const minutes = Math.ceil(retryAfter / 60);

return errorResponse(
`Your email is not verified. We've already sent verification emails recently. You can request another email in ${minutes} minute${minutes > 1 ? 's' : ''}.`,
400,
{
type: 'email_not_confirmed_rate_limited',
email: email,
retryAfter: retryAfter,
},
);
}

// Send verification email
const { error: resendError } = await supabase.auth.resend({
type: 'signup',
email: email.toLowerCase(),
options: {
emailRedirectTo: `${getOrigin(request)}/auth/login`,
},
});

if (resendError) {
console.error('Error resending verification email:', resendError);
}

return errorResponse(
'Your email address has not been verified. We sent you a verification email - please check your inbox.',
400,
{
type: 'email_not_confirmed',
email: email,
retryAfter: retryAfter,
}),
{ status: 400 },
},
);
}

// Send verification email
const { error: resendError } = await supabase.auth.resend({
type: 'signup',
email: email.toLowerCase(),
options: {
emailRedirectTo: `${new URL(request.url).origin}/auth/login`,
},
});

if (resendError) {
console.error('Error resending verification email:', resendError);
}

return new Response(
JSON.stringify({
error:
'Your email address has not been verified. We sent you a verification email - please check your inbox.',
type: 'email_not_confirmed',
email: email,
}),
{ status: 400 },
);
return errorResponse(error.message, 400);
}

return new Response(JSON.stringify({ error: error.message }), { status: 400 });
}

return new Response(JSON.stringify({ user: data.user }), { status: 200 });
} catch (err) {
console.error('Login error:', err);
return new Response(JSON.stringify({ error: 'An unexpected error occurred' }), { status: 500 });
}
};
return successResponse({ user: data.user });
},
),
);
Loading