-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddleware.ts
More file actions
101 lines (87 loc) · 2.89 KB
/
middleware.ts
File metadata and controls
101 lines (87 loc) · 2.89 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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
import { NextRequest, NextResponse } from 'next/server'
// Public routes that don't require authentication
const PUBLIC_ROUTES = [
'/login',
'/forgot-password',
'/api/auth/login',
'/api/auth/session',
'/api/health',
'/api/version',
]
// Role-based route prefixes
const ROLE_ROUTES: Record<string, string[]> = {
'/admin': ['ADMIN'],
'/hod': ['ADMIN', 'HOD'],
'/teacher': ['ADMIN', 'HOD', 'TEACHER'],
}
export async function middleware(req: NextRequest) {
const { pathname } = req.nextUrl
// Allow public routes
if (PUBLIC_ROUTES.some((r) => pathname.startsWith(r)) || pathname === '/') {
return NextResponse.next()
}
// Allow static files
if (
pathname.startsWith('/_next') ||
pathname.startsWith('/favicon') ||
pathname.includes('.')
) {
return NextResponse.next()
}
// Check session cookie
const sessionToken = req.cookies.get('session')?.value
if (!sessionToken) {
// API routes return 401, pages redirect to login
if (pathname.startsWith('/api/')) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
}
const loginUrl = new URL('/login', req.url)
loginUrl.searchParams.set('callbackUrl', pathname)
return NextResponse.redirect(loginUrl)
}
// For role-scoped routes (/admin, /hod, /teacher), validate role via session API
const roleMatch = pathname.match(/^\/(admin|hod|teacher)/)
const apiRoleMatch = pathname.match(/^\/api\/(admin)/)
if (roleMatch || apiRoleMatch) {
try {
const sessionUrl = new URL('/api/auth/session', req.url)
const sessionRes = await fetch(sessionUrl.toString(), {
headers: { cookie: `session=${sessionToken}` },
})
if (!sessionRes.ok) {
if (pathname.startsWith('/api/')) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
}
return NextResponse.redirect(new URL('/login', req.url))
}
const data = await sessionRes.json()
const userRole = data?.user?.role
if (!userRole) {
if (pathname.startsWith('/api/')) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
}
return NextResponse.redirect(new URL('/login', req.url))
}
// Check role access
const segment = roleMatch?.[1] || apiRoleMatch?.[1]
if (segment) {
const prefix = `/${segment}`
const allowedRoles = ROLE_ROUTES[prefix]
if (allowedRoles && !allowedRoles.includes(userRole)) {
if (pathname.startsWith('/api/')) {
return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
}
return NextResponse.redirect(new URL('/unauthorized', req.url))
}
}
} catch {
// If session check fails, let the server-side layout handle it
}
}
return NextResponse.next()
}
export const config = {
matcher: [
'/((?!_next/static|_next/image|favicon.ico).*)',
],
}