refactoring rate limit middleware
This commit is contained in:
parent
dfdd2b9043
commit
42e0e07c14
@ -19,51 +19,46 @@ const RATE_LIMIT_ENDPOINTS_GROUPS = {
|
||||
};
|
||||
|
||||
function rateLimitFn(userLimitsApi, endpointGroup = null) {
|
||||
if (isRateLimitEnabled(endpointGroup)) {
|
||||
return function rateLimitDisabledMiddleware(req, res, next) { next(); };
|
||||
}
|
||||
|
||||
return function rateLimitMiddleware(req, res, next) {
|
||||
if (!global.environment.enabledFeatures.rateLimitsEnabled) {
|
||||
return next();
|
||||
}
|
||||
|
||||
const user = res.locals.user;
|
||||
|
||||
if (!endpointGroup || !isRateLimitEnabledByEndpoint(endpointGroup)) {
|
||||
return next();
|
||||
}
|
||||
|
||||
userLimitsApi.getRateLimit(user, endpointGroup, function(err, rateLimit) {
|
||||
userLimitsApi.getRateLimit(res.locals.user, endpointGroup, function (err, rateLimit) {
|
||||
if (err) {
|
||||
return next(err);
|
||||
}
|
||||
|
||||
|
||||
if (!rateLimit) {
|
||||
return next();
|
||||
}
|
||||
|
||||
|
||||
const [isBlocked, limit, remaining, retry, reset] = rateLimit;
|
||||
|
||||
|
||||
res.set({
|
||||
'X-Rate-Limit-Limit': limit,
|
||||
'X-Rate-Limit-Remaining': remaining,
|
||||
'X-Rate-Limit-Retry-After': retry,
|
||||
'X-Rate-Limit-Reset': reset
|
||||
});
|
||||
|
||||
|
||||
if (isBlocked) {
|
||||
const rateLimitError = new Error('You are over the limits.');
|
||||
rateLimitError.http_status = 429;
|
||||
return next(rateLimitError);
|
||||
}
|
||||
|
||||
|
||||
return next();
|
||||
});
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
function isRateLimitEnabledByEndpoint(endpointGroup) {
|
||||
return global.environment.enabledFeatures.rateLimitsByEndpoint[endpointGroup] === true;
|
||||
function isRateLimitEnabled(endpointGroup) {
|
||||
return global.environment.enabledFeatures.rateLimitsEnabled &&
|
||||
endpointGroup &&
|
||||
global.environment.enabledFeatures.rateLimitsByEndpoint[endpointGroup];
|
||||
}
|
||||
|
||||
|
||||
module.exports = rateLimitFn;
|
||||
module.exports.RATE_LIMIT_ENDPOINTS_GROUPS = RATE_LIMIT_ENDPOINTS_GROUPS;
|
||||
|
Loading…
Reference in New Issue
Block a user