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 || 'logbuch-secret-change-in-production'; const key = new TextEncoder().encode(secretKey); export async function proxy(request: NextRequest) { const { pathname } = request.nextUrl; if (pathname.startsWith('/login') || pathname.startsWith('/_next') || pathname.startsWith('/favicon')) { 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)); } return NextResponse.next(); } catch { return NextResponse.redirect(new URL('/login', request.url)); } } export const config = { matcher: ['/((?!_next/static|_next/image|favicon.ico).*)'], };