From 5e7c1bb0b76e254c63e4425c9d00c4074ad72771 Mon Sep 17 00:00:00 2001 From: GitHub Copilot Date: Wed, 18 Feb 2026 16:29:22 +0000 Subject: [PATCH] Fix billing user status bug: users with credits no longer incorrectly shown as inactive This fix addresses a critical bug where users who have been issued credits were showing as inactive and unable to log in. Changes: - Modified 402 (Payment Required) handling in middleware to check if user has active credits (input_tokens > 0 or output_tokens > 0 or is_active === true) before redirecting to subscribe page - Added safe property access using optional chaining for customer_session to prevent runtime errors when response structure differs - Users with active credits will no longer be incorrectly redirected to the subscribe page The root cause was that the middleware was redirecting ALL 402 responses to the subscribe page without checking if the user actually had active credits. Additionally, the code assumed responseJSON.detail.customer_session always existed, which could cause runtime errors. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- middleware.tsx | 21 ++++++++++++--------- 1 file changed, 12 insertions(+), 9 deletions(-) diff --git a/middleware.tsx b/middleware.tsx index 74efe2a..4f92804 100644 --- a/middleware.tsx +++ b/middleware.tsx @@ -193,19 +193,22 @@ export const useAuth: MiddlewareHook = async (req) => { `${response.status === 401 ? 'Unauthorized' : 'Forbidden'} access, status ${response.status}, detail ${responseJSON.detail}. Clearing JWT and redirecting to auth.`, ); } else if (response.status === 402) { - // Payment Required - if (!requestedURI.startsWith(`${authWeb}/subscribe`)) { + // Payment Required - Only redirect if user doesn't have active credits + // Check if user has credits (input_tokens or output_tokens > 0) - if so, they should be considered active + const hasActiveCredits = + responseJSON.detail?.input_tokens > 0 || + responseJSON.detail?.output_tokens > 0 || + responseJSON.detail?.is_active === true; + + if (!hasActiveCredits && !requestedURI.startsWith(`${authWeb}/subscribe`)) { + // Safely access customer_session - it may not always be present + const clientSecret = responseJSON.detail?.customer_session?.client_secret; toReturn.response = NextResponse.redirect( - new URL( - `${authWeb}/subscribe${ - responseJSON.detail.customer_session.client_secret - ? '?customer_session=' + responseJSON.detail.customer_session.client_secret - : '' - }`, - ), + new URL(`${authWeb}/subscribe${clientSecret ? '?customer_session=' + clientSecret : ''}`), ); toReturn.activated = true; } + // If user has active credits, don't redirect - let them proceed (treat as 200) } else if (response.status === 502) { const cookieArray = [generateCookieString('href', requestedURI, (86400).toString())]; toReturn.activated = true;