Skip to content

Commit

Permalink
Implement country lookup by ip address
Browse files Browse the repository at this point in the history
  • Loading branch information
pfleidi committed Jan 31, 2016
1 parent 7c13ae3 commit b9d0943
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 2 deletions.
16 changes: 15 additions & 1 deletion lib/stats_extractor.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,22 @@
'use strict';

const url = require('url');
const geoip = require('geoip-lite');

const parseUserAgent = require('./user_agent_parser');

module.exports = function statsExtractor(req, res) {

function lookupCountry(ipAddress) {
let geo = geoip.lookup(ipAddress);

if (!geo) {
return 'unknown';
}

return geo.country;
}

function parseReferrer(referrer) {
if (referrer === 'unknown') {
return 'unknown';
Expand All @@ -20,13 +32,15 @@ module.exports = function statsExtractor(req, res) {
let userAgent = req.headers['user-agent'] || 'unknown';
let parsedUserAgent = parseUserAgent(userAgent);

let country = lookupCountry(req.ip);

return {
transfer_state: transferState,
transferred_bytes: sentBytes,
transfer_time: duration,
response_code: res.statusCode,
ip_address: req.ip,
country: '?',
country: country,
raw_user_agent: userAgent,
parsed_user_agent: parsedUserAgent,
raw_referrer: referrer,
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
"compression": "^1.6.0",
"errorhandler": "^1.4.2",
"express": "^4.13.3",
"geoip-lite": "^1.1.6",
"knex": "^0.9.0",
"lodash": "^3.10.1",
"mime-types": "^2.1.9",
Expand Down
25 changes: 24 additions & 1 deletion test/unit/stats_extractor_test.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ describe('statsExtractor', function () {
transfer_time: duration,
response_code: res.statusCode,
ip_address: req.ip,
country: '?',
country: 'unknown',
raw_user_agent: 'unknown',
parsed_user_agent: 'Other',
raw_referrer: 'unknown',
Expand Down Expand Up @@ -96,4 +96,27 @@ describe('statsExtractor', function () {
});
});

describe('with a german IP address', function () {
let ip = '193.99.144.80';

before(function () {
req.ip = ip;
});

after(function () {
req.ip = '127.0.0.1';
});

it('returns a response with the correctly parsed user agent', function () {
let stats = exctractStatistics('canceled', duration, sentBytes);

let expectedStats = _.assign({}, expectedStatsTemplate, {
ip_address: ip,
country: 'DE'
});

assert.deepEqual(stats, expectedStats);
});
});

});

0 comments on commit b9d0943

Please sign in to comment.