2018-10-11 15:48:06 +08:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
2018-11-07 22:43:44 +08:00
|
|
|
return unless Rails.env.production?
|
|
|
|
|
2019-11-26 22:09:40 +08:00
|
|
|
return if Rails.configuration.x.core_api_rate_limit.zero?
|
2018-12-17 22:15:56 +08:00
|
|
|
|
2018-10-11 15:48:06 +08:00
|
|
|
Rack::Attack.throttle('api requests by ip',
|
2019-11-26 22:09:40 +08:00
|
|
|
limit: Rails.configuration.x.core_api_rate_limit,
|
2018-10-11 15:48:06 +08:00
|
|
|
period: 60) do |request|
|
2018-11-07 22:43:44 +08:00
|
|
|
request.ip if request.path.match?(%r{^\/api\/})
|
2018-10-11 15:48:06 +08:00
|
|
|
end
|
|
|
|
|
|
|
|
Rack::Attack.throttled_response = lambda do |env|
|
|
|
|
match_data = env['rack.attack.match_data']
|
|
|
|
now = match_data[:epoch_time]
|
|
|
|
|
|
|
|
headers = {
|
|
|
|
'RateLimit-Limit' => match_data[:limit].to_s,
|
|
|
|
'RateLimit-Remaining' => '0',
|
|
|
|
'RateLimit-Reset' => (
|
|
|
|
now + (match_data[:period] - now % match_data[:period])
|
|
|
|
).to_s
|
|
|
|
}
|
|
|
|
|
|
|
|
[429, headers, ["Throttled\n"]]
|
|
|
|
end
|