mirror of
https://github.com/umami-software/umami.git
synced 2026-02-04 04:37:11 +01:00
Added country lookup for ip.
This commit is contained in:
parent
e6908d9e04
commit
822d46a2e0
6 changed files with 125 additions and 11 deletions
36
lib/utils.js
36
lib/utils.js
|
|
@ -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 {
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue