-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathindex.js
More file actions
32 lines (29 loc) · 1019 Bytes
/
index.js
File metadata and controls
32 lines (29 loc) · 1019 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
var geoip = require('geoip-lite');
module.exports = function () {
var getIpInfo = function (ip) {
// IPV6 addresses can include IPV4 addresses
// So req.ip can be '::ffff:86.3.182.58'
// However geoip-lite returns null for these
if (ip.includes('::ffff:')) {
ip = ip.split(':').reverse()[0]
}
var lookedUpIP = geoip.lookup(ip);
if ((ip === '127.0.0.1' || ip === '::1')) {
return {error:"This won't work on localhost"}
}
if (!lookedUpIP){
return { error: "Error occured while trying to process the information" }
}
return lookedUpIP;
}
var getIpInfoMiddleware = function (req, res, next) {
var xForwardedFor = (req.headers['x-forwarded-for'] || '').replace(/:\d+$/, '');
var ip = xForwardedFor || req.connection.remoteAddress;
req.ipInfo = { ip, ...getIpInfo(ip) };
next();
}
return {
getIpInfoMiddleware,
getIpInfo,
}
}