43 lines
1.4 KiB
TypeScript
43 lines
1.4 KiB
TypeScript
import { NextResponse } from "next/server";
|
|
import type { NextRequest } from "next/server";
|
|
import { getToken } from "next-auth/jwt";
|
|
|
|
export default async function middleware(request: NextRequest) {
|
|
const { nextUrl } = request;
|
|
const token = await getToken({
|
|
req: request,
|
|
secret: process.env.AUTH_SECRET,
|
|
cookieName:
|
|
process.env.NODE_ENV === "production"
|
|
? "__Secure-authjs.session-token"
|
|
: "authjs.session-token"
|
|
});
|
|
const isBriefingsRoute = nextUrl.pathname.startsWith("/briefings");
|
|
const isAdminRoute = nextUrl.pathname.startsWith("/admin");
|
|
const isAccountRoute = nextUrl.pathname.startsWith("/minha-conta");
|
|
|
|
if ((isBriefingsRoute || isAdminRoute || isAccountRoute) && !token) {
|
|
const loginUrl = new URL("/login", nextUrl);
|
|
loginUrl.searchParams.set("callbackUrl", nextUrl.pathname);
|
|
return NextResponse.redirect(loginUrl);
|
|
}
|
|
|
|
if (isAdminRoute && token?.papel !== "ADMIN") {
|
|
return NextResponse.redirect(new URL("/briefings", nextUrl));
|
|
}
|
|
|
|
if (isBriefingsRoute && token?.papel !== "CLIENTE") {
|
|
return NextResponse.redirect(new URL("/admin", nextUrl));
|
|
}
|
|
|
|
if (isAccountRoute && token?.papel !== "CLIENTE") {
|
|
return NextResponse.redirect(new URL("/admin", nextUrl));
|
|
}
|
|
|
|
return NextResponse.next();
|
|
}
|
|
|
|
export const config = {
|
|
matcher: ["/briefings/:path*", "/admin/:path*", "/minha-conta/:path*"]
|
|
};
|