-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmiddleware.ts
More file actions
260 lines (230 loc) · 8.33 KB
/
Copy pathmiddleware.ts
File metadata and controls
260 lines (230 loc) · 8.33 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
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
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
import { jwtDecode } from "jwt-decode";
// Helper function to get user roles from token
const getUserRoles = (token: string | undefined): string[] => {
if (!token) return [];
try {
const decoded = jwtDecode(token) as { role?: string | string[]; exp?: number } | null;
// Check if token is expired
if (decoded?.exp) {
const currentTime = Math.floor(Date.now() / 1000);
if (decoded.exp < currentTime) {
console.error("[AUTH] Token expired");
return [];
}
}
// Handle both string and array of roles
if (!decoded?.role) return [];
return Array.isArray(decoded.role) ? decoded.role : [decoded.role];
} catch (error) {
console.error("[AUTH] Failed to decode token:", error);
return [];
}
};
// Helper to check if user has specific role
const hasRole = (roles: string[], targetRole: string): boolean => {
return roles.includes(targetRole);
};
// Helper to get primary role for routing
const getPrimaryRole = (roles: string[]): string | null => {
// Priority order: ADMIN > INSTRUCTOR > STUDENT
if (roles.includes("ROLE_ADMIN")) return "ROLE_ADMIN";
if (roles.includes("ROLE_INSTRUCTOR")) return "ROLE_INSTRUCTOR";
if (roles.includes("ROLE_STUDENT")) return "ROLE_STUDENT";
return null;
};
export function middleware(request: NextRequest) {
const { pathname, searchParams } = request.nextUrl;
const token = request.cookies.get("authToken")?.value;
const userRoles = getUserRoles(token);
const primaryRole = getPrimaryRole(userRoles);
// Public routes - accessible without authentication
const publicRoutes = [
"/",
"/landing",
"/login",
"/register",
"/reset-password",
"/forgot-password",
"/supscription",
"/courses",
"/payment/callback",
];
// Static files and XML sitemaps should always be accessible
if (pathname === "/sitemap.xml" || pathname.endsWith(".xml") || pathname.endsWith(".json")) {
return NextResponse.next();
}
const isPublicRoute = publicRoutes.some(
(route) => pathname === route || pathname.startsWith(`${route}/`)
);
// Auth routes (login, register, etc.)
const authRoutes = ["/login", "/register", "/reset-password", "/forgot-password"];
const isAuthRoute = authRoutes.some(
(route) => pathname === route || pathname.startsWith(`${route}/`)
);
// If user is NOT authenticated
if (!token || userRoles.length === 0) {
// Allow access to public routes (includes /courses and /courses/[slug]/[courseId])
if (isPublicRoute) {
return NextResponse.next();
}
// Redirect all other routes to login
const response = NextResponse.redirect(new URL("/login", request.url));
if (token) response.cookies.delete("authToken");
return response;
}
// If user IS authenticated
// Redirect from auth pages to appropriate dashboard based on primary role
if (isAuthRoute) {
if (primaryRole === "ROLE_ADMIN") {
return NextResponse.redirect(new URL("/admin/dashboard", request.url));
} else if (primaryRole === "ROLE_INSTRUCTOR") {
return NextResponse.redirect(new URL("/instructor/dashboard", request.url));
} else {
return NextResponse.redirect(new URL("/courses", request.url));
}
}
// Role-based access control
const isAdminRoute = pathname.startsWith("/admin/");
const isInstructorRoute = pathname.startsWith("/instructor/");
const isCoursesRoute = pathname.startsWith("/courses");
const isMyBeyondRoute = pathname.startsWith("/mybeyond");
const isInstructorRegistrationRoute = pathname.startsWith("/instructor-registration");
// ADMIN: Only access admin pages
if (hasRole(userRoles, "ROLE_ADMIN")) {
if (isAdminRoute) {
return NextResponse.next();
}
// Admin can access other routes if they have multiple roles
if (userRoles.length > 1) {
// Allow access to instructor/student routes if they have those roles
if (isInstructorRoute && hasRole(userRoles, "ROLE_INSTRUCTOR")) {
return NextResponse.next();
}
if ((isCoursesRoute || isMyBeyondRoute) && hasRole(userRoles, "ROLE_STUDENT")) {
return NextResponse.next();
}
if (isInstructorRegistrationRoute) {
return NextResponse.next();
}
if (pathname === "/" || pathname === "/landing") {
return NextResponse.next();
}
}
// Default: redirect to admin dashboard
if (!isPublicRoute) {
return NextResponse.redirect(new URL("/admin/dashboard", request.url));
}
}
// INSTRUCTOR: Can access instructor pages, landing, mybeyond, and specific tabs
if (hasRole(userRoles, "ROLE_INSTRUCTOR")) {
// Allow access to instructor routes
if (isInstructorRoute) {
return NextResponse.next();
}
// Allow access to landing page
if (pathname === "/" || pathname === "/landing") {
return NextResponse.next();
}
// Allow access to instructor registration
if (isInstructorRegistrationRoute) {
return NextResponse.next();
}
// Allow access to mybeyond with specific tabs
if (isMyBeyondRoute) {
const tab = searchParams.get("tab");
// Instructor can access: mycourse, myprofile, mywallet
if (
!tab ||
tab === "mycourse" ||
tab === "myprofile" ||
tab === "myusage" ||
tab === "mycertificate" ||
tab === "search-certificate" ||
tab === "payment-history"
) {
return NextResponse.next();
}
// Redirect to myprofile if trying to access other tabs
return NextResponse.redirect(new URL("/mybeyond?tab=myprofile", request.url));
}
// Block access to admin routes if not admin
if (isAdminRoute && !hasRole(userRoles, "ROLE_ADMIN")) {
return NextResponse.redirect(new URL("/instructor/dashboard", request.url));
}
// Allow courses page access
if (isCoursesRoute) {
return NextResponse.next();
}
// For any other route, allow access
return NextResponse.next();
}
// STUDENT: Can access student pages, landing, mybeyond (except mywallet)
if (hasRole(userRoles, "ROLE_STUDENT")) {
// Block access to admin routes if not admin
if (isAdminRoute && !hasRole(userRoles, "ROLE_ADMIN")) {
return NextResponse.redirect(new URL("/courses", request.url));
}
// Block access to instructor routes if not instructor
if (isInstructorRoute && !hasRole(userRoles, "ROLE_INSTRUCTOR")) {
return NextResponse.redirect(new URL("/courses", request.url));
}
// Allow access to instructor registration
if (isInstructorRegistrationRoute) {
return NextResponse.next();
}
// Allow access to landing page
if (pathname === "/" || pathname === "/landing") {
return NextResponse.next();
}
// Allow access to mybeyond with specific tabs
if (isMyBeyondRoute) {
const tab = searchParams.get("tab");
// Student can access mycourse, myprofile
// If instructor, also allow mywallet
if (
!tab ||
tab === "mycourse" ||
tab === "myprofile" ||
tab === "myusage" ||
tab === "mycertificate" ||
tab === "search-certificate" ||
tab === "payment-history"
) {
return NextResponse.next();
}
if (tab === "mywallet" && hasRole(userRoles, "ROLE_INSTRUCTOR")) {
return NextResponse.next();
}
// Block mywallet for non-instructors
if (tab === "mywallet") {
return NextResponse.redirect(new URL("/mybeyond?tab=myprofile", request.url));
}
return NextResponse.redirect(new URL("/mybeyond?tab=myprofile", request.url));
}
// Allow access to courses
if (isCoursesRoute) {
return NextResponse.next();
}
// For any other route, allow access
return NextResponse.next();
}
// If no valid role, redirect to login
const response = NextResponse.redirect(new URL("/login", request.url));
response.cookies.delete("authToken");
return response;
}
export const config = {
matcher: [
/*
* Match all request paths except for the ones starting with:
* - api (API routes)
* - _next/static (static files)
* - _next/image (image optimization files)
* - favicon.ico (favicon file)
* - public files (images, xml, etc.)
*/
"/((?!api|_next/static|_next/image|favicon.ico|.*\\.(?:svg|png|jpg|jpeg|gif|webp|webm|mp4|xml|glb)$).*)",
],
};