35 lines
1015 B
TypeScript
35 lines
1015 B
TypeScript
import { NextRequest, NextResponse } from "next/server";
|
|
import { SESSION_COOKIE_NAME, verifySessionToken } from "@/lib/auth";
|
|
|
|
const PUBLIC_PATHS = ["/login", "/api/auth/login", "/api/auth/register"];
|
|
|
|
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 userId = token ? await verifySessionToken(token) : null;
|
|
|
|
if (!userId) {
|
|
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).*)"],
|
|
};
|