forked from filipedeschamps/tabnews.com.br
-
Notifications
You must be signed in to change notification settings - Fork 0
/
middleware.public.js
55 lines (46 loc) · 1.6 KB
/
middleware.public.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
import { NextResponse } from 'next/server';
import logger from 'infra/logger.js';
import rateLimit from 'infra/rate-limit.js';
import snakeize from 'snakeize';
import { UnauthorizedError } from '/errors/index.js';
import ip from 'models/ip.js';
export const config = {
matcher: ['/((?!_next/static|va/|favicon|manifest).*)'],
};
export async function middleware(request) {
if (process.env.VERCEL_ENV === 'production' && !ip.isRequestFromCloudflare(request)) {
const publicErrorObject = new UnauthorizedError({
message: 'Host não autorizado. Por favor, acesse https://www.tabnews.com.br.',
action: 'Não repita esta requisição.',
});
const privateErrorObject = {
...publicErrorObject,
context: {
clientIp: ip.extractFromRequest(request),
},
};
logger.info(snakeize(privateErrorObject));
return new NextResponse(JSON.stringify(publicErrorObject), {
status: 401,
headers: {
'content-type': 'application/json',
},
});
}
const url = request.nextUrl;
try {
const rateLimitResult = await rateLimit.check(request);
if (!rateLimitResult.success && url.pathname === '/api/v1/sessions') {
url.pathname = '/api/v1/_responses/rate-limit-reached-sessions'; // Fake response.
return NextResponse.rewrite(url);
}
if (!rateLimitResult.success) {
url.pathname = '/api/v1/_responses/rate-limit-reached';
return NextResponse.rewrite(url);
}
return NextResponse.next();
} catch (error) {
console.error(snakeize({ message: error.message, ...error }));
return NextResponse.next();
}
}