Sha256: 47e534791b1855c36199f453497ab3b081e9b0582bffe3eba65e4e0b5e09b137

Contents?: true

Size: 1.2 KB

Versions: 56

Compression:

Stored size: 1.2 KB

Contents

require "govspeak"

class SafeHtml < ActiveModel::Validator
  def validate(record)
    record.changes.each do |field_name, (old_value, new_value)|
      check_struct(record, field_name, new_value)
    end
  end

  def check_struct(record, field_name, value)
    if value.respond_to?(:values) # e.g. Hash
      value.values.each { |entry| check_struct(record, field_name, entry) }
    elsif value.respond_to?(:each) # e.g. Array
      value.each { |entry| check_struct(record, field_name, entry) }
    elsif value.is_a?(String)
      check_string(record, field_name, value)
    end
  end

  def check_string(record, field_name, string)
    if govspeak_fields(record).include?(field_name)
      unless Govspeak::Document.new(string).valid?
        error = "cannot include invalid Govspeak or JavaScript"
        record.errors.add(field_name, error)
      end
    else
      unless Govspeak::HtmlValidator.new(string).valid?
        error = "cannot include invalid HTML or JavaScript"
        record.errors.add(field_name, error)
      end
    end
  end

private
  def govspeak_fields(record)
    if record.class.const_defined?(:GOVSPEAK_FIELDS)
      record.class.const_get(:GOVSPEAK_FIELDS)
    else
      []
    end
  end
end

Version data entries

56 entries across 56 versions & 1 rubygems

Version Path
govuk_content_models-18.0.0 app/validators/safe_html.rb
govuk_content_models-17.2.1 app/validators/safe_html.rb
govuk_content_models-17.1.1 app/validators/safe_html.rb
govuk_content_models-17.1.0 app/validators/safe_html.rb
govuk_content_models-17.0.0 app/validators/safe_html.rb
govuk_content_models-16.2.0 app/validators/safe_html.rb
govuk_content_models-16.1.1 app/validators/safe_html.rb
govuk_content_models-16.1.0 app/validators/safe_html.rb
govuk_content_models-16.0.0 app/validators/safe_html.rb
govuk_content_models-15.1.2 app/validators/safe_html.rb
govuk_content_models-15.1.1 app/validators/safe_html.rb
govuk_content_models-15.1.0 app/validators/safe_html.rb
govuk_content_models-15.0.0 app/validators/safe_html.rb
govuk_content_models-14.1.1 app/validators/safe_html.rb
govuk_content_models-14.1.0 app/validators/safe_html.rb
govuk_content_models-14.0.1 app/validators/safe_html.rb
govuk_content_models-14.0.0 app/validators/safe_html.rb
govuk_content_models-13.4.0 app/validators/safe_html.rb
govuk_content_models-13.3.0 app/validators/safe_html.rb
govuk_content_models-13.2.1 app/validators/safe_html.rb