|
| 1 | +# Parse Request Params In Rack::Attack Block |
| 2 | + |
| 3 | +The [`Rack::Attack` docs](https://github.com/rack/rack-attack) demonstrate a |
| 4 | +way of throttling requests based on a value in the request params. In this |
| 5 | +example, it is a Sign In endpoint and the `email` is the discriminating value. |
| 6 | + |
| 7 | +```ruby |
| 8 | +Rack::Attack.throttle('limit logins per email', limit: 6, period: 60) do |req| |
| 9 | + if req.path == '/login' && req.post? |
| 10 | + # Normalize the email, using the same logic as your authentication process, to |
| 11 | + # protect against rate limit bypasses. |
| 12 | + req.params['email'].to_s.downcase.gsub(/\s+/, "") |
| 13 | + end |
| 14 | +end |
| 15 | +``` |
| 16 | + |
| 17 | +Depending on the particulars of your middleware, it may be the case that |
| 18 | +`req.params` is empty. That is because the request params need to be manually |
| 19 | +parsed from the body of the request. |
| 20 | + |
| 21 | +An updated example that parses the params before accessing them could look like |
| 22 | +this: |
| 23 | + |
| 24 | +```ruby |
| 25 | +Rack::Attack.throttle('limit logins per email', limit: 6, period: 60) do |req| |
| 26 | + if req.path == '/login' && req.post? |
| 27 | + params = JSON.parse(req.body.string) |
| 28 | + |
| 29 | + # Normalize the email, using the same logic as your authentication process, to |
| 30 | + # protect against rate limit bypasses. |
| 31 | + params['email'].to_s.downcase.gsub(/\s+/, "") |
| 32 | + end |
| 33 | +end |
| 34 | +``` |
| 35 | + |
| 36 | +You can pry into the block or add some logging to ensure that you are getting |
| 37 | +at the POST params you are interested in. |
| 38 | + |
| 39 | +[source](https://github.com/rack/rack-attack/issues/189#issuecomment-744593703) |
0 commit comments