-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmiddleware.ts
54 lines (47 loc) · 1.48 KB
/
middleware.ts
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
import type { NextRequest } from 'next/server';
import { NextResponse } from 'next/server';
// List of paths that don't require authentication
const publicPaths = [
'/',
'/login',
'/register',
'/forgot-password',
'/api/auth/login',
'/api/auth/register',
'/api/auth/reset-password',
];
// List of paths that require authentication
const protectedPaths = [
'/dashboard',
'/agents',
'/analytics',
'/settings',
'/api/agents',
'/api/system',
];
export function middleware(request: NextRequest) {
const { pathname } = request.nextUrl;
const token = request.cookies.get('auth-token')?.value;
// Check if the path is protected and user is not authenticated
if (protectedPaths.some((path) => pathname.startsWith(path)) && !token) {
const url = new URL('/login', request.url);
url.searchParams.set('from', pathname);
return NextResponse.redirect(url);
}
// Check if the user is authenticated and trying to access auth pages
if (token && publicPaths.includes(pathname)) {
return NextResponse.redirect(new URL('/dashboard', request.url));
}
return NextResponse.next();
}
export const config = {
matcher: [
/*
* Match all request paths except for the ones starting with:
* - _next/static (static files)
* - _next/image (image optimization files)
* - favicon.ico (favicon file)
*/
'/((?!_next/static|_next/image|favicon.ico).*)',
],
};