My nodejs express app serves a file that requires and loads css files, js files, etc. I have a logging middleware that requests the ip of a client and logs said ip (after checking it doesn't match to a json file of malicious ips). Because of the resources the server loads, when a person loads a page once, the server will log the ip many times.
logging middleware:
function checkIP(req, res, next) {
const clientIp = req.ip;
let allowCXN = true;
//read json file
fs.readFile("ip_info.json", "utf8", function (err, data) {
if (err) {
console.log(err);
} else {
var ip_info = JSON.parse(data);
for (let i = 0; i <= ip_info.ip_array.length - 1; i++) {
//console.log(ip_info.ip_array[i].ip);
if (clientIp == ip_info.ip_array[i].ip) {
allowCXN = false;
}
}
if (!allowCXN) {
res.end();
next();
}
} else {
console.log("Now serving ip:", "\x1b[33m", clientIp, "\x1b[37m");
next();
}
}
});
}
The ip is also being logged to a separate json file to keep track of who has connected, this fills up the json array with the same ip over and over, rather than just once. Is there a way to only log the ip once for one connection rather than for each connection to all other required files?
JSON file as requested:
{
"ip_array": [
{
"ip": "::ffff:198.23.172.233",
"unauth_joins": 0
},
{
"ip": "::ffff:64.62.197.182",
"unauth_joins": 0
},
{
"ip": "::ffff:23.148.145.235",
"unauth_joins": 0
},
{
"ip": "::1",
"unauth_joins": 0
},
{
"ip": "::ffff:127.0.0.1",
"unauth_joins": 0
}
]
}
You can do something like this:
const ip_info = JSON.parse(data);
for (let i = 0; i <= ip_info.ip_array.length - 1; i++) {
//console.log(ip_info.ip_array[i].ip);
const result = ip_info.ip_array.find(el => el.ip === 'userIPAddress');
if(result) {
// it means IP exist don't append in the data
} else {
// add to the array
}
}
There could be other ways too like adding IP address as key in the object or you can use Map DS from the JS native, it is efficient for searching.