-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmiddleware.ts
More file actions
43 lines (34 loc) · 1.43 KB
/
middleware.ts
File metadata and controls
43 lines (34 loc) · 1.43 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
38
39
40
41
42
43
import { withAuth } from "next-auth/middleware";
import { NextResponse } from "next/server";
export default withAuth(
function middleware(req) {
const token = req.nextauth.token;
const path = req.nextUrl.pathname;
// Allow access to /cart and /checkout if authenticated
if (path.startsWith("/cart") || path.startsWith("/checkout")) {
return NextResponse.next();
}
const roleAccess: Record<string, string[]> = {
"super-admin": ["/dashboard", "/dashboard/users", "/dashboard/settings", "/dashboard/payments", "/dashboard/products", "/dashboard/orders", "/dashboard/profile"],
"admin": ["/dashboard", "/dashboard/users", "/dashboard/products", "/dashboard/orders", "/dashboard/profile"],
"manager": ["/dashboard", "/dashboard/products", "/dashboard/orders", "/dashboard/profile"],
"user": ["/dashboard", "/dashboard/orders", "/dashboard/profile", "/dashboard"]
};
if (!token) return NextResponse.next();
const userRole = token.role as string;
const allowedPaths = roleAccess[userRole] || [];
const isAllowed = allowedPaths.some((allowedPath) => path.startsWith(allowedPath));
if (!isAllowed) {
return NextResponse.redirect(new URL("/dashboard", req.url));
}
return NextResponse.next();
},
{
callbacks: {
authorized: ({ token }) => !!token
}
}
);
export const config = {
matcher: ["/dashboard/:path*", "/cart/:path*", "/checkout/:path*"]
};