ip_block.rb 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  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 Paginable
  18. enum severity: {
  19. sign_up_requires_approval: 5000,
  20. sign_up_block: 5500,
  21. no_access: 9999,
  22. }
  23. validates :ip, :severity, presence: true
  24. validates :ip, uniqueness: true
  25. after_commit :reset_cache
  26. def to_log_human_identifier
  27. "#{ip}/#{ip.prefix}"
  28. end
  29. class << self
  30. def blocked?(remote_ip)
  31. blocked_ips_map = Rails.cache.fetch(CACHE_KEY) { FastIpMap.new(IpBlock.where(severity: :no_access).pluck(:ip)) }
  32. blocked_ips_map.include?(remote_ip)
  33. end
  34. end
  35. private
  36. def reset_cache
  37. Rails.cache.delete(CACHE_KEY)
  38. end
  39. end