Class: BetterAuth::RateLimiter
- Inherits:
-
Object
- Object
- BetterAuth::RateLimiter
- Defined in:
- lib/better_auth/rate_limiter.rb
Defined Under Namespace
Classes: MemoryStore
Instance Method Summary collapse
- #call(request, context, path) ⇒ Object
-
#initialize ⇒ RateLimiter
constructor
A new instance of RateLimiter.
Constructor Details
#initialize ⇒ RateLimiter
Returns a new instance of RateLimiter.
37 38 39 |
# File 'lib/better_auth/rate_limiter.rb', line 37 def initialize @memory_store = MemoryStore.new end |
Instance Method Details
#call(request, context, path) ⇒ Object
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 |
# File 'lib/better_auth/rate_limiter.rb', line 41 def call(request, context, path) config = context.rate_limit_config || {} return unless config[:enabled] ip = client_ip(request, context.) return unless ip rule = rate_limit_rule(request, context, config, path) return if rule == false window = rule[:window] || 10 max = rule[:max] || 100 key = rate_limit_key(ip, path) now = Time.now.to_f storage = storage_for(context, config) data = read_storage(storage, key) unless data write_storage(storage, key, rate_limit_data(key, 1, now), ttl: window, update: false) return end last_request = data.fetch(:last_request).to_f count = data.fetch(:count).to_i if should_rate_limit?(max.to_i, window.to_f, count, last_request, now) return rate_limit_response(retry_after(last_request, window.to_f, now)) end next_data = if now - last_request > window.to_f rate_limit_data(key, 1, now) else rate_limit_data(key, count + 1, now) end write_storage(storage, key, next_data, ttl: window, update: true) nil end |