-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddleware.ts
More file actions
39 lines (31 loc) · 1.19 KB
/
Copy pathmiddleware.ts
File metadata and controls
39 lines (31 loc) · 1.19 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
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
import NextAuth from "next-auth";
import { authConfig } from "@/lib/auth/auth.config";
const { auth } = NextAuth(authConfig);
export default auth(async function middleware(req: NextRequest & { auth: { user?: unknown } | null }) {
const { pathname } = req.nextUrl;
// Admin API routes: require ADMIN role
if (pathname.startsWith("/api/admin")) {
const role = (req.auth as { user?: { role?: string } } | null)?.user?.role;
if (role !== "ADMIN") {
return NextResponse.json({ data: null, error: "FORBIDDEN" }, { status: 403 });
}
return NextResponse.next();
}
// Skip auth processing for all other API routes
if (pathname.startsWith("/api/")) {
return NextResponse.next();
}
// Admin page routes: non-admin users get a 403 response
if (pathname.startsWith("/admin")) {
const role = (req.auth as { user?: { role?: string } } | null)?.user?.role;
if (role !== "ADMIN") {
return new NextResponse("Forbidden", { status: 403 });
}
}
return NextResponse.next();
});
export const config = {
matcher: ["/((?!_next/static|_next/image|favicon.ico|.*\\..*).*)"],
};