Permalink
Browse files

switched to using maxmind databases for geoip lookups

  • Loading branch information...
omgimanerd committed Aug 15, 2017
1 parent 12d3841 commit 6534acf857c77a0792e5b08004e814d1d16132f6
Showing with 46 additions and 11 deletions.
  1. +1 −0 .gitignore
  2. +1 −1 package.json
  3. +33 −6 server/analytics.js
  4. +11 −4 yarn.lock
View
@@ -1,4 +1,5 @@
/dist
/node_modules
*.log
*.mmdb
setup
View
@@ -17,8 +17,8 @@
"express": "^4.15.3",
"express-winston": "^2.4.0",
"file-loader": "^0.11.2",
"geoip-native": "^0.0.8",
"jquery": "^3.2.1",
"maxmind": "^2.2.0",
"moment": "^2.18.1",
"node-sass": "^4.5.3",
"nouislider": "^10.0.0",
View
@@ -7,7 +7,7 @@
const Promise = require('bluebird')
const fs = Promise.promisifyAll(require('fs'))
const geoip = require('geoip-native')
const maxmind = require('maxmind')
const ServerError = require('./ServerError')
@@ -17,8 +17,26 @@ const ServerError = require('./ServerError')
*/
const CACHE_KEEP_TIME = 3600000
/**
* Name of the MMDB file, which is assumed to be in the server directory.
* @type {string}
*/
const MMDB_FILE = 'server/GeoLite2-City.mmdb'
const cache = {}
// eslint-disable-next-line no-sync
const maxmindDb = maxmind.openSync(MMDB_FILE)
/**
* Looks up an IP address in the maxmind database.
* @param {string} ip The IP address to look up.
* @return {Object}
*/
const lookupIp = ip => {
return maxmindDb.get(ip)
}
/**
* Fetches analytics on recent site traffic and returns a Promise
* @param {string} file file to fetch analytics data from.
@@ -37,16 +55,25 @@ const get = file => {
return fs.readFileAsync(file, 'utf8').then(data => {
const analytics = data.trim().split('\n').map(entry => {
const json = JSON.parse(entry)
json.country = geoip.lookup(json.ip).name
/*
* Iterate through the entries and get a country name for each
* IP address.
*/
const locationData = lookupIp(json.ip)
json.country = 'unknown'
if (locationData) {
json.country = locationData.country.names.en
}
return json
})
cache[file] = {}
cache[file].analytics = analytics
cache[file].expires = currentTime + CACHE_KEEP_TIME
cache[file] = {
analytics: analytics,
expires: currentTime + CACHE_KEEP_TIME
}
return analytics
}).catch(error => {
throw new ServerError('AnalyticsError', error)
})
}
module.exports = exports = { get }
module.exports = exports = { lookupIp, get }
View

Some generated files are not rendered by default. Learn more.

Oops, something went wrong.

0 comments on commit 6534acf

Please sign in to comment.