This commit is contained in:
@@ -0,0 +1,34 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { SESSION_COOKIE_NAME, verifySessionToken } from "@/lib/auth";
|
||||
|
||||
const PUBLIC_PATHS = ["/login", "/api/auth/login", "/api/auth/setup", "/api/auth/status"];
|
||||
|
||||
export async function middleware(request: NextRequest) {
|
||||
const { pathname } = request.nextUrl;
|
||||
|
||||
if (
|
||||
PUBLIC_PATHS.includes(pathname) ||
|
||||
pathname.startsWith("/_next") ||
|
||||
pathname.startsWith("/favicon")
|
||||
) {
|
||||
return NextResponse.next();
|
||||
}
|
||||
|
||||
const token = request.cookies.get(SESSION_COOKIE_NAME)?.value;
|
||||
const isAuthenticated = token ? await verifySessionToken(token) : false;
|
||||
|
||||
if (!isAuthenticated) {
|
||||
if (pathname.startsWith("/api")) {
|
||||
return NextResponse.json({ error: "Nicht authentifiziert." }, { status: 401 });
|
||||
}
|
||||
const loginUrl = new URL("/login", request.url);
|
||||
loginUrl.searchParams.set("next", pathname);
|
||||
return NextResponse.redirect(loginUrl);
|
||||
}
|
||||
|
||||
return NextResponse.next();
|
||||
}
|
||||
|
||||
export const config = {
|
||||
matcher: ["/((?!_next/static|_next/image|favicon.ico).*)"],
|
||||
};
|
||||
Reference in New Issue
Block a user