UNPKG

dos-protect

Version:

DOS Protector for NPM

96 lines (91 loc) 2.62 kB
var listCache = []; var rateLimit = 5; //5 MiliSecond var _ = require('lodash'); var moment = require('moment'); function authenticateV1(ip) { var found = listCache.filter((res) => { return res.ip == ip; }) var currentTime = Date.now(); var res = {}; if (found.length < 1) { listCache.push({ "ip": ip, "timestmp": currentTime }); res.status = "200"; res.message = "IP Validated"; } else { var diff = (currentTime) - (found[0].timestmp); if (diff < rateLimit) { res.status = "429"; res.message = "Too Many Request from Same Address"; } else { res.status = "200"; res.message = "IP Validated"; } } return (res); } function authenticateV2(ip, maxHits, timeAllowed) { maxHits = validateValue(maxHits) ? maxHits : 5; timeAllowed = validateValue(timeAllowed) ? timeAllowed : 5; var res = {}; var isValidated = true; var ipFound = _.find(listCache, function (o) { return ( o.ip == ip ) }); if (validateValue(ipFound)) { if (moment().format("X") - ipFound.timestmp > timeAllowed) { isValidated = true listCache = _.remove(listCache, function (n) { return n.ip != ip; }); listCache.push({ "ip": ip, "timestmp": moment().format("X"), count: 1 }) } else { var index = _.findIndex(listCache, { ip: ip }); listCache[index]["count"] = parseInt(listCache[index]["count"]) + 1; if (ipFound.count <= maxHits) { isValidated = true } else { isValidated = false; } } } else { isValidated = true listCache.push({ "ip": ip, "timestmp": moment().format("X"), count: 1 }) } if (isValidated) { res.status = "200"; res.ip = ip; res.message = "IP Validated"; } else { res.status = "429"; res.ip = ip; res.message = "Too Many Request from Same Address"; } return (res); } module.exports = { authenticateV1, authenticateV2 }; function validateValue(val) { if (!val || val == undefined || val == null || val == 'undefined' || val == 'null' || val == "" || val.length < 1 || val == NaN || val == 'NaN' || val == 'false' || val == false) { return (false); } else { return (true); } }