email_domain_block.rb 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. # frozen_string_literal: true
  2. # == Schema Information
  3. #
  4. # Table name: email_domain_blocks
  5. #
  6. # id :bigint(8) not null, primary key
  7. # domain :string default(""), not null
  8. # created_at :datetime not null
  9. # updated_at :datetime not null
  10. # parent_id :bigint(8)
  11. #
  12. class EmailDomainBlock < ApplicationRecord
  13. self.ignored_columns = %w(
  14. ips
  15. last_refresh_at
  16. )
  17. include DomainNormalizable
  18. belongs_to :parent, class_name: 'EmailDomainBlock', optional: true
  19. has_many :children, class_name: 'EmailDomainBlock', foreign_key: :parent_id, inverse_of: :parent, dependent: :destroy
  20. validates :domain, presence: true, uniqueness: true, domain: true
  21. # Used for adding multiple blocks at once
  22. attr_accessor :other_domains
  23. def history
  24. @history ||= Trends::History.new('email_domain_blocks', id)
  25. end
  26. def self.block?(domain_or_domains, attempt_ip: nil)
  27. domains = Array(domain_or_domains).map do |str|
  28. domain = begin
  29. if str.include?('@')
  30. str.split('@', 2).last
  31. else
  32. str
  33. end
  34. end
  35. TagManager.instance.normalize_domain(domain) if domain.present?
  36. rescue Addressable::URI::InvalidURIError
  37. nil
  38. end
  39. # If some of the inputs passed in are invalid, we definitely want to
  40. # block the attempt, but we also want to register hits against any
  41. # other valid matches
  42. blocked = domains.any?(&:nil?)
  43. where(domain: domains).find_each do |block|
  44. blocked = true
  45. block.history.add(attempt_ip) if attempt_ip.present?
  46. end
  47. blocked
  48. end
  49. end