forked from KabiruH/attendance_project
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddleware.ts
More file actions
75 lines (64 loc) · 2.46 KB
/
middleware.ts
File metadata and controls
75 lines (64 loc) · 2.46 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
// middleware.ts
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
import { jwtVerify } from 'jose'
// Arrays of public and protected paths
const publicPaths = ['/login', '/signup', '/'];
const protectedPaths = ['/dashboard', '/attendance', '/reports', '/profile', '/users'];
const adminOnlyPaths = ['/users'];
export async function middleware(request: NextRequest) {
const { pathname } = request.nextUrl;
// Check path types
const isProtectedPath = protectedPaths.some(path => pathname.startsWith(path));
const isPublicPath = publicPaths.some(path => pathname.startsWith(path));
const isAdminPath = adminOnlyPaths.some(path => pathname.startsWith(path));
try {
// Get token from cookies
const token = request.cookies.get('token');
if (!token && (isProtectedPath || isAdminPath)) {
// Redirect to login if trying to access protected route without token
return NextResponse.redirect(new URL('/login', request.url));
}
if (token && isPublicPath) {
// Redirect to dashboard if trying to access public route with token
return NextResponse.redirect(new URL('/dashboard', request.url));
}
if (token && (isProtectedPath || isAdminPath)) {
try {
// Verify the token and decode its payload
const { payload } = await jwtVerify(
token.value,
new TextEncoder().encode(process.env.JWT_SECRET)
);
// Check role for admin paths
if (isAdminPath && payload.role !== 'admin') {
// Redirect non-admin users to dashboard
return NextResponse.redirect(new URL('/dashboard', request.url));
}
// Token is valid and role check passed (if required), allow access
return NextResponse.next();
} catch (error) {
// Token is invalid, redirect to login
return NextResponse.redirect(new URL('/login', request.url));
}
}
// Allow access to public routes
return NextResponse.next();
} catch (error) {
// Handle any errors by redirecting to login
return NextResponse.redirect(new URL('/login', request.url));
}
}
// Configure which routes use this middleware
export const config = {
matcher: [
/*
* Match all request paths except:
* - api routes (handles separately)
* - _next/static (static files)
* - _next/image (image optimization files)
* - favicon.ico (favicon file)
*/
'/((?!api|_next/static|_next/image|favicon.ico).*)',
],
}