-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmiddleware.ts
170 lines (151 loc) · 4.57 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
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
import { NextResponse } from "next/server";
import { NextRequest } from "next/server";
export function middleware(request: NextRequest) {
const path = request.nextUrl.pathname;
// Define public paths
const publicPaths = ["/login", "/register"];
const publicVisitsPath = ["/contact", "/faq", "/rule-regulations","/contact"];
const publicApiPath = [
"/api/auth/user/login",
"/api/auth/admin/login",
"/api/auth/logout",
"/api/public/:path*",
];
// Define user-specific paths
const userPaths = [
"/client/:path", // Match any path under a user's route
];
const adminPaths = [
"/admin/:path", // Match any path under an admin's route
];
// Define protected API routes
const userAPIRoutes = ["/api/issues/:path*"];
const adminAPIRoutes = [
"/api/admin/:path*",
"/api/auth/user/register",
"/api/userdata/userinfo/:path*",
"/api/issues/:path*",
"/api/issues/getissue/all",
"/api/auth/admin/users",
];
// Get tokens from cookies
const userToken = request.cookies.get("user-token")?.value || "";
const adminToken = request.cookies.get("admin-token")?.value || "";
// Verify Token
// try {
// // Verify the JWT token
// const isVerified = jwt.verify(token, secretKey);
// // Connect to the database
// await connectToDatabase();
// // Fetch user data excluding the password
// const userData = await User.findOne({ email: isVerified.email }).select({
// password: 0,
// });
// if (!userData) {
// return NextResponse.json(
// { message: 'Unauthorized, User not found' },
// { status: 404 }
// );
// }
// // Attach user data and token to the request object (Next.js way)
// req.user = userData;
// req.token = token;
// req.userID = userData._id;
// return NextResponse.next(); // Allow the request to continue
// } catch (error) {
// console.error('Error verifying token:', error);
// return NextResponse.json(
// { message: 'Unauthorized. Invalid Token.' },
// { status: 401 }
// );
// }
// }
// Public API
if (path.startsWith("/api/public/")) {
// Do not check tokens, allow access without affecting the request
return NextResponse.next();
}
// Redirect logic for public paths
if (publicPaths.includes(path)) {
if (userToken || adminToken) {
// If user or admin is logged in, redirect them to the home page
return NextResponse.redirect(new URL("/", request.url));
}
}
// Redirect if accessing a protected path without a user token
if (
!publicPaths.includes(path) &&
!publicVisitsPath.includes(path) &&
!publicApiPath.includes(path)
) {
if (!userToken && !adminToken) {
return NextResponse.redirect(new URL("/login", request.url));
}
}
// Protect user-specific paths
if (path.startsWith("/client/")) {
// Redirect to login if accessing client paths without a user token
if (!userToken) {
if (request.nextUrl.pathname.startsWith("/api")) {
return NextResponse.json(
{
message: "Access Denied!!",
success: false,
},
{
status: 401,
}
);
}
return NextResponse.redirect(new URL("/login", request.url));
}
}
// Protect user-specific paths
if (path.startsWith("/admin/")) {
// Redirect to login if accessing client paths without a user token
if (!adminToken) {
if (request.nextUrl.pathname.startsWith("/api")) {
return NextResponse.json(
{
message: "Access Denied!!",
success: false,
},
{
status: 401,
}
);
}
return NextResponse.redirect(new URL("/login", request.url));
}
}
// Protect API routes
if (
userAPIRoutes.some((route) =>
path.startsWith(route.replace(/:\w+/g, ""))
) &&
!userToken
) {
return NextResponse.json({ message: "Unauthorized" }, { status: 401 });
}
// Admin Protect API Routes
if (
adminAPIRoutes.some((route) =>
path.startsWith(route.replace(/:\w+/g, ""))
) &&
!adminToken
) {
return NextResponse.json({ message: "Unauthorized" }, { status: 401 });
}
// Add other custom logic if needed
}
// Configuration for which paths to apply the middleware to
export const config = {
matcher: [
"/login",
"/register",
"/api/:path*", // Apply middleware to all API routes
"/client/:path*", // Apply middleware to all client-specific routes
"/admin/:path*",
"/api/public/:path*",
],
};