2024-02-25 12:15:55 -05:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
2020-10-24 08:47:20 -04:00
|
|
|
class RateLimiter
|
|
|
|
def self.check_limit(key, max_attempts, lockout_time = 1.minute)
|
2022-11-29 13:14:09 -05:00
|
|
|
return true if Cache.fetch("#{key}:lockout")
|
2020-10-24 08:47:20 -04:00
|
|
|
|
2022-11-29 13:14:09 -05:00
|
|
|
attempts = Cache.fetch(key) || 0
|
2020-10-24 08:47:20 -04:00
|
|
|
if attempts >= max_attempts
|
2023-05-19 16:53:20 -04:00
|
|
|
Cache.write("#{key}:lockout", true, expires_in: lockout_time)
|
2020-10-24 08:47:20 -04:00
|
|
|
reset_limit(key)
|
|
|
|
return true
|
|
|
|
end
|
|
|
|
false
|
|
|
|
end
|
|
|
|
|
|
|
|
def self.hit(key, time_period = 1.minute)
|
2022-11-29 13:14:09 -05:00
|
|
|
value = Cache.fetch(key) || 0
|
2023-05-19 16:53:20 -04:00
|
|
|
Cache.write(key, value.to_i + 1, expires_in: time_period)
|
2022-11-29 13:14:09 -05:00
|
|
|
value.to_i + 1
|
2020-10-24 08:47:20 -04:00
|
|
|
end
|
|
|
|
|
|
|
|
def self.reset_limit(key)
|
|
|
|
Cache.delete(key)
|
|
|
|
end
|
|
|
|
end
|