Skip to content

Commit

Permalink
Use rack-attack for api rate limit
Browse files Browse the repository at this point in the history
  • Loading branch information
andrew committed Jun 12, 2016
1 parent abd2d9c commit 1b9ff40
Show file tree
Hide file tree
Showing 5 changed files with 23 additions and 6 deletions.
3 changes: 2 additions & 1 deletion Gemfile
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,8 @@ gem 'mail', require: ['mail', 'mail/utilities', 'mail/parsers']
gem 'pictogram'
gem 'rails-timeago', github: 'librariesio/rails-timeago'
gem 'multi_fetch_fragments'
gem 'rack-attack'
gem 'rack-attack-rate-limit', require: 'rack/attack/rate-limit'
gem 'api-pagination'

group :development do
Expand Down Expand Up @@ -88,5 +90,4 @@ group :production do
gem 'bugsnag'
gem 'lograge'
gem 'rails_safe_tasks'
gem 'rack-throttle'
end
9 changes: 6 additions & 3 deletions Gemfile.lock
Original file line number Diff line number Diff line change
Expand Up @@ -255,15 +255,17 @@ GEM
quiet_assets (1.1.0)
railties (>= 3.1, < 5.0)
rack (1.6.4)
rack-attack (4.4.1)
rack
rack-attack-rate-limit (1.1.0)
rack
rack-canonical-host (0.2.2)
addressable (> 0, < 3)
rack (>= 1.0.0, < 3)
rack-protection (1.5.3)
rack
rack-test (0.6.3)
rack (>= 1.0)
rack-throttle (0.4.0)
rack (>= 1.0.0)
rack-timeout (0.4.2)
rails (4.2.6)
actionmailer (= 4.2.6)
Expand Down Expand Up @@ -461,8 +463,9 @@ DEPENDENCIES
premailer-rails
puma
quiet_assets
rack-attack
rack-attack-rate-limit
rack-canonical-host
rack-throttle
rack-timeout
rails (= 4.2.6)
rails-timeago!
Expand Down
3 changes: 3 additions & 0 deletions config/application.rb
Original file line number Diff line number Diff line change
Expand Up @@ -37,5 +37,8 @@ class Application < Rails::Application
Rails::Timeago.default_options :limit => proc { 60.days.ago }, :nojs => true

GC::Profiler.enable

config.middleware.use Rack::Attack
config.middleware.use Rack::Attack::RateLimit, throttle: ['api']
end
end
2 changes: 0 additions & 2 deletions config/environments/production.rb
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,4 @@
config.action_mailer.delivery_method = :smtp

config.lograge.enabled = true

config.middleware.use ApiRateLimit, :cache => Rails.cache, :key_prefix => :throttle, :max => 60
end
12 changes: 12 additions & 0 deletions config/initializers/rack-attack.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
limit_proc = proc do |req|
if req.params['api_key'].present?
key = ApiKey.active.find_by_access_token(req.params['api_key'])
key ? key.rate_limit : 30
else
30 # req/min for anonymous users
end
end

Rack::Attack.throttle('api', :limit => limit_proc, :period => 1.minute) do |req|
(req.params['api_key'] || req.ip) if req.path.match(/^\/api/i)
end

0 comments on commit 1b9ff40

Please sign in to comment.