-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmiddleware.ts
More file actions
63 lines (55 loc) · 1.87 KB
/
Copy pathmiddleware.ts
File metadata and controls
63 lines (55 loc) · 1.87 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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
import { withAuth } from "next-auth/middleware"
import { NextResponse } from "next/server"
import { USER_STATUS } from "./lib/constants"
export default withAuth(
function middleware(req) {
const { token } = req.nextauth
const { pathname } = req.nextUrl
// Allow access to auth pages
if (pathname.startsWith('/auth/')) {
return NextResponse.next()
}
// Check if user is authenticated
if (!token) {
const url = new URL('/auth/signin', req.url)
url.searchParams.set('callbackUrl', req.url)
return NextResponse.redirect(url)
}
// Check if user status is active or pending (allow pending for testing)
if (token.status === USER_STATUS.INACTIVE) {
return NextResponse.redirect(new URL('/auth/error?error=AccountInactive', req.url))
}
// Additional role-based checks can be added here
// For example, admin-only routes:
if (pathname.startsWith('/admin/') && !token.roles?.includes('Admin')) {
return NextResponse.redirect(new URL('/unauthorized', req.url))
}
return NextResponse.next()
},
{
callbacks: {
authorized: ({ token, req }) => {
// Allow unauthenticated access to auth pages and API auth routes
const { pathname } = req.nextUrl
if (pathname.startsWith('/auth/') || pathname.startsWith('/api/auth/')) {
return true
}
// Require authentication for all other routes
return !!token
},
},
}
)
export const config = {
matcher: [
/*
* Match all request paths except for the ones starting with:
* - api/auth (auth API routes)
* - _next/static (static files)
* - _next/image (image optimization files)
* - favicon.ico, sitemap.xml, robots.txt (public files)
* - public folder files
*/
'/((?!api/auth|_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt|public).*)',
],
}