field.rb 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. # frozen_string_literal: true
  2. class Account::Field < ActiveModelSerializers::Model
  3. MAX_CHARACTERS_LOCAL = 255
  4. MAX_CHARACTERS_COMPAT = 2_047
  5. ACCEPTED_SCHEMES = %w(https).freeze
  6. attributes :name, :value, :verified_at, :account
  7. def initialize(account, attributes)
  8. # Keeping this as reference allows us to update the field on the account
  9. # from methods in this class, so that changes can be saved.
  10. @original_field = attributes
  11. @account = account
  12. super(
  13. name: sanitize(attributes['name']),
  14. value: sanitize(attributes['value']),
  15. verified_at: attributes['verified_at']&.to_datetime,
  16. )
  17. end
  18. def verified?
  19. verified_at.present?
  20. end
  21. def value_for_verification
  22. @value_for_verification ||= begin
  23. if account.local?
  24. value
  25. else
  26. extract_url_from_html
  27. end
  28. end
  29. end
  30. def verifiable?
  31. return false if value_for_verification.blank?
  32. # This is slower than checking through a regular expression, but we
  33. # need to confirm that it's not an IDN domain.
  34. parsed_url = Addressable::URI.parse(value_for_verification)
  35. ACCEPTED_SCHEMES.include?(parsed_url.scheme) &&
  36. parsed_url.user.nil? &&
  37. parsed_url.password.nil? &&
  38. parsed_url.host.present? &&
  39. parsed_url.normalized_host == parsed_url.host
  40. rescue Addressable::URI::InvalidURIError, IDN::Idna::IdnaError
  41. false
  42. end
  43. def requires_verification?
  44. !verified? && verifiable?
  45. end
  46. def mark_verified!
  47. @original_field['verified_at'] = self.verified_at = Time.now.utc
  48. end
  49. def to_h
  50. { name: name, value: value, verified_at: verified_at }
  51. end
  52. private
  53. def sanitize(str)
  54. str.strip[0, character_limit]
  55. end
  56. def character_limit
  57. account.local? ? MAX_CHARACTERS_LOCAL : MAX_CHARACTERS_COMPAT
  58. end
  59. def extract_url_from_html
  60. doc = Nokogiri::HTML(value).at_xpath('//body')
  61. return if doc.children.size > 1
  62. element = doc.children.first
  63. return if element.name != 'a' || element['href'] != element.text
  64. element['href']
  65. end
  66. end