-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathmiddleware.ts
More file actions
42 lines (36 loc) · 1.22 KB
/
middleware.ts
File metadata and controls
42 lines (36 loc) · 1.22 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
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
import { Role } from "./@types";
import { getToken } from "./lib/storeGetDelete";
import { PageAccessName, protectedRoutes } from "./routes/types";
import pageAccessRights from "./routes/pageAccessRights";
export async function middleware(req: NextRequest) {
const { pathname } = req.nextUrl;
const token = await getToken();
const pageAccessRight = pageAccessRights.get(pathname as PageAccessName) || {
roles: [],
};
if (pathname === "/sign-in" || pathname === "/sign-up") {
const hasToken = Boolean(token);
if (hasToken) {
return NextResponse.redirect(new URL("/already-signed-in", req.nextUrl));
}
}
if (protectedRoutes.includes(pathname as PageAccessName)) {
if (!token) {
return NextResponse.redirect(new URL("/forbidden", req.nextUrl));
} else if (!pageAccessRight.roles.includes(token.userRole as Role)) {
return NextResponse.redirect(new URL("/unauthorized", req.nextUrl));
}
}
return NextResponse.next();
}
export const config = {
matcher: [
"/code-analysis/:path*",
"/sign-in/:path*",
"/sign-up/:path*",
"/dashboard/:path*",
"/add-developers/:path*",
],
};