Class: BetterAuth::RateLimiter

Inherits:
Object
  • Object
show all
Defined in:
lib/better_auth/rate_limiter.rb

Defined Under Namespace

Classes: MemoryStore

Constant Summary collapse

MISSING_CLIENT_IP_WARNING =
"Rate limiting skipped: could not determine client IP address. " \
"Ensure your runtime forwards a trusted client IP header and configure `advanced.ipAddress.ipAddressHeaders` if needed."

Instance Method Summary collapse

Constructor Details

#initializeRateLimiter

Returns a new instance of RateLimiter.



40
41
42
43
# File 'lib/better_auth/rate_limiter.rb', line 40

def initialize
  @memory_store = MemoryStore.new
  @warned_missing_client_ip = false
end

Instance Method Details

#call(request, context, path) ⇒ Object



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
78
79
80
81
82
# File 'lib/better_auth/rate_limiter.rb', line 45

def call(request, context, path)
  config = context.rate_limit_config || {}
  return unless config[:enabled]

  ip = client_ip(request, context.options)
  warn_missing_client_ip(context) unless ip
  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