-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmiddleware.js
73 lines (64 loc) · 2.11 KB
/
middleware.js
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
import { NextResponse } from 'next/server';
import { getToken } from 'next-auth/jwt';
export async function middleware(request) {
// Get the pathname of the request
const path = request.nextUrl.pathname;
// Define public paths that don't require authentication
const isPublicPath =
path === '/auth/signin' ||
path === '/auth/signup' ||
path === '/api/auth/signin' ||
path === '/api/auth/signup' ||
path === '/api/auth/callback' ||
path === '/api/auth/session' ||
path === '/api/auth/csrf' ||
path === '/api/auth/providers' ||
path.startsWith('/_next') ||
path.startsWith('/static') ||
path === '/favicon.ico';
// Check if the path is public
if (isPublicPath) {
return NextResponse.next();
}
// Check if the path is an API route
const isApiRoute = path.startsWith('/api/');
// For API routes, check for authentication
if (isApiRoute) {
try {
const token = await getToken({ req: request });
// If no token is found and it's not a public API route, return unauthorized
if (!token) {
console.log(`Unauthorized API access attempt: ${path}`);
return NextResponse.json(
{ error: 'Unauthorized' },
{ status: 401 }
);
}
// For admin-only API routes, check if the user is an admin
if (path.startsWith('/api/admin/') && !token.isAdmin) {
console.log(`Forbidden API access attempt: ${path}`);
return NextResponse.json(
{ error: 'Forbidden' },
{ status: 403 }
);
}
} catch (error) {
console.error('Middleware error:', error);
// Continue to the next middleware or route handler
}
}
// Continue to the next middleware or route handler
return NextResponse.next();
}
// Configure the middleware to run on specific paths
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).*)',
],
};