Repository navigation
Expand file tree
/
Copy pathmiddleware.ts
More file actions
58 lines (46 loc) · 1.6 KB
/
Copy pathmiddleware.ts
File metadata and controls
58 lines (46 loc) · 1.6 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
import NextAuth from "next-auth";
import { NextResponse } from "next/server";
import { authConfig } from "@/lib/auth.config";
import { ROLE_DASHBOARD_PATH } from "@/types";
import type { Role } from "@prisma/client";
const publicRoutes = ["/", "/login", "/register"];
const authRoutes = ["/login", "/register"];
const roleRoutePrefixes: Record<Role, string> = {
PATIENT: "/patient",
DOCTOR: "/doctor",
CAREGIVER: "/caregiver",
ADMIN: "/admin",
};
const { auth } = NextAuth(authConfig);
export default auth((req) => {
const { nextUrl } = req;
const isLoggedIn = !!req.auth;
const pathname = nextUrl.pathname;
const isPublicRoute = publicRoutes.includes(pathname);
const isAuthRoute = authRoutes.includes(pathname);
if (isAuthRoute && isLoggedIn) {
const role = req.auth?.user?.role;
if (role) {
return NextResponse.redirect(new URL(ROLE_DASHBOARD_PATH[role], nextUrl));
}
}
if (!isPublicRoute && !isLoggedIn) {
const loginUrl = new URL("/login", nextUrl);
loginUrl.searchParams.set("callbackUrl", pathname);
return NextResponse.redirect(loginUrl);
}
if (isLoggedIn && req.auth?.user?.role) {
const role = req.auth.user.role;
const allowedPrefix = roleRoutePrefixes[role];
const isRoleProtectedRoute = Object.values(roleRoutePrefixes).some(
(prefix) => pathname.startsWith(prefix) && prefix !== allowedPrefix,
);
if (isRoleProtectedRoute) {
return NextResponse.redirect(new URL(allowedPrefix, nextUrl));
}
}
return NextResponse.next();
});
export const config = {
matcher: ["/((?!api|_next/static|_next/image|favicon.ico).*)"],
};