You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

43 lines
1.3 KiB

  1. # frozen_string_literal: true
  2. class Rack::Attack
  3. # Always allow requests from localhost
  4. # (blocklist & throttles are skipped)
  5. Rack::Attack.safelist('allow from localhost') do |req|
  6. # Requests are allowed if the return value is truthy
  7. '127.0.0.1' == req.ip || '::1' == req.ip
  8. end
  9. # Rate limits for the API
  10. throttle('api', limit: 300, period: 5.minutes) do |req|
  11. req.ip if req.path =~ /\A\/api\/v/
  12. end
  13. # Rate limit logins
  14. throttle('login', limit: 5, period: 5.minutes) do |req|
  15. req.ip if req.path == '/auth/sign_in' && req.post?
  16. end
  17. # Rate limit sign-ups
  18. throttle('register', limit: 5, period: 5.minutes) do |req|
  19. req.ip if req.path == '/auth' && req.post?
  20. end
  21. # Rate limit forgotten passwords
  22. throttle('reminder', limit: 5, period: 5.minutes) do |req|
  23. req.ip if req.path == '/auth/password' && req.post?
  24. end
  25. self.throttled_response = lambda do |env|
  26. now = Time.now.utc
  27. match_data = env['rack.attack.match_data']
  28. headers = {
  29. 'X-RateLimit-Limit' => match_data[:limit].to_s,
  30. 'X-RateLimit-Remaining' => '0',
  31. 'X-RateLimit-Reset' => (now + (match_data[:period] - now.to_i % match_data[:period])).iso8601(6),
  32. }
  33. [429, headers, [{ error: I18n.t('errors.429') }.to_json]]
  34. end
  35. end