return 429 for too many requests instead of 421

This commit is contained in:
Albert Yi
2016-10-18 13:32:41 -07:00
parent b17cd5bffc
commit 2424f24fcd
4 changed files with 16 additions and 11 deletions

View File

@@ -1,5 +1,5 @@
module ApiLimiter
def idempotent?(method)
def self.idempotent?(method)
case method
when "POST", "PUT", "DELETE"
false
@@ -9,18 +9,18 @@ module ApiLimiter
end
end
def throttled?(ip_addr, http_method = "GET")
idempotent = idempotent?(http_method)
key = "api/#{ip_addr}/#{Time.now.hour}/#{idempotent}"
def throttled?(user_key, http_method = "GET")
idempotent = ApiLimiter.idempotent?(http_method)
key = "api/#{user_key}/#{Time.now.hour}/#{idempotent}"
MEMCACHE.fetch(key, 1.hour, :raw => true) {0}
MEMCACHE.incr(key).to_i > CurrentUser.user.api_hourly_limit(idempotent)
end
def remaining_hourly_limit(ip_addr, idempotent = true)
key = "api/#{ip_addr}/#{Time.now.hour}/#{idempotent}"
def remaining_hourly_limit(user_key, idempotent = true)
key = "api/#{user_key}/#{Time.now.hour}/#{idempotent}"
requests = MEMCACHE.fetch(key, 1.hour, :raw => true) {0}.to_i
CurrentUser.user.api_hourly_limit - requests
end
module_function :throttled?, :idempotent?, :remaining_hourly_limit
module_function :throttled?, :remaining_hourly_limit
end