Created
May 11, 2018 15:16
-
-
Save diegoparrilla/06ef6eb9d6064aa3d980dced253f777c to your computer and use it in GitHub Desktop.
Using Cloudflare Workers and https://Apility.io API to block access to the pages filtered if the IP belongs to a blacklisted IP address of the service
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
addEventListener('fetch', event => { | |
event.respondWith(fetchAndCheckOrigin(event.request)) | |
}) | |
async function fetchAndCheckOrigin(req) { | |
try { | |
const body = await req.body; | |
const ip = req.headers.get('cf-connecting-ip'); | |
const apilityio = await fetch('https://api.apility.net/badip/' + ip + '?token=APILITY_IO_API_KEY'); | |
const status = await apilityio.status; | |
if (status == 200) { | |
// The IP has been found in any blacklist | |
return new Response('Sorry, you cannot access this site from this IP: ' + ip, | |
{ status: 403, statusText: 'Forbidden' }) | |
} | |
if (status == 429) { | |
// Quota Exceeded. Too many requests. | |
return new Response('Your Apility.io quota has run out. Please change your plan to support more traffic.', | |
{ status: 429, statusText: 'Too many requests.' }) | |
} | |
return await fetch(req) | |
} catch (err) { | |
console.log(err); | |
return new Response('Internal Error') | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment