Skip to content

Commit

Permalink
throttle for ddos
Browse files Browse the repository at this point in the history
  • Loading branch information
wwahammy committed Jun 16, 2018
1 parent 2b48be4 commit a1a2861
Show file tree
Hide file tree
Showing 4 changed files with 22 additions and 0 deletions.
2 changes: 2 additions & 0 deletions Gemfile
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ gem 'responders', '~> 2.0'

gem 'rails_admin'

gem 'rack-attack'

gem 'rabl'

gem 'watir'
Expand Down
3 changes: 3 additions & 0 deletions Gemfile.lock
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,8 @@ GEM
rabl (0.13.1)
activesupport (>= 2.3.14)
rack (1.6.10)
rack-attack (5.2.0)
rack
rack-cors (1.0.2)
rack-pjax (1.0.0)
nokogiri (~> 1.5)
Expand Down Expand Up @@ -268,6 +270,7 @@ DEPENDENCIES
pg (= 0.20)
pry-rails
rabl
rack-attack
rack-cors
rails (= 4.2.10)
rails_12factor
Expand Down
1 change: 1 addition & 0 deletions config/application.rb
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ class Application < Rails::Application
# The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
# config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]
# config.i18n.default_locale = :de
config.middleware.use Rack::Attack
config.middleware.use Rack::Cors do
allow do
origins '*'
Expand Down
16 changes: 16 additions & 0 deletions config/initializers/rack_attack.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
Rack::Attack.throttle("requests by ip", limit: 5, period: 2) do |request|
request.ip
end

Rack::Attack.throttled_response = lambda do |env|
now = Time.now
match_data = env['rack.attack.match_data']

headers = {
'X-RateLimit-Limit' => match_data[:limit].to_s,
'X-RateLimit-Remaining' => '0',
'X-RateLimit-Reset' => (now + (match_data[:period] - now.to_i % match_data[:period])).to_s
}

[ 429, headers, ["Throttled\n"]]
end

0 comments on commit a1a2861

Please sign in to comment.