Last active
October 22, 2018 19:09
-
-
Save Floofies/41094f204073243e90a3c0b64e39e57b to your computer and use it in GitHub Desktop.
Slows down failed authentication attempts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const tryLimit = 10; // Number of tries allowed in try period | |
const tryPeriod = 1800000; // 30 Minutes until tries expire | |
const banPeriod = 1800000; // 30 Minutes until bans expire | |
const cooldownIndex = new Map(); // Index of authentication attempts and bans | |
// Takes Express request object to set ban/cooldown for the client | |
function setCooldown(req) { | |
const time = Date.now(); | |
const ip = getIP(req); | |
var cooldown = cooldownIndex.get(ip); | |
if ((typeof cooldown) === "undefined") { | |
cooldown = { | |
banUntil: 0, | |
lastTry: time, | |
tries: 0 | |
} | |
cooldownIndex.set(ip, cooldown); | |
} | |
cooldown.lastTry = time; | |
cooldown.tries++; | |
if (cooldown.tries >= tryLimit) cooldown.banUntil = time + banPeriod; | |
} | |
// Takes Express request object to check ban/cooldown of the client | |
// Returns True if the client is banned/cooling down | |
// Returns False if the client is NOT banned/cooling down | |
function checkCooldown(req) { | |
const time = Date.now(); | |
const cooldown = cooldownIndex.get(getIP(req)); | |
if ((typeof cooldown) === "undefined") return false; | |
if (cooldown.banUntil >= time) return true; | |
if (cooldown.banUntil !== 0 && cooldown.banUntil <= time) { | |
cooldown.banUntil = 0; | |
} | |
if (cooldown.lastTry >= time + tryPeriod) { | |
cooldown.tries = 0; | |
} | |
return false; | |
} | |
// Extracts client IP address from Express request object | |
function getIP(req) { | |
return req.headers['x-forwarded-for'] || req.connection.remoteAddress; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment