regions + city

This commit is contained in:
Nisarg 2021-10-10 23:08:28 -07:00
parent 2575cbfc11
commit 117d7c4400
6 changed files with 23 additions and 18 deletions

View file

@ -1,8 +1,7 @@
import path from 'path';
import requestIp from 'request-ip';
import { browserName, detectOS } from 'detect-browser';
import isLocalhost from 'is-localhost-ip';
import maxmind from 'maxmind';
import geoip from 'fast-geoip';
import {
DESKTOP_OS,
@ -12,8 +11,6 @@ import {
MOBILE_SCREEN_WIDTH,
} from './constants';
let lookup;
export function getIpAddress(req) {
// Cloudflare
if (req.headers['cf-connecting-ip']) {
@ -51,7 +48,7 @@ export function getDevice(screen, browser, os) {
}
}
export async function getCountry(req, ip) {
export async function getLocation(req, ip) {
// Cloudflare
if (req.headers['cf-ipcountry']) {
return req.headers['cf-ipcountry'];
@ -62,23 +59,24 @@ export async function getCountry(req, ip) {
return;
}
// Database lookup
if (!lookup) {
lookup = await maxmind.open(path.resolve('./public/geo/GeoLite2-Country.mmdb'));
}
const result = await geoip.lookup(ip);
const result = lookup.get(ip);
return result?.country?.iso_code;
return {
country: result?.country,
region: result?.region,
city: result?.city,
};
}
export async function getClientInfo(req, { screen }) {
const userAgent = req.headers['user-agent'];
const ip = getIpAddress(req);
const country = await getCountry(req, ip);
const country = await getLocation(req, ip).country;
const region = await getLocation(req, ip).region;
const city = await getLocation(req, ip).city;
const browser = browserName(userAgent);
const os = detectOS(userAgent);
const device = getDevice(screen, browser, os);
return { userAgent, browser, os, ip, country, device };
return { userAgent, browser, os, ip, country, device, region, city };
}

View file

@ -23,7 +23,10 @@ export async function getSession(req) {
throw new Error(`Invalid website: ${website_uuid}`);
}
const { userAgent, browser, os, ip, country, device } = await getClientInfo(req, payload);
const { userAgent, browser, os, ip, country, device, region, city } = await getClientInfo(
req,
payload,
);
const website = await getWebsiteByUuid(website_uuid);
@ -46,6 +49,8 @@ export async function getSession(req) {
language,
country,
device,
region,
city,
});
}