ip_block.rb 1004 B

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