2.1 KiB
Middleware Authentication Fix Summary
Problem
6 out of 12 e2e tests failing due to middleware not properly protecting routes.
Root Cause Analysis
Issue 1: Cookie Loss in Redirect Chain
When navigating to /sponsor, the page component does a server-side redirect('/sponsor/dashboard') which loses cookies in the redirect chain. This causes the second request to /sponsor/dashboard to have no cookies.
Evidence:
/sponsor - cookie header length: 50 ✓
/sponsor/dashboard - cookie header length: 0 ✗
Fix: Handle /sponsor → /sponsor/dashboard redirect in middleware to preserve cookies.
Issue 2: Auth Page Redirect Loop
When an authenticated user with insufficient permissions is redirected to /auth/login?returnTo=/sponsor/dashboard, the middleware immediately redirects them away from the login page because they're authenticated. This creates a conflict.
Fix: Allow authenticated users to access login pages if they have a returnTo parameter (indicating they were sent there due to insufficient permissions).
Issue 3: SessionGateway Cookie Handling
The SessionGateway.getSession() method was checking if (cookieHeader) which evaluates to false for empty strings, causing it to fall through to server component context even when called from middleware with an empty cookie header.
Fix: Check if (cookieHeader !== undefined) instead.
Changes Made
-
apps/website/lib/gateways/SessionGateway.ts
- Fixed cookie header check to use
!== undefinedinstead of truthy check
- Fixed cookie header check to use
-
apps/website/middleware.ts
- Added redirect from
/sponsorto/sponsor/dashboardin middleware - Added check for
returnToparameter in auth page logic - Added comprehensive logging
- Added redirect from
-
apps/website/app/sponsor/dashboard/page.tsx
- Added
export const dynamic = 'force-dynamic'(reverted - doesn't work with client components)
- Added
Test Results
Still failing - need to investigate further.
Next Steps
- Check if cookies are being set with correct domain
- Verify Playwright cookie handling in Docker environment
- Consider if the test expectations are correct