skip to Main Content

I am making a login system. I am trying to make user wait for 5 minutes when login attempts exceed 3 times, here is the User Model:

const UserSchema = new mongoose.Schema({
  // Other Model Schemas
  loginAttempts: { type: Number, default: 0 },
});

//Functions - Other functions above

// I am trying to make user wait for 5 minutes when login attempts exceed 3.
// But this is not working.

if (this.loginAttempts > 3) {
  setTimeout(() => {
    this.loginAttempts = 0;
    this.save();
  }, 1000 * 60 * 5);
}
if (this.loginAttempts >= 1) {
  setTimeout(() => {
    this.loginAttempts = 0;
    this.save();
  }, 1000 * 60 * 60 * 60 * 1);
}

const User = mongoose.model("User", UserSchema);
module.exports = User;

I was searching UserSchema.<parameter>, I was searching parameters or function (sorry I don’t know the exact term) which works like setTimeout() or setInterval() which checks on model and updates data like I have tried in above if(){} statement.

Can anyone suggest me a function in Schema which checks on intervals and update data as the time runs out just like, setTimeout function and setInterval function

2

Answers


  1. use rate-limiter-flexible!.
    I hope this package is helpful.

    Login or Signup to reply.
  2. You could do something like this:

    You can create a new schema called exceededUser and create an TTl (time to live)

    const ExceededUser = new mongoose.Schema({
      userId: { //your userId type },
      createdAt: { type: Date, default: Date.now(), expires: 60 * 5 },
    });
    

    What this expires do is, it delets itself after 5 min.

    When you login you first check if your userId is saved inside this exceededuser collection.

    1. If yes, return error that user needs to wait (that means the TTL of 5 min arent over an it didnt deleted itself yet).
    2. If no, then try to log in.
      1. If credentials are correct, reset loginAttempts to 0
      2. If credentials are not correct, increase loginAttempts by 1
        1. If loginAttempts is 3, then save "exceededUser" with your user ID, reset login attempts and return error that he exceeded.
        2. If loginAttempts is less then 3, just return normal error that credentials are wrong
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search