Sha256: 294136a49c7e968d88f551296b554508f11c7906c5151e78dfdcfc309e3d4922

Contents?: true

Size: 1.04 KB

Versions: 20

Compression:

Stored size: 1.04 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 record.class::GOVSPEAK_FIELDS.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
end

Version data entries

20 entries across 20 versions & 1 rubygems

Version Path
govuk_content_models-8.3.1 app/validators/safe_html.rb
govuk_content_models-8.3.0 app/validators/safe_html.rb
govuk_content_models-8.2.0 app/validators/safe_html.rb
govuk_content_models-8.1.0 app/validators/safe_html.rb
govuk_content_models-8.0.0 app/validators/safe_html.rb
govuk_content_models-7.3.1 app/validators/safe_html.rb
govuk_content_models-7.3.0 app/validators/safe_html.rb
govuk_content_models-7.2.1 app/validators/safe_html.rb
govuk_content_models-7.2.0 app/validators/safe_html.rb
govuk_content_models-7.1.1 app/validators/safe_html.rb
govuk_content_models-7.1.0 app/validators/safe_html.rb
govuk_content_models-7.0.0 app/validators/safe_html.rb
govuk_content_models-6.4.0 app/validators/safe_html.rb
govuk_content_models-6.3.0 app/validators/safe_html.rb
govuk_content_models-6.1.0 app/validators/safe_html.rb
govuk_content_models-6.0.6 app/validators/safe_html.rb
govuk_content_models-6.0.5 app/validators/safe_html.rb
govuk_content_models-6.0.4 app/validators/safe_html.rb
govuk_content_models-6.0.3 app/validators/safe_html.rb
govuk_content_models-6.0.2 app/validators/safe_html.rb