Open2
rack-attackの導入にあたって
rack-attakの導入
gemの追加
/Gemfile
gem 'rack-attack'
gem "redis"
いつものを実行
$ bundle install
重要なパスに制限をかける
/config/initializers/rack_attack.rb
class Rack::Attack
Rack::Attack.cache.store = Redis.new
throttle('req/ip', limit: 300, period: 5.minutes) do |req|
req.ip unless req.path.start_with?('/assets')
end
throttle('logins/ip', limit: 5, period: 20.seconds) do |req|
if req.path == '/login' && req.post?
req.ip
end
end
throttle('signup/ip', limit: 5, period: 20.seconds) do |req|
if req.path == '/signup' && req.post?
req.ip
end
end
throttle('password_resets/ip', limit: 5, period: 20.seconds) do |req|
if req.path == '/password_resets' && req.post?
req.ip
end
end
end
/config/application.rb
require "rack/attack"
config.middleware.use Rack::Attack
/config/environments/development.rb
config.cache_store = :redis_cache_store, { url: 'redis://localhost:6379/1' }
Redisの操作あれこれ
Redis(レディス)とは、オープンソースのインメモリデータベースで、キーバリュー型(KVS)のNoSQL(ノーエスキューエル)データベースシステムです。データがメモリに保存されるため、高速なデータの読み書きが可能です。
だそうな
redisの導入
$ brew update
$ brew install redis
redisの起動や停止など
# サービスの起動
$ brew services start redis
# 起動中のサービスを表示
$ brew services list
# Redisの詳細情報
$ brew services info redis
# サービスの停止
$ brew services stop redis
redisに接続
# Redisに接続
$ redis-cli
# キー一覧を表示
> KEYS "*rack::attack*"
# 特定のキーの内容を確認
> GET "rack::attack:#{IPアドレス}"
確認
6回目以降は「Retry later」と返ってくる
# 10回POSTリクエストを送信
for i in {1..10}; do
curl -X POST http://localhost:3000/login
done
参考URL
参考になるかも
Railsのキャッシュストアをmemory_storeからredisにする話
Redisについてもちょっと出てくる