How to limit user login attempts Angular.js (typescript)

3.6k Views Asked by At

My code limits the user login attempts but when the page is refreshed it resets the user count.

login() {
/* Only attempt login if user has less than 5 login attempts */
if (this.failedAttempts < 4) {


  this.auth.login(this.credentials).subscribe(() => {
    this.router.navigateByUrl('/');
    this.alert.success('Welcome! Thanks for logging in!');
  }, (err) => {
    this.failedAttempts++;
    console.error(err);
    this.alert.error('Login failed. Invalid email or password.');
  });
  /*If user reaches 5 failed attempts refresh number of failed attempts after 5 minutes and disable submit button*/
} else if (this.failedAttempts < 4) {
} else {
  /*increments number of times locked out */
  this.numLockedOut++;

  this.alert.error('Login failed. Invalid email or password. Locked out for ' + (this.numLockedOut * 300000) / 60000 + ' minutes');
  this.btnDisable = true;
  setTimeout(() => this.failedAttempts = 0, this.numLockedOut * 300000);
  setTimeout(() => this.btnDisable = false, this.numLockedOut * 300000);
}

}

How do I settimeout() without restarting the clock on page refresh?

2

There are 2 best solutions below

1
dave On

You almost definitely want to be recording failed login attempts on your server, rather than in the browser. Even if you get this code working, it would be trivial for someone to edit the Javascript in their browser and make as many login attempts as they want.

If you did have your server recording attempted logins for a given username, then the response from the server could tell you that the number of login attempts has exceeded the allowed amount and the angular code could simply relay that information to the user. This would also solve your problem of the attempt count not persisting between page visits. :)

0
lkamal On

I suggest you to implement this via login API (REST API).

When the UI sends a login request to the API, it can track the number of failure login attempts.

// maintain login failure count against username; maybe in a database or in a Map
// loginFailureCount(username, count, expiryTime)

if (loginIsBlocked(username) {
   return login-response-with-login-blocked-message
} 

if (loginfailure) {
   incrementLoginFailureCount(username, expiryTime);
} else {
   resetLoginFailureCount(username);
}
// send the loginFailureCount(username) in the API response if login failed

Now the API supports failure count as well as locked message.

// In the UI show the failure count or locked message if the login response is a failure