48 lines
1.5 KiB
TypeScript
48 lines
1.5 KiB
TypeScript
import { NextResponse } from 'next/server';
|
|
import type { NextRequest } from 'next/server';
|
|
|
|
const PUBLIC_PATHS = [
|
|
'/login',
|
|
'/api/auth',
|
|
'/api/backoffice/auth',
|
|
'/manifest.json',
|
|
'/manifest.webmanifest',
|
|
'/favicon.ico',
|
|
];
|
|
|
|
export function proxy(request: NextRequest) {
|
|
const { pathname } = request.nextUrl;
|
|
|
|
// Allow public paths (including PWA manifest, which Authelia was intercepting)
|
|
if (PUBLIC_PATHS.some((p) => pathname === p || pathname.startsWith(p + '/'))) {
|
|
return NextResponse.next();
|
|
}
|
|
|
|
// The identity backend issues the mdv_session cookie. Keep legacy names
|
|
// accepted during migration, but do not redirect valid current sessions.
|
|
const cookie = request.headers.get('cookie') ?? '';
|
|
const hasSession =
|
|
cookie.includes('mdv_session=') ||
|
|
cookie.includes('backoffice_session=') ||
|
|
cookie.includes('session_token=');
|
|
|
|
if (!hasSession) {
|
|
// API callers expect JSON. Redirecting them to /login makes fetch() follow
|
|
// the redirect and receive the HTML login page, which surfaces as the
|
|
// cryptic "Unexpected token '<'" parse error in the terminal UI.
|
|
if (pathname.startsWith('/api/')) {
|
|
return NextResponse.json(
|
|
{ error: { statusCode: 401, code: 'UNAUTHORIZED', message: 'Authentication required' } },
|
|
{ status: 401 },
|
|
);
|
|
}
|
|
return NextResponse.redirect(new URL('/login', request.url));
|
|
}
|
|
|
|
return NextResponse.next();
|
|
}
|
|
|
|
export const config = {
|
|
matcher: ['/((?!_next/static|_next/image|favicon.ico).*)'],
|
|
};
|