-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddleware.js
More file actions
75 lines (61 loc) · 2.25 KB
/
middleware.js
File metadata and controls
75 lines (61 loc) · 2.25 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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
// middleware.js
import { NextResponse } from "next/server";
// Simple JWT decoder function that doesn't require external libraries
function decodeJWT(token) {
try {
// JWT tokens are base64url encoded and have 3 parts separated by dots
const base64Url = token.split(".")[1]; // Get the payload part
const base64 = base64Url.replace(/-/g, "+").replace(/_/g, "/");
const jsonPayload = decodeURIComponent(
atob(base64)
.split("")
.map((c) => "%" + ("00" + c.charCodeAt(0).toString(16)).slice(-2))
.join("")
);
return JSON.parse(jsonPayload);
} catch (error) {
console.error("Error decoding JWT:", error);
return null;
}
}
export function middleware(request) {
console.log("Middleware running on path:", request.nextUrl.pathname);
// Get the token from cookies - CHANGED from "jwt" to "token" to match your auth system
const token = request.cookies.get("token")?.value;
console.log("Token found:", token ? "Yes" : "No");
// Admin-only routes
const adminRoutes = ["/dashboard", "/profile", "/admin"];
const currentPath = request.nextUrl.pathname;
// Check if current path is an admin route
const isAdminRoute = adminRoutes.some(
(route) => currentPath === route || currentPath.startsWith(`${route}/`)
);
console.log("Is admin route:", isAdminRoute);
if (isAdminRoute) {
// No token - redirect to login
if (!token) {
console.log("No token, redirecting to login");
return NextResponse.redirect(new URL("/login", request.url));
}
// Decode token to check role
const decoded = decodeJWT(token);
console.log("Decoded token:", decoded);
if (!decoded) {
console.log("User is not admin, redirecting to unauthorized");
return NextResponse.redirect(new URL("/unauthorized", request.url));
}
if (decoded.role !== "Admin") {
return NextResponse.redirect(new URL("/", request.url));
}
console.log("User is admin, allowing access");
}
return NextResponse.next();
}
// Configure middleware to run on these routes
export const config = {
matcher: ["/dashboard", "/dashboard/:path*", "/admin", "/profile1", "/login"],
};
// lefew35865@clubemp.com
// besecab627@anlocc.com
// revahi6260@clubemp.com //++
// yebiv18346@cxnlab.com