Home > Mobile >  How would I make the limit based if a user is logged in or not?
How would I make the limit based if a user is logged in or not?

Time:06-14

I am trying to use express and express-rate-limit to limit anonymous users download limit, the catch is that if the user object sent with the request is true, I want to disable the limit. How would I go about doing it? This is a code snippet:

const limiter = rateLimit({
    windowMs: 24 * 60 * 60 * 1000, // 24 hours
    max: if (user) { return 0 } else { return 10 }, //THIS IS THE LINE I NEED HELP WITH
    standardHeaders: true, // Return rate limit info in the `RateLimit-*` headers
    legacyHeaders: false, // Disable the `X-RateLimit-*` headers
})
app.use('/link', limiter)
app.post("/link", async (req, res) => {
  const premiumLink = req.body.downloadLink;
  const password = req.body.password;
  const user = req.body.user;
//do function here

CodePudding user response:

According to the express-rate-limit documentation, max can be either a number or a function.

max: number | function

The maximum number of connections to allow during the window before rate limiting the client.

Can be the limit itself as a number or a (sync/async) function that accepts the Express request and response objects and then returns a number.

Here is an example also provided in the documentation:

const isPremium = async (user) => {
    // ...
}

const limiter = rateLimit({
    // ...
    max: async (request, response) => {
        if (await isPremium(request.user)) return 10
        else return 5
    },
})

EDIT:

To better answer, your question, here is how you can achieve what you want to do:

const limiter = rateLimit({
        // ...
        max: async (request, response) => {
            if (request.body.user) return 0
            else return 10
        },
    })
  • Related