Files
logbuch/middleware.ts
T
admin 1f70940dce fix: Middleware aktiviert — proxy.ts → middleware.ts
proxy.ts wurde nie als Next.js-Middleware erkannt (falscher Dateiname,
falscher Exportname). Die mustChangePassword-Weiterleitung und der
Login-Guard liefen daher nie. Zusätzlich Fallback-Secret entfernt.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-01 16:07:21 +02:00

57 lines
1.7 KiB
TypeScript

import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
import { jwtVerify } from 'jose';
const SESSION_COOKIE_NAME = 'logbuch_session';
const secretKey = process.env.AUTH_SECRET;
if (!secretKey) throw new Error('AUTH_SECRET Umgebungsvariable ist nicht gesetzt!');
const key = new TextEncoder().encode(secretKey);
export async function middleware(request: NextRequest) {
const { pathname } = request.nextUrl;
if (pathname.startsWith('/login') || pathname.startsWith('/_next') || pathname.startsWith('/favicon')) {
return NextResponse.next();
}
// Allow the statistik grafik proxy route to be called without an app session cookie
if (pathname.startsWith('/api/statistik/grafik')) {
return NextResponse.next();
}
const cookie = request.cookies.get(SESSION_COOKIE_NAME);
if (!cookie?.value) {
return NextResponse.redirect(new URL('/login', request.url));
}
try {
const { payload } = await jwtVerify(cookie.value, key, { algorithms: ['HS256'] });
const mustChange = payload.mustChangePassword as boolean;
if (mustChange && pathname !== '/change-password') {
return NextResponse.redirect(new URL('/change-password', request.url));
}
if (!mustChange && pathname === '/change-password') {
return NextResponse.redirect(new URL('/', request.url));
}
if (pathname === '/api/statistik/grafik') {
return NextResponse.next();
}
return NextResponse.next({
headers: {
'X-Frame-Options': 'DENY',
},
});
} catch {
return NextResponse.redirect(new URL('/login', request.url));
}
}
export const config = {
matcher: ['/((?!_next/static|_next/image|favicon.ico).*)'],
};