Skip to content

Commit

Permalink
Add rack-attack and some API usage limits
Browse files Browse the repository at this point in the history
  • Loading branch information
alinetskyi authored and Louis committed Oct 31, 2018
1 parent a0df95d commit 09844d2
Show file tree
Hide file tree
Showing 5 changed files with 33 additions and 1 deletion.
1 change: 1 addition & 0 deletions Gemfile
Expand Up @@ -36,6 +36,7 @@ gem 'public_suffix'
gem 'devise-security'
gem 'devise-pwned_password'
gem 'email_validator', require: 'email_validator/strict'
gem 'rack-attack', '~> 5.4.1'

gem 'doorkeeper-jwt', git: 'https://github.com/rubykube/doorkeeper-jwt.git'
gem 'memoist', '~> 0.16'
Expand Down
3 changes: 3 additions & 0 deletions Gemfile.lock
Expand Up @@ -274,6 +274,8 @@ GEM
rack (2.0.5)
rack-accept (0.4.5)
rack (>= 0.4)
rack-attack (5.4.1)
rack (>= 1.0, < 3)
rack-test (1.1.0)
rack (>= 1.0, < 3)
rails (5.2.1)
Expand Down Expand Up @@ -462,6 +464,7 @@ DEPENDENCIES
pry-byebug (~> 3.5)
public_suffix
puma (~> 3.7)
rack-attack (~> 5.4.1)
rails (~> 5.2.1)
rails-controller-testing
recaptcha
Expand Down
2 changes: 1 addition & 1 deletion config/application.rb
Expand Up @@ -22,7 +22,7 @@ class Application < Rails::Application
config.generators.tests = false
config.generators.test_framework :rspec
config.eager_load_paths += %W[#{config.root}/lib]

config.middleware.use Rack::Attack
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
Expand Down
3 changes: 3 additions & 0 deletions config/environments/test.rb
Expand Up @@ -45,6 +45,9 @@
# Print deprecation notices to the stderr.
config.active_support.deprecation = :stderr

# Delete rack-attack for test environment
config.middleware.delete Rack::Attack

# Raises error for missing translations
# config.action_view.raise_on_missing_translations = true
end
25 changes: 25 additions & 0 deletions config/initializers/rack_attack.rb
@@ -0,0 +1,25 @@
class Rack::Attack

Rack::Attack.cache.store = ActiveSupport::Cache::MemoryStore.new

phone_verif_limit = ENV.fetch('PHONE_VERIFICATION_RATE_LIMIT', 5)

# Limit nubmer of calls from ip per second
throttle('logins/ip',limit: 10, period: 1.seconds) do |req|
req.ip
end

# Limit number of phone verification calls per number
throttle('phone_verification/number', limit: phone_verif_limit , period: 24.hours) do |req|
case req.path
when '/phones/verification'
req.body.string
when '/phones'
req.cookies['_barong_session']
end
end

# TODO: Limit by account id not by barong session

end

0 comments on commit 09844d2

Please sign in to comment.