-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddleware.ts
More file actions
43 lines (35 loc) · 1.24 KB
/
middleware.ts
File metadata and controls
43 lines (35 loc) · 1.24 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
import { withAuth } from "next-auth/middleware";
import { NextResponse } from "next/server";
export default withAuth(
function middleware(req) {
const token = req.nextauth.token;
const path = req.nextUrl.pathname;
// Redirect to login if not authenticated (handled by withAuth by default, but explicit check here)
if (!token) {
return NextResponse.redirect(new URL("/login", req.url));
}
const role = token.role;
// Role-based protection
if (path.startsWith("/student") && role !== "student") {
return NextResponse.redirect(new URL("/login", req.url)); // Or unauthorized page
}
if (path.startsWith("/lecturer") && role !== "lecturer") {
return NextResponse.redirect(new URL("/login", req.url));
}
if (path.startsWith("/admin") && role !== "admin") {
return NextResponse.redirect(new URL("/login", req.url));
}
return NextResponse.next();
},
{
callbacks: {
authorized: ({ token }) => !!token,
},
pages: {
signIn: "/login",
},
}
);
export const config = {
matcher: ["/student/:path*", "/lecturer/:path*", "/admin/:path*"],
};