-
Notifications
You must be signed in to change notification settings - Fork 0
/
middleware.ts
57 lines (48 loc) · 1.34 KB
/
middleware.ts
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
import { NextRequest, NextResponse } from "next/server";
import { updateSession } from "@sessions/sessionUtils";
import {
handleExpiredSession,
handlePrivateRoute,
handlePublicRoute,
} from "@middlewares/index";
const PUBLIC_ROUTES = ["/", "/login", "/signup", "/admin-login"];
const PRIVATE_ROUTES = [
"/patient",
"/receptionist",
"/doctor",
"/hospital",
"/admin",
];
const SESSION_COOKIE = "session";
const SESSION_EXPIRED_URL = "/session-expired";
export async function middleware(request: NextRequest) {
const path = request.nextUrl.pathname;
const token = request.cookies.get(SESSION_COOKIE)?.value;
// update session
if (token) {
try {
await updateSession(request);
} catch (error) {
const USER_ROLE = path.split("/")[1];
return handleExpiredSession(
request,
SESSION_COOKIE,
`${SESSION_EXPIRED_URL}?role=${USER_ROLE}`
);
}
}
// check if it's a public route
if (PUBLIC_ROUTES.includes(path)) {
return handlePublicRoute(request, token);
}
// handle private routes
if (PRIVATE_ROUTES.includes(`/${path.split("/")[1]}`)) {
return handlePrivateRoute(request, token);
}
return NextResponse.next();
}
export const config = {
matcher: [
"/((?!api|_next/static|_next/image|.*\\.png$|.*\\.svg$|.*\\.gif$|.*\\.ico$|.*\\.jpg$|.*\\.webp$|error).*)",
],
};