1

my aim is 10 tires before lockout for 10 minutes. and if the user tries again and has 5 more failed attempts the lock time increase to 20 minutes. after 20 minutes, if the same user has 3 failed attempts lockout is 1 hour and finally, After 1 hour if the same user gets it wrong again, it locks them out for 24 hours.

how could I do that? I am using express-rate-limit and passing it as middleware

const rateLimit = require('express-rate-limit');

    const apiLimiter = rateLimit({
        windowMs: 10 * 60 * 1000,
        headers: true,
        max: 10,
    });
    
    module.exports = apiLimiter;

the first attempt working but to do the next attempt.

  • is there anyone to give some info? – freelanceing mindset Oct 09 '21 at 08:06
  • Your question is 30 minutes old. No reason to get impatient. – Tomalak Oct 09 '21 at 08:09
  • 1
    You need custom implementation using some storage. Perhaps redis store and write down your middleware to handle your business logic. – Abhik Chakraborty Oct 09 '21 at 08:10
  • 1
    Huh? You don't need redis for this. A simple `Map` between IP address and `{lastUnsuccessfulAttempt: Date; countUnsuccessfulAttempts: Number}` is enough to figure out when any IP is allowed to try again. – Tomalak Oct 09 '21 at 09:11
  • @Tomalak could you share the code, I am completely a beginner in this. – freelanceing mindset Oct 09 '21 at 10:14
  • 1
    @freelanceingmindset I'm not going to write it all down, but the idea is: When your app starts, create a map (`knownIPs = new Map();`) and every time someone uses your `/login` route and fails, check if they are already in the list (`knownIPs.has(clientIP)`) - if not, add them to the map (`knownIPs.set(clientIP, {lastUnsuccessfulAttempt: new Date(); countUnsuccessfulAttempts: 1})`). If they are already known, retrieve their stats (`knownIPs.get(clientIP)`), increase the counter and do the math. If they have hit a limit, send `429 Too Many Requests`. Delete their entry when the login succeded. – Tomalak Oct 09 '21 at 16:26
  • 1
    (That also means you don't really need `express-rate-limit`.) – Tomalak Oct 09 '21 at 16:27
  • @Tomalak you are amazing. I got enough idea. let me Implement. again thanks for your time. – freelanceing mindset Oct 09 '21 at 18:19
  • I hardly did anything. :) If you end up with code that works, post it as an answer below and ping me, I'll have a look and comment/upvote. – Tomalak Oct 09 '21 at 18:32
  • 1
    @freelanceingmindset You can use [rate-limiter-flexible](https://www.npmjs.com/package/rate-limiter-flexible). I would create 4 different limiters with options you need. [Here is simple example](https://github.com/animir/node-rate-limiter-flexible/wiki/Overall-example#minimal-protection-against-password-brute-force). – Animir Oct 17 '21 at 08:12

0 Answers0