2020-07-17 10:03:38 +02:00
|
|
|
import requestIp from 'request-ip';
|
|
|
|
import { browserName, detectOS } from 'detect-browser';
|
2020-07-23 05:45:09 +02:00
|
|
|
import isLocalhost from 'is-localhost-ip';
|
2020-07-18 09:25:29 +02:00
|
|
|
import maxmind from 'maxmind';
|
|
|
|
import geolite2 from 'geolite2-redist';
|
2020-07-18 06:01:49 +02:00
|
|
|
|
2020-07-17 10:03:38 +02:00
|
|
|
export function getIpAddress(req) {
|
2020-07-18 09:25:29 +02:00
|
|
|
// Cloudflare
|
2020-07-17 10:03:38 +02:00
|
|
|
if (req.headers['cf-connecting-ip']) {
|
|
|
|
return req.headers['cf-connecting-ip'];
|
|
|
|
}
|
2020-07-18 09:25:29 +02:00
|
|
|
|
2020-07-17 10:03:38 +02:00
|
|
|
return requestIp.getClientIp(req);
|
|
|
|
}
|
|
|
|
|
|
|
|
export function getDevice(req) {
|
|
|
|
const userAgent = req.headers['user-agent'];
|
|
|
|
const browser = browserName(userAgent);
|
|
|
|
const os = detectOS(userAgent);
|
|
|
|
|
|
|
|
return { userAgent, browser, os };
|
|
|
|
}
|
|
|
|
|
2020-07-18 09:25:29 +02:00
|
|
|
export async function getCountry(req, ip) {
|
|
|
|
// Cloudflare
|
|
|
|
if (req.headers['cf-ipcountry']) {
|
|
|
|
return req.headers['cf-ipcountry'];
|
|
|
|
}
|
|
|
|
|
|
|
|
// Ignore local ips
|
|
|
|
if (await isLocalhost(ip)) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
// Database lookup
|
|
|
|
const lookup = await geolite2.open('GeoLite2-Country', path => {
|
|
|
|
return maxmind.open(path);
|
|
|
|
});
|
|
|
|
|
|
|
|
const result = lookup.get(ip);
|
|
|
|
|
|
|
|
lookup.close();
|
|
|
|
|
|
|
|
return result.country.iso_code;
|
2020-07-17 10:03:38 +02:00
|
|
|
}
|