Created
May 25, 2018 15:29
-
-
Save diegoparrilla/500f82e5dc83502dced406abe9748290 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 an European country because of the GDPR.
This file contains 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 are European and you can sue me from this IP: ' + ip, | |
{ status: 451, statusText: 'Unavailable For Legal Reasons' }) | |
} | |
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