Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save diegoparrilla/06ef6eb9d6064aa3d980dced253f777c to your computer and use it in GitHub Desktop.
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
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