I'm trying to implement a feature such as the one given by Instagram; I'm talking about its "login activity" page. This is what I'm talking about:
Every time the user logs in, the device being in used is currently stored in the page. How would I go about that?
The current code that I have uses two libraries, one to find the ip.address() from the device being used and a second one that is supposed to help me to fetch the location data concerning the given ip address. Sadly, I'm unable to make it work. This is what the code looks like:
const ipLocation = require('ip-to-location')
const ip = require('ip')
const loc = await ipLocation.fetch(ip.address())
console.dir('Location', loc)
await User.findOneAndUpdate(
{ email: req.body.email },
{
$push: {
loginActivity: {
type: 'Point',
coordinates: [loc.longitude, loc.latitude],
// formattedAddress: loc[0].formattedAddress,
// street: loc[0].streetName,
city: loc.city.city,
state: loc.region_name,
zipcode: loc.zip_code,
country: loc.country_code,
},
},
}
)
Is there any alternate library to use? or can someone point me in the right direction to make this possible?
Santiago Trujillo
Well, if you can get the ip address of an user, you can try ipgeolocation.io
This is a free api that can give you latitude and longitude value of an ip address (and much more if you need).
More at documentation
You can give the IP2Location Node.js a try.
https://github.com/ip2location/ip2location-nodejs
It can either call a database file (free or paid) or call a web service.
For database, the code will look similar to the below:
const {IP2Location} = require("ip2location-nodejs");
let ip2location = new IP2Location();
ip2location.open("./DB25.BIN");
testip = ['8.8.8.8', '2404:6800:4001:c01::67'];
for (var x = 0; x < testip.length; x++) {
result = ip2location.getAll(testip[x]);
for (var key in result) {
console.log(key + ": " + result[key]);
}
console.log("--------------------------------------------------------------");
}
ip2location.close();
For web service, you can use the below example:
const {IP2LocationWebService} = require("ip2location-nodejs");
let ws = new IP2LocationWebService();
let ip = "8.8.8.8";
let apiKey = "YOUR_API_KEY";
let apiPackage = "WS25";
let useSSL = true;
// addon and lang to get more data and translation (leave both blank if you don't need them)
let addon = "continent,country,region,city,geotargeting,country_groupings,time_zone_info";
let lang = "fr";
ws.open(apiKey, apiPackage, useSSL);
ws.lookup(ip, addon, lang, (err, data) => {
if (!err) {
console.log(data);
ws.getCredit((err, data) => {
if (!err) {
console.log(data);
}
});
}
});