diff --git a/lib/detect.js b/lib/detect.js index 44eaa26a..74d95daa 100644 --- a/lib/detect.js +++ b/lib/detect.js @@ -27,7 +27,7 @@ export function getIpAddress(req) { return requestIp.getClientIp(req); } -export function getDevice(screen, browser, os) { +export function getDevice(screen, os) { if (!screen) return; const [width] = screen.split('x'); @@ -55,12 +55,7 @@ export function getDevice(screen, browser, os) { } } -export async function getCountry(req, ip) { - // Cloudflare - if (req.headers['cf-ipcountry']) { - return req.headers['cf-ipcountry']; - } - +export async function getLocation(ip) { // Ignore local ips if (await isLocalhost(ip)) { return; @@ -72,19 +67,27 @@ export async function getCountry(req, ip) { } const result = lookup.get(ip); + const country = result?.country?.iso_code ?? result?.registered_country?.iso_code; + const subdivision1 = result?.subdivisions[0].iso_code; + const subdivision2 = result?.subdivisions[1].iso_code; + const city = result?.city?.names?.en; - return result?.country?.iso_code; + return { country, subdivision1, subdivision2, city }; } export async function getClientInfo(req, { screen }) { + const location = await getLocation(ip); const userAgent = req.headers['user-agent']; const ip = getIpAddress(req); - const country = await getCountry(req, ip); + const country = location.country; + const subdivision1 = location.subdivision1; + const subdivision2 = location.subdivision2; + const city = location.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, subdivision1, subdivision2, city, device }; } export function getJsonBody(req) {