-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproxy.ts
More file actions
37 lines (30 loc) · 1.11 KB
/
proxy.ts
File metadata and controls
37 lines (30 loc) · 1.11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import { Role } from "@prisma/client";
import { NextResponse, type NextRequest } from "next/server";
import { getToken } from "next-auth/jwt";
import { allowedRolesForPath, hasAccess } from "@/lib/rbac";
const loginRoute = "/login";
const accessDeniedRoute = "/access-denied";
export async function proxy(request: NextRequest) {
const { pathname, search } = request.nextUrl;
const token = await getToken({
req: request,
secret: process.env.NEXTAUTH_SECRET,
});
if (!token) {
const loginUrl = new URL(loginRoute, request.url);
loginUrl.searchParams.set("callbackUrl", `${pathname}${search}`);
return NextResponse.redirect(loginUrl);
}
if (!hasAccess(pathname, token.role as Role | null | undefined)) {
const allowed = allowedRolesForPath(pathname);
const denyUrl = new URL(accessDeniedRoute, request.url);
if (allowed) {
denyUrl.searchParams.set("required", allowed.join(","));
}
return NextResponse.redirect(denyUrl);
}
return NextResponse.next();
}
export const config = {
matcher: ["/student/:path*", "/teacher/:path*", "/admin/:path*", "/super-admin/:path*"],
};