diff --git a/Gemfile b/Gemfile index ea0d679e..a7c08bbc 100644 --- a/Gemfile +++ b/Gemfile @@ -62,6 +62,8 @@ gem "rest-client", "~> 1.6.7" gem "rails-i18n" +gem 'rack-attack', '~> 2.2.0' + # Needed for the new asset pipeline group :assets do diff --git a/Gemfile.lock b/Gemfile.lock index a24e2b7e..431db003 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -190,6 +190,8 @@ GEM dye (>= 0.1.1) yard (>= 0.6.3) rack (1.4.5) + rack-attack (2.2.0) + rack rack-cache (1.2) rack (>= 0.4) rack-fiber_pool (0.9.2) @@ -325,6 +327,7 @@ DEPENDENCIES openneo-auth-signatory (~> 0.1.0) parallel (~> 0.5.17) patron (~> 0.4.18) + rack-attack (~> 2.2.0) rack-fiber_pool rails (= 3.2.13) rails-i18n diff --git a/config/application.rb b/config/application.rb index 7c1689c2..80cb0467 100644 --- a/config/application.rb +++ b/config/application.rb @@ -50,6 +50,8 @@ module OpenneoImpressItems config.assets.paths << Rails.root.join('app', 'assets', 'fonts') config.assets.precompile << '*.js' config.assets.initialize_on_precompile = false + + config.middleware.insert_after ActionDispatch::Flash, Rack::Attack end end diff --git a/config/initializers/attack.rb b/config/initializers/attack.rb new file mode 100644 index 00000000..e402e99e --- /dev/null +++ b/config/initializers/attack.rb @@ -0,0 +1,23 @@ +Rack::Attack.throttle('pets/ip', limit: 10, period: 1.minute) do |req| + Rails.logger.debug "Pets hit? #{req.path.inspect} #{req.ip.inspect}" + req.ip if req.path.start_with?('/pets/load') +end + +PETS_THROTTLE_MESSAGE = "We've received a lot of pet names from you " + + "recently, so we're giving our servers a break. Try " + + "again in a minute or so. Thanks!" + +Rack::Attack.throttled_response = lambda do |env| + if env['rack.attack.matched'] == 'pets/ip' + req = ActionDispatch::Request.new(env) + if req.path.end_with?('.json') + [503, {}, [PETS_THROTTLE_MESSAGE]] + else + flash = req.flash + flash[:warning] = PETS_THROTTLE_MESSAGE + [302, {"Location" => "/"}, [PETS_THROTTLE_MESSAGE]] + end + else + [503, {}, ["Retry later"]] + end +end \ No newline at end of file diff --git a/vendor/cache/rack-attack-2.2.0.gem b/vendor/cache/rack-attack-2.2.0.gem new file mode 100644 index 00000000..9ed7f14e Binary files /dev/null and b/vendor/cache/rack-attack-2.2.0.gem differ