forked from 1leuk/Webdev-CR-Revisi
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddleware.ts
More file actions
43 lines (38 loc) · 1.13 KB
/
Copy pathmiddleware.ts
File metadata and controls
43 lines (38 loc) · 1.13 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
import { withAuth } from "next-auth/middleware";
import { NextResponse } from "next/server";
export default withAuth(
// `withAuth` augments your `Request` with the user's token
function middleware(req) {
const token = req.nextauth.token;
const isAuthenticated = !!token;
const isAdmin = token?.role === "ADMIN";
const pathname = req.nextUrl.pathname;
// Redirect to login if not authenticated
if (!isAuthenticated) {
const url = new URL("/login", req.url);
url.searchParams.set("callbackUrl", encodeURI(req.url));
return NextResponse.redirect(url);
}
// Handle admin routes
if (pathname.startsWith("/admin") && !isAdmin) {
return NextResponse.redirect(new URL("/", req.url));
}
return NextResponse.next();
},
{
callbacks: {
// Only run this middleware on protected routes
authorized: ({ token }) => !!token,
},
}
);
// Specify which routes this middleware should apply to
export const config = {
matcher: [
"/profile/:path*",
"/admin/:path*",
"/orders/:path*",
"/checkout/:path*",
"/chat/:path*", // Added chat routes
],
};