From 3680285cd9a366390a7a29dbb9d2b4f70a056b55 Mon Sep 17 00:00:00 2001 From: Nate Kelley Date: Tue, 22 Jul 2025 10:39:53 -0600 Subject: [PATCH] fix duplicate redirect logic --- apps/web/src/middleware/assetReroutes.ts | 31 +++++++++++++++--------- 1 file changed, 20 insertions(+), 11 deletions(-) diff --git a/apps/web/src/middleware/assetReroutes.ts b/apps/web/src/middleware/assetReroutes.ts index 5bb39a8dc..f34a790ba 100644 --- a/apps/web/src/middleware/assetReroutes.ts +++ b/apps/web/src/middleware/assetReroutes.ts @@ -8,28 +8,37 @@ import { isShareableAssetPage } from '@/routes/busterRoutes'; +/** + * Creates a login redirect URL with the current page as the 'next' parameter + */ +const createLoginRedirect = (request: NextRequest): NextResponse => { + const originalUrl = `${request.nextUrl.pathname}${request.nextUrl.search}`; + const loginUrl = new URL(createBusterRoute({ route: BusterRoutes.AUTH_LOGIN }), request.url); + loginUrl.searchParams.set('next', encodeURIComponent(originalUrl)); + return NextResponse.redirect(loginUrl); +}; + export const assetReroutes = async ( request: NextRequest, response: NextResponse, user: User | null ) => { const userExists = !!user && !!user.id; + + // If user doesn't exist and page requires authentication if (!userExists && !isPublicPage(request)) { - const originalUrl = `${request.nextUrl.pathname}${request.nextUrl.search}`; - const loginUrl = new URL(createBusterRoute({ route: BusterRoutes.AUTH_LOGIN }), request.url); - loginUrl.searchParams.set('next', encodeURIComponent(originalUrl)); - return NextResponse.redirect(loginUrl); + return createLoginRedirect(request); } + // If user doesn't exist and it's a shareable asset page if (!userExists && isShareableAssetPage(request)) { - const redirect = getEmbedAssetRedirect(request); - if (redirect) { - return NextResponse.redirect(new URL(redirect, request.url)); + // Try to get embed asset redirect first + const embedRedirect = getEmbedAssetRedirect(request); + if (embedRedirect) { + return NextResponse.redirect(new URL(embedRedirect, request.url)); } - const originalUrl = `${request.nextUrl.pathname}${request.nextUrl.search}`; - const loginUrl = new URL(createBusterRoute({ route: BusterRoutes.AUTH_LOGIN }), request.url); - loginUrl.searchParams.set('next', encodeURIComponent(originalUrl)); - return NextResponse.redirect(loginUrl); + // Fall back to login redirect + return createLoginRedirect(request); } return response;