-
-
Notifications
You must be signed in to change notification settings - Fork 4
/
middleware.api.ts
40 lines (32 loc) · 1.22 KB
/
middleware.api.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
import type { NextRequest } from "next/server"
import { NextResponse } from "next/server"
export const config = {
matcher: ["/colors/:path*", "/generators/:path*", "/contrast-checker/:path*"],
}
export const middleware = ({ headers }: NextRequest) => {
const blockedUserAgents = process.env.BLOCKED_USER_AGENTS?.split(",") ?? []
const blockedIpAddresses = process.env.BLOCKED_IP_ADDRESSES?.split(",") ?? []
const userAgent = headers.get("user-agent")
const xRealIp = headers.get("x-real-ip")
const xForwardedFor = headers.get("x-forwarded-for")
const ip = xRealIp ?? xForwardedFor?.split(",").at(0)
if (userAgent) {
const isBlockedUserAgent = (blockedUserAgent: string) =>
userAgent
.toLocaleUpperCase()
.includes(blockedUserAgent.toLocaleUpperCase())
if (blockedUserAgents.some(isBlockedUserAgent)) {
return new NextResponse("Access Denied", { status: 403 })
}
}
if (ip) {
const isBlockedIpAddress = (blockedIpAddress: string) =>
ip.includes(blockedIpAddress.toLocaleUpperCase())
if (blockedIpAddresses.some(isBlockedIpAddress)) {
return new NextResponse("Access Denied", { status: 403 })
} else {
console.log(ip)
}
}
return NextResponse.next()
}