-
Couldn't load subscription status.
- Fork 48
refactor: extract and reuse helpers in api #82
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
mkczarkowski
wants to merge
1
commit into
master
Choose a base branch
from
extract-api-utils
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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( | ||
| '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 }); | ||
| }, | ||
| ), | ||
| ); | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
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()insrc/pages/api/utils/to: