Throttle # of requests per user (with rack-attack & devise)
Asked Answered
M

1

13

I'm using https://github.com/kickstarter/rack-attack/#throttles to throttle request to certain url's.

Rack-attack docs show how to throttle by request IP or request parameters, but what I'd like to do is throttle requests per user. So no matter the IP, user should be able to make no more than n request in certain time frame.

We use devise for authentication and I cannot think of a simple way to uniquely identify users based on request.

Should I store user id in the session/cookie? Maybe a uniq hash? What's you opinion on the best way to go about doing that?

Misreport answered 30/7, 2015 at 8:52 Comment(0)
M
22

Figured it out. Devise already stores user id in the session. The code would look something like:

Rack::Attack.throttle('something', limit: 6, period: 60.seconds) do |req|
  req.env['rack.session']["warden.user.user.key"][0][0] if some_condition?
end
Misreport answered 30/7, 2015 at 9:4 Comment(1)
ddgd, could you tell me how to check the request content type e.g. application/javascript or text/html in the throttled_response method? #36305493Lapointe

© 2022 - 2024 — McMap. All rights reserved.