Complete the code to set a rate limit of 5 requests per minute using Rack::Attack.
Rack::Attack.throttle('req/ip', limit: 5, period: 60) do |req| req.[1] end
The ip method returns the client's IP address, which is commonly used to identify unique requesters for rate limiting.
Complete the code to block requests from a specific IP address '192.168.1.1'.
Rack::Attack.blocklist('block 192.168.1.1') do |req| req.[1] == '192.168.1.1' end
The ip method returns the IP address of the request, which you compare to the blocked IP.
Fix the error in the throttle block to correctly count requests per user ID.
Rack::Attack.throttle('req/user', limit: 10, period: 60) do |req| req.env['warden'].user.[1] end
The id uniquely identifies the user, which is needed to count requests per user.
Fill both blanks to create a custom response for throttled requests with status 429 and a JSON message.
Rack::Attack.throttled_response = lambda do |env| [[1], { 'Content-Type' => 'application/json' }, [{ error: [2] }.to_json]] end
Status code 429 means too many requests. The JSON message should explain the error clearly.
Fill all three blanks to define a throttle that limits POST requests to '/login' to 5 per minute per IP.
Rack::Attack.throttle('logins/ip', limit: [1], period: [2]) do |req| req.[3] if req.path == '/login' && req.post? end
The limit is 5 requests, period is 60 seconds (1 minute), and the IP address identifies the user.