forked from filipedeschamps/tabnews.com.br
-
Notifications
You must be signed in to change notification settings - Fork 0
/
middleware.public.js
76 lines (63 loc) · 2.14 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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
import { NextResponse } from 'next/server';
import snakeize from 'snakeize';
import { UnauthorizedError } from 'errors';
import logger from 'infra/logger.js';
import rateLimit from 'infra/rate-limit.js';
import underMaintenance from 'infra/under-maintenance';
import webserver from 'infra/webserver.js';
import ip from 'models/ip.js';
export const config = {
matcher: ['/((?!_next/static|va/|favicon|manifest).*)'],
};
export async function middleware(request) {
if (webserver.isProduction && !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 isUnderMaintenance = underMaintenance.check(request);
if (isUnderMaintenance) {
return new NextResponse(isUnderMaintenance.body, {
status: isUnderMaintenance.status,
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);
}
if (url.pathname === '/api/v1/swr') {
return new NextResponse(JSON.stringify({ timestamp: Date.now() }), {
status: 200,
headers: { 'Content-Type': 'application/json' },
});
}
return NextResponse.next();
} catch (error) {
console.error(snakeize({ message: error.message, ...error }));
return NextResponse.next();
}
}