diff --git a/db/mysql/migrations/05_add_session_geo_columns/migration.sql b/db/mysql/migrations/05_add_session_geo_columns/migration.sql new file mode 100644 index 000000000..d976e2c8f --- /dev/null +++ b/db/mysql/migrations/05_add_session_geo_columns/migration.sql @@ -0,0 +1,3 @@ +-- AlterTable +ALTER TABLE `session` ADD COLUMN `city` VARCHAR(100) NULL, + ADD COLUMN `prefecture` VARCHAR(2) NULL; diff --git a/lib/request.js b/lib/request.js index 86e48f393..b69ab2cd7 100644 --- a/lib/request.js +++ b/lib/request.js @@ -2,7 +2,6 @@ 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 { @@ -56,17 +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']; - } - - // Ignore local ips - if (await isLocalhost(ip)) { - return; - } - +export async function getGeoInfo(ip) { // Database lookup if (!lookup) { lookup = await maxmind.open(path.resolve('node_modules/.geo/GeoLite2-City.mmdb')); @@ -74,20 +63,32 @@ export async function getCountry(req, ip) { const result = lookup.get(ip); - console.log(JSON.stringify(result)); + if (!result) { + return undefined; + } - return result?.country?.iso_code; + console.log(result.subdivisions); + + const city = result.city?.names.en; + const country = result.country?.iso_code; + const prefecture = result.subdivisions[0]?.iso_code; + + return { + city, + country, + prefecture, + }; } export async function getClientInfo(req, { screen }) { const userAgent = req.headers['user-agent']; const ip = getIpAddress(req); - const country = await getCountry(req, ip); + const { country, prefecture, city } = await getGeoInfo(ip); 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, prefecture, city, device }; } export function getJsonBody(req) { diff --git a/lib/session.js b/lib/session.js index 1ad4a693e..ba73f6f55 100644 --- a/lib/session.js +++ b/lib/session.js @@ -47,7 +47,10 @@ export async function getSession(req) { } // const ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress; - const { userAgent, browser, os, ip, country, device } = await getClientInfo(req, payload); + const { userAgent, browser, os, ip, country, prefecture, city, device } = await getClientInfo( + req, + payload, + ); let session_uuid = uuid(websiteId, hostname, ip, userAgent); if (process.env.CROSSDOMAIN_TRACKING) { @@ -80,6 +83,8 @@ export async function getSession(req) { screen, language, country, + prefecture, + city, device, ip, user_agent: userAgent,