-
Notifications
You must be signed in to change notification settings - Fork 167
/
middleware.ts
72 lines (60 loc) · 1.94 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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
import type { NextRequest } from 'next/server';
import { NextResponse } from 'next/server';
import { validateApiKey, extractAuthToken } from '@lib/auth';
import { getToken } from 'next-auth/jwt';
import { sessionName } from '@lib/constants';
import micromatch from 'micromatch';
// Add API routes that don't require authentication
const unAuthenticatedApiRoutes = [
'/api/health',
'/api/hello',
'/api/auth/**',
'/api/federated-saml/**',
'/api/identity-federation/**',
'/api/logout/**',
'/api/oauth/**',
'/api/scim/v2.0/**',
'/api/scim/oauth/**',
'/api/well-known/**',
'/api/setup/**',
'/api/branding',
];
export async function middleware(req: NextRequest) {
const { pathname } = req.nextUrl;
// Bypass routes that don't require authentication
if (micromatch.isMatch(pathname, unAuthenticatedApiRoutes)) {
return NextResponse.next();
}
// Validate API routes `/api/admin/**`
if (micromatch.isMatch(pathname, '/api/admin/**')) {
const adminToken = await getToken({
req,
cookieName: sessionName,
});
if (!adminToken) {
return sendUnAuthorizedResponse({ message: 'Unauthorized' });
}
return NextResponse.next();
}
// Validate API routes `/api/v1/**`
if (micromatch.isMatch(pathname, ['/api/v1/**', '/api/internals/**'])) {
if (!validateApiKey(extractAuthToken(req))) {
return sendUnAuthorizedResponse({ message: 'Unauthorized' });
}
return NextResponse.next();
}
// By default, deny access to all other routes
return sendUnAuthorizedResponse({ message: 'Unauthorized' });
}
// Send 401 response for unauthenticated requests
const sendUnAuthorizedResponse = async (error: { message: string }) => {
const response = JSON.stringify({ error });
return new NextResponse(response, {
status: 401,
headers: { 'content-type': 'application/json' },
});
};
// Limit the middleware to specific '/api/*' routes
export const config = {
matcher: ['/api/:path*'],
};