Files
AM_CMS_Summative/proxy.ts
T
2026-11-06 10:02:29 +00:00

42 lines
1.5 KiB
TypeScript

// export { auth as proxy } from "@/auth";
import { auth } from "@/auth";
import { cookies } from "next/headers"
import { NextResponse } from "next/server";
export const proxy = auth(async (req) => { // req is incoming request, auth from nextauth wraps the function
const isLoggedIn = !!req.auth // boolean based on if session info is present
const currentPath = req.nextUrl.pathname;
const isAuthRoute = currentPath === "/login" || currentPath === "/register"//
const isPublicRoute = isAuthRoute || currentPath === "/" || currentPath === "/newsletters" || currentPath.startsWith("/newsletters/") || currentPath ==="/users"; // checks individual newsletters
// is a public route if its an authroute, newsletter route, or root(homepage) route
const isAdminRoute = currentPath === "/users"
if (process.env.ENFORCEADMIN === "true" && isAdminRoute) {
return NextResponse.redirect(new URL("/login", req.nextUrl.origin))
}
if (!isLoggedIn && !isPublicRoute) { // if not logged in and not on public route
const newUrl = new URL("/login", req.nextUrl.origin);
return NextResponse.redirect(newUrl);
}
if (isLoggedIn && isAuthRoute) { // if logged in and trying to log in
const newUrl = new URL("/", req.nextUrl.origin);
return NextResponse.redirect(newUrl);
}
return NextResponse.next();
}
)
export const config = {
matcher: ["/((?!api|_next/static|_next/image|favicon.ico).*)"],
};
// runs proxy function on paths in matcher