-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddleware.js
More file actions
95 lines (79 loc) · 2.49 KB
/
middleware.js
File metadata and controls
95 lines (79 loc) · 2.49 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
import { NextResponse } from "next/server";
import { getToken } from "next-auth/jwt";
const secret = process.env.NEXTAUTH_SECRET;
export async function middleware(req) {
const token = await getToken({ req, secret });
const pathname = req.nextUrl.pathname;
// Define path categories
const publicPaths = ["/", "/login", "/signup", "/about", "/contact"];
const protectedPaths = ["/dashboard", "/profile", "/settings"];
// Role-specific paths
const recruiterPaths = [
"/recruiter",
"/post-job",
"/applicants",
"/browse",
"/manage-jobs"
];
const candidatePaths = [
"/candidate",
"/applications",
"/saved",
"/job-search",
"/my-profile"
];
// Check path types
const isPublicPage = publicPaths.includes(pathname);
const isProtectedPage = protectedPaths.some(path => pathname.startsWith(path));
const isRecruiterPage = recruiterPaths.some(path => pathname.startsWith(path));
const isCandidatePage = candidatePaths.some(path => pathname.startsWith(path));
// Redirect logged-in users from public pages to dashboard
if (token && isPublicPage) {
return NextResponse.redirect(new URL("/dashboard", req.url));
}
// Redirect logged-out users from protected pages to login
if (!token && (isProtectedPage || isRecruiterPage || isCandidatePage)) {
const loginUrl = new URL("/login", req.url);
loginUrl.searchParams.set("callbackUrl", pathname);
return NextResponse.redirect(loginUrl);
}
// Role-based access control for authenticated users
if (token) {
const userRole = token.accountType;
// Block candidates from accessing recruiter-only paths
if (isRecruiterPage && userRole === "candidate") {
return NextResponse.redirect(new URL("/dashboard", req.url));
}
// Block recruiters from accessing candidate-only paths
if (isCandidatePage && userRole === "recruiter") {
return NextResponse.redirect(new URL("/dashboard", req.url));
}
}
return NextResponse.next();
}
export const config = {
matcher: [
// Public paths
"/",
"/login",
"/signup",
"/about",
"/contact",
// Protected paths
"/dashboard/:path*",
"/profile/:path*",
"/settings/:path*",
// Recruiter paths
"/recruiter/:path*",
"/post-job/:path*",
"/applicants/:path*",
"/browse/:path*",
"/manage-jobs/:path*",
// Candidate paths
"/candidate/:path*",
"/applications/:path*",
"/saved/:path*",
"/job-search/:path*",
"/my-profile/:path*"
],
};