-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproxy.ts
More file actions
75 lines (60 loc) · 1.8 KB
/
Copy pathproxy.ts
File metadata and controls
75 lines (60 loc) · 1.8 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
import { NextRequest, NextResponse } from "next/server";
import { getToken } from "next-auth/jwt";
import {
clearSessionCookies,
getAuthSecret,
hasSessionCookie,
} from "@/lib/auth";
const freelancerRoutes = ["/Fdash", "/Fprofile", "/MyApplications", "/ApplyJob"];
const clientRoutes = ["/Cdash", "/Cprofile", "/NewJob", "/JobApplications"];
function matchesRoute(pathname: string, routes: string[]) {
return routes.some((route) => pathname === route || pathname.startsWith(`${route}/`));
}
async function getValidToken(req: NextRequest) {
try {
return await getToken({ req, secret: getAuthSecret() });
} catch {
return null;
}
}
export async function proxy(req: NextRequest) {
const { pathname } = req.nextUrl;
let token = null;
if (hasSessionCookie(req)) {
token = await getValidToken(req);
if (!token) {
const response = NextResponse.next();
clearSessionCookies(response);
return response;
}
}
const isFreelancerRoute = matchesRoute(pathname, freelancerRoutes);
const isClientRoute = matchesRoute(pathname, clientRoutes);
if ((isFreelancerRoute || isClientRoute) && !token) {
const loginUrl = new URL("/login", req.url);
return NextResponse.redirect(loginUrl);
}
if (!token) {
return NextResponse.next();
}
if (isFreelancerRoute && token.role !== "Freelancer") {
return NextResponse.redirect(new URL("/Cdash", req.url));
}
if (isClientRoute && token.role !== "Client") {
return NextResponse.redirect(new URL("/Fdash", req.url));
}
return NextResponse.next();
}
export const config = {
matcher: [
"/Fdash/:path*",
"/Fprofile/:path*",
"/MyApplications/:path*",
"/ApplyJob/:path*",
"/Cdash/:path*",
"/Cprofile/:path*",
"/NewJob/:path*",
"/JobApplications/:path*",
"/api/auth/:path*",
],
};