ip_block.rb 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. # frozen_string_literal: true
  2. # == Schema Information
  3. #
  4. # Table name: ip_blocks
  5. #
  6. # id :bigint(8) not null, primary key
  7. # created_at :datetime not null
  8. # updated_at :datetime not null
  9. # expires_at :datetime
  10. # ip :inet default(#<IPAddr: IPv4:0.0.0.0/255.255.255.255>), not null
  11. # severity :integer default(NULL), not null
  12. # comment :text default(""), not null
  13. #
  14. class IpBlock < ApplicationRecord
  15. CACHE_KEY = 'blocked_ips'
  16. include Expireable
  17. include InetContainer
  18. include Paginable
  19. enum :severity, {
  20. sign_up_requires_approval: 5000,
  21. sign_up_block: 5500,
  22. no_access: 9999,
  23. }, prefix: true
  24. validates :ip, :severity, presence: true
  25. validates :ip, uniqueness: true
  26. after_commit :reset_cache
  27. def to_log_human_identifier
  28. "#{ip}/#{ip.prefix}"
  29. end
  30. class << self
  31. def blocked?(remote_ip)
  32. blocked_ips_map.include?(remote_ip)
  33. end
  34. private
  35. def blocked_ips_map
  36. Rails.cache.fetch(CACHE_KEY) { FastIpMap.new(severity_no_access.pluck(:ip)) }
  37. end
  38. end
  39. private
  40. def reset_cache
  41. Rails.cache.delete(CACHE_KEY)
  42. end
  43. end