-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmiddleware.ts
50 lines (41 loc) · 1.58 KB
/
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
38
39
40
41
42
43
44
45
46
47
48
49
50
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
import { getRolePath } from "./app/lib/getRolePath";
const rolePaths: Record<string, string[]> = {
student: ["/dashboard/student"],
asisten: ["/dashboard/asisten"],
dosen: ["/dashboard/dosen"],
admin: ["/dashboard/admin"],
superadmin: ["/dashboard/superadmin"],
};
export function middleware(request: NextRequest) {
const { pathname } = request.nextUrl;
const accessToken = request.cookies.get("access_token")?.value;
const role = request.cookies.get("user_role")?.value;
if (!accessToken || !role) {
return NextResponse.redirect(new URL("/masuk", request.url));
}
try {
// Decode payload JWT (part kedua)
const payloadBase64 = accessToken.split(".")[1];
const payloadJson = Buffer.from(payloadBase64, "base64").toString("utf-8");
const payload = JSON.parse(payloadJson);
// Periksa expiry (exp) dalam payload
const currentTime = Math.floor(Date.now() / 1000);
if (payload.exp && payload.exp < currentTime) {
throw new Error("Token expired");
}
const userRole = getRolePath(role);
const allowedPaths = rolePaths[userRole as keyof typeof rolePaths] || [];
if (!allowedPaths.some((path) => pathname.startsWith(path))) {
return NextResponse.redirect(new URL("/unauthorized", request.url));
}
} catch (error) {
// Redirect ke login jika token tidak valid atau expired
return NextResponse.redirect(new URL("/masuk", request.url));
}
return NextResponse.next();
}
export const config = {
matcher: ["/dashboard/:path*"],
};