Added country lookup for ip.

This commit is contained in:
Mike Cao 2020-07-18 00:25:29 -07:00
parent e6908d9e04
commit 822d46a2e0
6 changed files with 125 additions and 11 deletions

View file

@ -2,6 +2,11 @@ import crypto from 'crypto';
import { v5 as uuid } from 'uuid';
import requestIp from 'request-ip';
import { browserName, detectOS } from 'detect-browser';
import maxmind from 'maxmind';
import geolite2 from 'geolite2-redist';
import isLocalhost from 'is-localhost-ip';
const UUID_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-5][0-9a-f]{3}-[089ab][0-9a-f]{3}-[0-9a-f]{12}$/;
export function md5(s) {
return crypto.createHash('md5').update(s).digest('hex');
@ -12,13 +17,15 @@ export function hash(s) {
}
export function validHash(s) {
return /^[0-9a-f]{8}-[0-9a-f]{4}-[0-5][0-9a-f]{3}-[089ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(s);
return UUID_REGEX.test(s);
}
export function getIpAddress(req) {
// Cloudflare
if (req.headers['cf-connecting-ip']) {
return req.headers['cf-connecting-ip'];
}
return requestIp.getClientIp(req);
}
@ -30,15 +37,34 @@ export function getDevice(req) {
return { userAgent, browser, os };
}
export function getCountry(req) {
return req.headers['cf-ipcountry'];
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;
}
export function parseSessionRequest(req) {
export async function parseSessionRequest(req) {
const ip = getIpAddress(req);
const { website_id, screen, language } = JSON.parse(req.body);
const { userAgent, browser, os } = getDevice(req);
const country = getCountry(req);
const country = await getCountry(req, ip);
const session_id = hash(`${website_id}${ip}${userAgent}${os}`);
return {