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

3.3k Views Asked by At

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?

1

There are 1 best solutions below

1
On BEST ANSWER

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