-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathmiddleware.ts
36 lines (26 loc) · 1.07 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
import { NextResponse, type NextRequest } from 'next/server';
import { CommonResponseFactory } from '@/app/lib/network';
import { isAuthorized } from '@/app/lib/auth';
import { env } from '@/app/config/env';
export const config = {
matcher: '/api/:path*',
};
export async function middleware(request: NextRequest) {
const isAuthRequired = !!env.API_TOKEN;
if (!isAuthRequired) {
return NextResponse.next();
}
const unprotectedRoutes = ['/api/ping', '/api/auth/', '/api/serve/', '/api/static/'];
const isUnprotected = unprotectedRoutes.some((route) => request.nextUrl.pathname.startsWith(route));
if (isUnprotected) {
return NextResponse.next();
}
return returnUnauthorizedResponseIfTokenDoesNotMatch(request, env.API_TOKEN!);
}
function returnUnauthorizedResponseIfTokenDoesNotMatch(request: NextRequest, apiToken: string) {
const actualAuthToken = request.headers.get('Authorization');
const expectedAuthToken = apiToken;
if (!isAuthorized({ actualAuthToken, expectedAuthToken })) {
return CommonResponseFactory.buildUnauthorizedResponse();
}
}