2026-03-02 09:05:18 +01:00
|
|
|
/**
|
2026-03-05 05:18:03 +01:00
|
|
|
* TEE OFF SECURITY MIDDLEWARE v1.1
|
2026-03-02 09:05:18 +01:00
|
|
|
* ---------------------------------------------------------------------------
|
|
|
|
|
* REGEL: Beskytter alle ruter under /admin (unntatt /admin/login).
|
|
|
|
|
* FUNKSJON: Sjekker for admin_session cookie og omdirigerer hvis den mangler.
|
2026-03-05 05:18:03 +01:00
|
|
|
* RETTING: Flyttet NextRequest til next/server for å fikse build-error.
|
2026-03-02 09:05:18 +01:00
|
|
|
* ---------------------------------------------------------------------------
|
|
|
|
|
*/
|
|
|
|
|
|
2026-03-05 05:18:03 +01:00
|
|
|
import { NextResponse, type NextRequest } from 'next/server';
|
2026-03-02 09:05:18 +01:00
|
|
|
|
|
|
|
|
export function middleware(request: NextRequest) {
|
|
|
|
|
const { pathname } = request.nextUrl;
|
|
|
|
|
const session = request.cookies.get('admin_session');
|
2026-04-13 15:29:43 +02:00
|
|
|
const isAdminPage = pathname.startsWith('/admin');
|
|
|
|
|
const isAdminApi = pathname.startsWith('/api/admin');
|
2026-03-02 09:05:18 +01:00
|
|
|
|
|
|
|
|
// 1. Tillat alltid tilgang til innloggingssiden
|
|
|
|
|
if (pathname.startsWith('/admin/login')) {
|
|
|
|
|
return NextResponse.next();
|
|
|
|
|
}
|
|
|
|
|
|
2026-04-13 15:29:43 +02:00
|
|
|
// 2. Beskytt interne admin-API-ruter med 401 i stedet for redirect
|
|
|
|
|
if (isAdminApi) {
|
|
|
|
|
if (!session) {
|
|
|
|
|
return NextResponse.json({ detail: 'Admin-innlogging kreves' }, { status: 401 });
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// 3. Beskytt alle andre ruter under /admin
|
|
|
|
|
if (isAdminPage) {
|
|
|
|
|
if (pathname.startsWith('/admin/login')) {
|
|
|
|
|
return NextResponse.next();
|
|
|
|
|
}
|
|
|
|
|
|
2026-03-02 09:05:18 +01:00
|
|
|
if (!session) {
|
|
|
|
|
// Ingen sesjon funnet -> Send til innlogging
|
|
|
|
|
const loginUrl = new URL('/admin/login', request.url);
|
|
|
|
|
return NextResponse.redirect(loginUrl);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return NextResponse.next();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Definer hvilke ruter middleware skal kjøre på
|
|
|
|
|
export const config = {
|
2026-04-13 15:29:43 +02:00
|
|
|
matcher: ['/admin/:path*', '/api/admin/:path*'],
|
|
|
|
|
};
|