Reputation: 1585
I'm building an app in node.js that allows users to upload documents using express and busboy. The user can upload multiple documents in one upload but is limited to a total file size of 20mb.
Is it possible to prevent a user from making multiple upload requests in a given amount of time? My concern is that someone could easily write a script to upload 20mb (the limit per upload) and repeat this 100x a minute or some large amount. It would be ideal to have a user only be able to upload once every 30 seconds or minute.
Upvotes: 5
Views: 8187
Reputation: 1204
I'd suggest rate-limiter-flexible package
const { RateLimiterMemory } = require('rate-limiter-
flexible');
const rateLimiter = new RateLimiterMemory(
{
points: 1,
duration: 30, // per 30 seconds
});
const rateLimiterMiddleware = (req, res, next) => {
const userId = getUserId();
// Consume 1 point for each action
rateLimiter.consume(userId) // or req.ip
.then(() => {
next();
})
.catch((rejRes) => {
res.status(429).send('Too Many Requests');
});
};
app.use('/upload', rateLimiterMiddleware);
Memory
works in current process memory only. There are also Cluster
, Mongo
and Redis
limiters for cluster and distributed apps
Upvotes: 2
Reputation: 511
If you'd like to rate-limit by IP, this module adds various configurations including the ability to apply the rule by path (example your upload function):
https://www.npmjs.com/package/express-rate-limit
Upvotes: 3
Reputation: 5225
You can use middleware to check it
app.use('/upload', upload-middleware, req-res-func)
upload-middleware
receive req
, calc user by cookies/session-id/etc and stored last upload time. If current request time and prev time is match then call next()
to forwarding request to req-res-function else call next(new Error('Upload error...'))
.Upvotes: 0
Reputation: 469
You could implement this in a number of ways, but I think probably the approach that makes the most sense to me is to have either a total upload limit per user, or some sort of date field that indicates when a specific user could upload a new set of files.
If you could provide some more details about your stack, I could probably help bang some code out.
Upvotes: 1