-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddleware.ts
More file actions
44 lines (38 loc) · 1.31 KB
/
middleware.ts
File metadata and controls
44 lines (38 loc) · 1.31 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
import { withAuth } from 'next-auth/middleware'
import { NextResponse } from 'next/server'
export default withAuth(
function middleware(req) {
// If user is accessing admin routes, check if they have admin role
if (req.nextUrl.pathname.startsWith('/admin')) {
if (req.nextUrl.pathname === '/admin/login') {
// Allow access to login page
return NextResponse.next()
}
// Check if user has admin role
if (req.nextauth.token?.role !== 'admin') {
// Redirect to login if not admin
return NextResponse.redirect(new URL('/admin/login', req.url))
}
}
return NextResponse.next()
},
{
callbacks: {
authorized: ({ token, req }) => {
// Allow access to login page without authentication
if (req.nextUrl.pathname === '/admin/login') {
return true
}
// For admin routes, require authentication
if (req.nextUrl.pathname.startsWith('/admin')) {
return !!token
}
// Allow all other routes
return true
},
},
}
)
export const config = {
matcher: ['/admin/:path*']
}