Updatweb
This commit is contained in:
66
backend/config/rateLimiter.js
Normal file
66
backend/config/rateLimiter.js
Normal file
@@ -0,0 +1,66 @@
|
||||
const rateLimit = require("express-rate-limit");
|
||||
const logger = require("./logger");
|
||||
const { RATE_LIMITS, HTTP_STATUS } = require("./constants");
|
||||
|
||||
const createRateLimiter = (config, limitType = "API") => {
|
||||
return rateLimit({
|
||||
windowMs: config.windowMs,
|
||||
max: config.max,
|
||||
skipSuccessfulRequests: config.skipSuccessfulRequests || false,
|
||||
message: {
|
||||
success: false,
|
||||
message: config.message,
|
||||
},
|
||||
standardHeaders: true,
|
||||
legacyHeaders: false,
|
||||
handler: (req, res) => {
|
||||
logger.warn(`${limitType} rate limit exceeded`, {
|
||||
ip: req.ip,
|
||||
path: req.path,
|
||||
email: req.body?.email,
|
||||
});
|
||||
res.status(HTTP_STATUS.TOO_MANY_REQUESTS).json({
|
||||
success: false,
|
||||
message: config.message,
|
||||
});
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
// General API rate limiter
|
||||
const apiLimiter = createRateLimiter(
|
||||
{
|
||||
windowMs:
|
||||
parseInt(process.env.RATE_LIMIT_WINDOW_MS) || RATE_LIMITS.API.windowMs,
|
||||
max: parseInt(process.env.RATE_LIMIT_MAX_REQUESTS) || RATE_LIMITS.API.max,
|
||||
message: "Too many requests from this IP, please try again later.",
|
||||
},
|
||||
"API"
|
||||
);
|
||||
|
||||
// Strict limiter for authentication endpoints
|
||||
const authLimiter = createRateLimiter(
|
||||
{
|
||||
windowMs: RATE_LIMITS.AUTH.windowMs,
|
||||
max: RATE_LIMITS.AUTH.max,
|
||||
skipSuccessfulRequests: true,
|
||||
message: "Too many login attempts, please try again after 15 minutes.",
|
||||
},
|
||||
"Auth"
|
||||
);
|
||||
|
||||
// File upload limiter
|
||||
const uploadLimiter = createRateLimiter(
|
||||
{
|
||||
windowMs: RATE_LIMITS.UPLOAD.windowMs,
|
||||
max: RATE_LIMITS.UPLOAD.max,
|
||||
message: "Upload limit reached, please try again later.",
|
||||
},
|
||||
"Upload"
|
||||
);
|
||||
|
||||
module.exports = {
|
||||
apiLimiter,
|
||||
authLimiter,
|
||||
uploadLimiter,
|
||||
};
|
||||
Reference in New Issue
Block a user