40 lines
1.1 KiB
TypeScript
40 lines
1.1 KiB
TypeScript
import { getToken } from "next-auth/jwt";
|
|
import { NextResponse, type NextRequest } from "next/server";
|
|
|
|
const PUBLIC_PATHS = ["/login"];
|
|
|
|
function usesSecureAuthCookies() {
|
|
const authUrl = process.env.AUTH_URL ?? process.env.NEXTAUTH_URL;
|
|
|
|
return authUrl?.startsWith("https://") ?? false;
|
|
}
|
|
|
|
export async function proxy(request: NextRequest) {
|
|
const { pathname, search } = request.nextUrl;
|
|
const isPublicPath = PUBLIC_PATHS.includes(pathname);
|
|
const cookieName = `${process.env.APP_ENV ?? "local"}-chocoadmin.session-token`;
|
|
const token = await getToken({
|
|
req: request,
|
|
secret: process.env.AUTH_SECRET ?? process.env.NEXTAUTH_SECRET,
|
|
secureCookie: usesSecureAuthCookies(),
|
|
cookieName,
|
|
});
|
|
|
|
if (!token && !isPublicPath) {
|
|
const loginUrl = new URL("/login", request.url);
|
|
loginUrl.searchParams.set("callbackUrl", `${pathname}${search}`);
|
|
|
|
return NextResponse.redirect(loginUrl);
|
|
}
|
|
|
|
if (token && isPublicPath) {
|
|
return NextResponse.redirect(new URL("/", request.url));
|
|
}
|
|
|
|
return NextResponse.next();
|
|
}
|
|
|
|
export const config = {
|
|
matcher: ["/((?!api/|_next/static|_next/image|favicon.ico|.*\\..*).*)"],
|
|
};
|