-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddleware.ts
More file actions
41 lines (32 loc) · 1.26 KB
/
middleware.ts
File metadata and controls
41 lines (32 loc) · 1.26 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
import NextAuth from "next-auth"
import authConfig from "@/auth.config"
const { auth } = NextAuth(authConfig)
import { NextResponse } from "next/server"
// ... imports
export default auth((req) => {
const isLoggedIn = !!req.auth
const isAuthRoute = req.nextUrl.pathname.startsWith("/auth")
const isAdminRoute = req.nextUrl.pathname.startsWith("/admin")
// Allow auth routes always
if (isAuthRoute) {
return
}
// Protect admin routes
if (isAdminRoute) {
if (!isLoggedIn) {
console.log("Middleware: Admin route accessed, not logged in. Redirecting to signin.")
return NextResponse.redirect(new URL("/auth/signin", req.nextUrl))
}
// @ts-ignore
const userRole = req.auth?.user?.role || "CUSTOMER"
console.log(`Middleware: Admin route accessed. User Role: ${userRole}`)
if (userRole !== "ADMIN" && userRole !== "Admin") {
console.log("Middleware: User is not ADMIN. Redirecting to /.")
return NextResponse.redirect(new URL("/", req.nextUrl))
}
}
})
// Optionally, don't invoke Middleware on some paths
export const config = {
matcher: ["/((?!api|_next/static|_next/image|favicon.ico).*)"],
}