Skip to content
Merged
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
10 changes: 10 additions & 0 deletions app/api/webhooks/polar/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { PolarService } from '@/app/api/_lib/polar/services/polar.service';
import { SubscriptionService } from '@/app/api/_lib/polar/services/subscription.service';
import { PolarWebhookProcessorService } from '@/app/api/_lib/polar/services/polar-webhook-processor.service';
import { getNextCorsHeaders } from '@/lib/utils/next-cors';
import { invalidateUserAuthCache } from '@/lib/auth/cache-invalidation';

/**
* API Route para webhooks de Polar
Expand Down Expand Up @@ -108,6 +109,15 @@ async function processSubscriptionEvent(subscriptionId: string, payloadData?: an

if (result.success) {
console.log(`Successfully processed subscription ${subscriptionId}:`, result.message);

// Invalidar cache de autenticación del usuario para asegurar datos actualizados
// Esto es crítico para que el middleware obtenga el plan correcto inmediatamente
if (result.userId) {
console.log(`Invalidating auth cache for user: ${result.userId} (plan: ${result.plan})`);
invalidateUserAuthCache(result.userId);
} else {
console.warn(`No userId found in subscription result for ${subscriptionId}`);
}
} else {
console.error(`Failed to process subscription ${subscriptionId}:`, result.message);
}
Expand Down
47 changes: 47 additions & 0 deletions lib/auth/cache-invalidation.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
/*
* Copyright 2025 Fasttify LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import { invalidateUserCache } from '@/middlewares/auth/auth';

/**
* Invalida el cache de autenticación cuando se actualiza el plan del usuario
*
* @param userId - ID del usuario cuyo cache debe ser invalidado
*
* @example
* // Cuando se actualiza el plan del usuario
* await updateUserPlan(userId, 'Royal');
* invalidateUserCache(userId);
*
* // Cuando se cambia el tipo de usuario
* await updateUserType(userId, 'store_owner');
* invalidateUserCache(userId);
*/
export function invalidateUserAuthCache(userId: string): void {
console.log(`Invalidating auth cache for user: ${userId}`);
invalidateUserCache(userId);
}

/**
* Invalida el cache de múltiples usuarios
*
* @param userIds - Array de IDs de usuarios
*/
export function invalidateMultipleUsersCache(userIds: string[]): void {
console.log(`Invalidating auth cache for ${userIds.length} users`);
userIds.forEach((userId) => {
invalidateUserCache(userId);
});
}
120 changes: 0 additions & 120 deletions lib/debug/auth-debug.ts

This file was deleted.

19 changes: 0 additions & 19 deletions middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -348,15 +348,7 @@ async function handleLoginRedirect(
request: NextRequest,
next: () => Promise<NextResponse | null>
): Promise<NextResponse | null> {
const isProduction = process.env.NODE_ENV === 'production';

if (request.nextUrl.pathname === PROTECTED_ROUTES.LOGIN) {
if (isProduction) {
console.log('Login redirect handler called:', {
path: request.nextUrl.pathname,
timestamp: new Date().toISOString(),
});
}
return await handleAuthenticatedRedirectMiddleware(request, NextResponse.next());
}

Expand Down Expand Up @@ -402,17 +394,6 @@ async function executeHandlers(
* @returns Respuesta procesada por los middlewares
*/
export async function middleware(request: NextRequest): Promise<NextResponse> {
const isProduction = process.env.NODE_ENV === 'production';

// Log de entrada del middleware principal
if (isProduction) {
console.log('Main middleware called:', {
path: request.nextUrl.pathname,
method: request.method,
timestamp: new Date().toISOString(),
});
}

// Definir la cadena de handlers en orden de ejecución
const handlers: MiddlewareHandler[] = [
handleOAuthProtection,
Expand Down
Loading