-
Notifications
You must be signed in to change notification settings - Fork 24
/
middleware.ts
37 lines (29 loc) · 972 Bytes
/
middleware.ts
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 { withAuth } from "next-auth/middleware";
import { NextResponse } from "next/server";
const ROLES_ALLOWED_TO_AUTH = ["ADMIN", "MODERATOR", "USER"];
export default withAuth(
function middleware(req) {
if(req.nextUrl.pathname === '/' && req.nextauth.token){
return NextResponse.redirect(new URL("/portal", req.url));
}
if (req.nextUrl.pathname.startsWith("/portal") && !req.nextauth.token) {
return NextResponse.redirect(new URL("/", req.url));
}
if (
req.nextUrl.pathname.startsWith("/dashboard") &&
req.nextauth.token?.role !== "ADMIN" &&
req.nextauth.token?.role !== "MODERATOR"
) {
return NextResponse.redirect(new URL("/portal", req.url));
}
},
{
callbacks: {
authorized: ({ token }) =>
token?.role !== undefined && ROLES_ALLOWED_TO_AUTH.includes(token.role),
},
}
);
export const config = {
matcher: ["/dashboard/:path*", "/portal/:path*", "/"],
};