闭社主体 forked from https://github.com/tootsuite/mastodon
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.

36 lines
1.0 KiB

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