init
This commit is contained in:
@@ -0,0 +1,42 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import type { NextRequest } from "next/server";
|
||||
import { ADMIN_SESSION_COOKIE } from "@/lib/auth/session";
|
||||
import { publicRequestUrl } from "@/lib/request-public-url";
|
||||
|
||||
function hasValidSession(request: NextRequest): boolean {
|
||||
return request.cookies.get(ADMIN_SESSION_COOKIE)?.value === "1";
|
||||
}
|
||||
|
||||
export function proxy(request: NextRequest) {
|
||||
const { pathname } = request.nextUrl;
|
||||
const isLogin = pathname === "/login";
|
||||
const isAuthApi = pathname.startsWith("/api/auth/");
|
||||
|
||||
if (isAuthApi) {
|
||||
return NextResponse.next();
|
||||
}
|
||||
|
||||
// Let route handlers return JSON (401, etc.). A redirect to /login breaks `fetch` + `res.json()` in the admin UI.
|
||||
if (!hasValidSession(request) && pathname.startsWith("/api/")) {
|
||||
return NextResponse.next();
|
||||
}
|
||||
|
||||
if (isLogin) {
|
||||
if (hasValidSession(request)) {
|
||||
return NextResponse.redirect(publicRequestUrl(request, "/"));
|
||||
}
|
||||
return NextResponse.next();
|
||||
}
|
||||
|
||||
if (!hasValidSession(request)) {
|
||||
return NextResponse.redirect(publicRequestUrl(request, "/login"));
|
||||
}
|
||||
|
||||
return NextResponse.next();
|
||||
}
|
||||
|
||||
export const config = {
|
||||
matcher: [
|
||||
"/((?!_next/static|_next/image|favicon.ico|.*\\.(?:svg|png|jpg|jpeg|gif|webp)$).*)",
|
||||
],
|
||||
};
|
||||
Reference in New Issue
Block a user