diff --git a/lib/cartodb/middleware/rate-limit.js b/lib/cartodb/middleware/rate-limit.js index ee4c9c78..e2b94369 100644 --- a/lib/cartodb/middleware/rate-limit.js +++ b/lib/cartodb/middleware/rate-limit.js @@ -37,25 +37,35 @@ const ENDPOINT_KEY_REDIS = 'rate-limit:store:'; const USER_KEY_REDIS = 'rate-limit:status:'; -module.exports = function rateLimitMiddleware (metadataBackend) { +module.exports = function rateLimitMiddleware(metadataBackend) { return function rateLimit(req, res, next) { - + const user = 'cdb'; // const user = res.locals.user; const endpointGroup = getEndpointGroup(); const redisParams = [ getLuaScript(), - 3, + 2, getStoreKey(user, endpointGroup), // KEY[1] getStatusKey(user, endpointGroup) // KEY[2] ]; - metadataBackend.redisCmd(REDIS_DB, 'EVAL', redisParams, function(err, {isBloqued, limit, remaining, retry, reset}) { + metadataBackend.redisCmd(REDIS_DB, 'EVAL', redisParams, function(err, data) { if (err) { return next(err); } - + + if (!data || !Array.isArray(data)) { + return next(); + } + + const isBloqued = data[0]; + const limit = data[1]; + const remaining = data[2]; + const retry = data[3]; + const reset = data[4]; + res.set({ 'X-Rate-Limit-Limit': limit, 'X-Rate-Limit-Remaining': remaining, @@ -63,13 +73,13 @@ module.exports = function rateLimitMiddleware (metadataBackend) { 'X-Rate-Limit-Reset': reset }); - if(isBloqued) { + if (isBloqued) { const err = new Error('You are over the limits.'); err.http_status = 429; return next(err); } - - next(); + + return next(); }); }; }; @@ -85,7 +95,7 @@ function getEndpointGroup(currentEndpoint = null) { return ENDPOINTS_GROUPS_REDIS.ENDPOINT_8; } else { // get endpoint from route path - return ENDPOINTS_GROUPS_REDIS.ENDPOINT_8; + return ENDPOINTS_GROUPS_REDIS.ENDPOINT_8; } } @@ -109,8 +119,17 @@ function getStatusKey(user, endpointGroup) { } function getLuaScript() { - return ` - local userValues = redis.call("HGETALL", KEYS[1]) - return redis.call("CL.THROTTLE", KEYS[2], userValues[b], userValues[c], userValues[p]) + return ` + local limmits = {} + local limmitsArray = redis.call("HGETALL", KEYS[1]) + if table.getn(limmitsArray) == 4 then + limmits[limmitsArray[1]] = limmitsArray[2] + limmits[limmitsArray[3]] = limmitsArray[4] + limmits[limmitsArray[5]] = limmitsArray[6] + + return redis.call("CL.THROTTLE", KEYS[2], limmits['b'], limmits['c'], limmits['p']) + else + return nil + end `; }