Created
October 23, 2018 11:43
-
-
Save greenlikeorange/a5f6a0b94239e3f0e5a564206649ceca to your computer and use it in GitHub Desktop.
Login attempt
This file contains 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 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