-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmiddleware.ts
62 lines (52 loc) · 1.64 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
58
59
60
61
62
import { parse, serialize } from "cookie";
import type { NextRequest } from "next/server";
import { NextResponse } from "next/server";
import { decrypt } from "./lib/auth/auth";
const handleRoleBasedRedirect = (req: NextRequest, role: string) => {
const cookie = req.headers.get("cookie");
if (!cookie) {
return NextResponse.redirect(new URL("/login", req.url));
}
const cookies = parse(cookie);
const authToken = cookies["auth"];
if (!authToken) {
return NextResponse.redirect(new URL("/login", req.url));
}
try {
const decrypted = decrypt(authToken);
if (!decrypted) {
const response = NextResponse.redirect(new URL("/login", req.url));
response.headers.set(
"Set-Cookie",
serialize("auth", "", { path: "/", maxAge: -1 })
);
return response;
}
const user = JSON.parse(decrypted);
if (user.role !== role) {
return NextResponse.redirect(new URL(`/${user.role}`, req.url));
}
return NextResponse.next();
} catch (error) {
console.error("Error decrypting cookie:", error);
const response = NextResponse.redirect(new URL("/login", req.url));
response.headers.set(
"Set-Cookie",
serialize("auth", "", { path: "/", maxAge: -1 })
);
return response;
}
};
export async function middleware(req: NextRequest) {
const { pathname } = req.nextUrl;
if (pathname.includes("/admin")) {
return handleRoleBasedRedirect(req, "admin");
}
if (pathname.includes("/devotee")) {
return handleRoleBasedRedirect(req, "devotee");
}
return NextResponse.next();
}
export const config = {
matcher: ["/admin/:path*", "/devotee/:path*"],
};