Skip to content

Commit 5e7c1bb

Browse files
GitHub CopilotCopilot
andcommitted
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>
1 parent e282124 commit 5e7c1bb

File tree

1 file changed

+12
-9
lines changed

1 file changed

+12
-9
lines changed

middleware.tsx

Lines changed: 12 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -193,19 +193,22 @@ export const useAuth: MiddlewareHook = async (req) => {
193193
`${response.status === 401 ? 'Unauthorized' : 'Forbidden'} access, status ${response.status}, detail ${responseJSON.detail}. Clearing JWT and redirecting to auth.`,
194194
);
195195
} else if (response.status === 402) {
196-
// Payment Required
197-
if (!requestedURI.startsWith(`${authWeb}/subscribe`)) {
196+
// Payment Required - Only redirect if user doesn't have active credits
197+
// Check if user has credits (input_tokens or output_tokens > 0) - if so, they should be considered active
198+
const hasActiveCredits =
199+
responseJSON.detail?.input_tokens > 0 ||
200+
responseJSON.detail?.output_tokens > 0 ||
201+
responseJSON.detail?.is_active === true;
202+
203+
if (!hasActiveCredits && !requestedURI.startsWith(`${authWeb}/subscribe`)) {
204+
// Safely access customer_session - it may not always be present
205+
const clientSecret = responseJSON.detail?.customer_session?.client_secret;
198206
toReturn.response = NextResponse.redirect(
199-
new URL(
200-
`${authWeb}/subscribe${
201-
responseJSON.detail.customer_session.client_secret
202-
? '?customer_session=' + responseJSON.detail.customer_session.client_secret
203-
: ''
204-
}`,
205-
),
207+
new URL(`${authWeb}/subscribe${clientSecret ? '?customer_session=' + clientSecret : ''}`),
206208
);
207209
toReturn.activated = true;
208210
}
211+
// If user has active credits, don't redirect - let them proceed (treat as 200)
209212
} else if (response.status === 502) {
210213
const cookieArray = [generateCookieString('href', requestedURI, (86400).toString())];
211214
toReturn.activated = true;

0 commit comments

Comments
 (0)