-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmiddleware.ts
More file actions
37 lines (27 loc) · 1 KB
/
middleware.ts
File metadata and controls
37 lines (27 loc) · 1 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 { NextResponse, type NextRequest } from "next/server";
import { getToken } from "next-auth/jwt";
import { canAccessPath } from "@/lib/role";
const allowedPaths = ["/error/unauthorized", "/error"];
export default async function middleware(req: NextRequest) {
const { pathname } = req.nextUrl;
if (pathname === "/") {
return NextResponse.redirect(new URL("/auth/login", req.url));
}
if (pathname.startsWith("/api") || pathname.startsWith("/auth") || allowedPaths.includes(pathname)) {
return NextResponse.next();
}
const token = await getToken({
req,
secret: process.env.AUTH_SECRET,
});
if (!token?.id) {
return NextResponse.redirect(new URL("/auth/login", req.url));
}
if (!canAccessPath(token.role as string | undefined, pathname)) {
return NextResponse.redirect(new URL("/error/unauthorized", req.url));
}
return NextResponse.next();
}
export const config = {
matcher: ["/((?!_next/static|_next/image|favicon.ico|.*\\.(?:svg|png|jpg|jpeg|gif|webp)$).*)"],
};