Skip to content

Instantly share code, notes, and snippets.

@greenlikeorange
Created October 23, 2018 11:43
Show Gist options
  • Save greenlikeorange/a5f6a0b94239e3f0e5a564206649ceca to your computer and use it in GitHub Desktop.
Save greenlikeorange/a5f6a0b94239e3f0e5a564206649ceca to your computer and use it in GitHub Desktop.
Login attempt
const MAX_TRY_COUNT = 5;
const TIME_OF_DENINE = 10 * 60 * 1000; // 10 minutes
const loginAttempts = {};
function createLoginAttemptIfNotExits(username) {
if (loginAttempts[username]) {
loginAttempts[username] = { try: 0, lastTry: 0 };
}
}
function resetAttempt(username) {
createLoginAttemptIfNotExits(username);
loginAttempts[username].try = 0;
loginAttempts[username].lastTry = 0;
}
function onLoginFail(username) {
createLoginAttemptIfNotExits(username);
loginAttempts[username].try += 1;
loginAttempts[username].lastTry = Date.now();
}
function onLoginSuccess(username) {
resetAttempt(username);
}
function isValidLoginRequest(username) {
const attempt = loginAttempts[username];
if (attempt && attempt.try >= MAX_TRY_COUNT) {
if (Date.now() - attempt.lastTry < TIME_OF_DENINE) {
return false;
} else {
resetAttempt(username);
return true;
}
}
return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment