Skip to content

Instantly share code, notes, and snippets.

@ctrezevant

ctrezevant/banmi.js

Last active May 6, 2019
Embed
What would you like to do?
banmi.js is a simple module for implementing rate-limited lockouts
// banmi.js - 2.0
// A simple module for rate-limited lockouts
// (c) 2019 Charlton Trezevant
// MIT License
var Banmi = {};
// Initial ban length, which is used to calculate the scaling ban length per
// the total number of failed attempts
Banmi.initialBanLength = 120;
// Maximum number of failures allowed before enforcing a ban.
Banmi.maxFailThreshold = 2;
Banmi.bans = {};
Banmi.createBanRecord = function(user){
this.bans[user] = {
numFailuresRecorded: 0,
initialBanTime: new Date(),
lastFailTime: new Date()
};
};
Banmi.deleteBanRecord = function(user){
delete this.bans[user];
};
Banmi.banRecordExists = function(user){
if(this.bans[user]){
return true;
} else {
return null;
}
};
Banmi.numFailuresRecorded = function(user){
if(!this.banRecordExists(user))
return 0;
return this.bans[user].numFailuresRecorded;
};
Banmi.banTimeRemaining = function(user){
if(!this.banRecordExists(user))
return 0;
currentTime = new Date();
return this.bans[user].expireTime - currentTime;
};
Banmi.recordFailure = function(user){
if(!this.banRecordExists(user))
this.createBanRecord(user);
currentTime = new Date();
this.bans[user].lastFailTime = new Date();
this.bans[user].numFailuresRecorded++;
scaledBanLength = this.initialBanLength;
if(this.numFailuresRecorded(user) >= this.maxFailThreshold)
scaledBanLength = (Math.floor(this.bans[user].numFailuresRecorded / this.maxFailThreshold) * this.initialBanLength);
this.bans[user].expireTime = currentTime.setSeconds(currentTime.getSeconds() + scaledBanLength);
};
Banmi.isBanned = function(user){
if(!this.banRecordExists(user))
return false;
if(this.banTimeRemaining(user) < 0){
this.deleteBanRecord(user);
return false;
}
return this.numFailuresRecorded(user) >= this.maxFailThreshold;
};
module.exports = Banmi;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment