-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproxy.ts
More file actions
76 lines (57 loc) · 2.52 KB
/
proxy.ts
File metadata and controls
76 lines (57 loc) · 2.52 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
import type { NextRequest } from 'next/server';
import { NextResponse } from 'next/server';
import jwt, { JwtPayload } from 'jsonwebtoken';
import { deleteCookie, getCookie } from '@/services/auth/tokenHandlers';
import { getDefaultDashboardRoute, getRouteOwner, isAuthRoute, UserRole } from '@/lib/auth-utils';
// This function can be marked `async` if using `await` inside
export async function proxy(request: NextRequest) {
const pathname = request.nextUrl.pathname;
// const accessToken = request.cookies.get("accessToken")?.value || null;
const accessToken = await getCookie("accessToken") || null;
let userRole: UserRole | null = null;
if (accessToken) {
const verifiedToken: JwtPayload | string = jwt.verify(accessToken, process.env.JWT_SECRET as string);
if (typeof verifiedToken === "string") {
await deleteCookie("accessToken");
await deleteCookie("refreshToken");
return NextResponse.redirect(new URL('/login', request.url));
}
userRole = verifiedToken.role;
}
const routerOwner = getRouteOwner(pathname);
//path = /doctor/appointments => "DOCTOR"
//path = /my-profile => "COMMON"
//path = /login => null
const isAuth = isAuthRoute(pathname)
// Rule 1 : User is logged in and trying to access auth route. Redirect to default dashboard
if (accessToken && isAuth) {
return NextResponse.redirect(new URL(getDefaultDashboardRoute(userRole as UserRole), request.url))
}
// Rule 2 : User is trying to access open public route
if (routerOwner === null) {
return NextResponse.next();
}
// Rule 1 & 2 for open public routes and auth routes
if (!accessToken) {
const loginUrl = new URL("/login", request.url);
loginUrl.searchParams.set("redirect", pathname);
return NextResponse.redirect(loginUrl);
}
// Rule 3 : User is trying to access common protected route
if (routerOwner === "COMMON") {
return NextResponse.next();
}
// Rule 4 : User is trying to access role based protected route
if (routerOwner === "ADMIN" || routerOwner === "DOCTOR" || routerOwner === "PATIENT") {
if (userRole !== routerOwner) {
return NextResponse.redirect(new URL(getDefaultDashboardRoute(userRole as UserRole), request.url))
}
}
console.log(userRole);
return NextResponse.next();
}
export const config = {
matcher: [
'/((?!api|_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt|.well-known).*)',
],
}