Ask A Question

Notifications

You’re not receiving notifications from this thread.

Rails::HTML Sanitizer: mimic CKEDITOR allowedContent configuration, by specifying attributes and CSS classes for each tag

TL asked in General

Let's say that I want to sanitize user generated HTML written by CKEDITOR or something similar.

CKEDITOR has a really nice hash-like syntax for allowing content:

config.allowedContent = {
    a: {
      attributes: 'href'
    },
    b: true,
    i: true,
    u: true,
    table: true,
    tbody: true,
    tr: true,
    td: true,
    blockquote: true,
    img: {
      attributes: [ '!src', 'alt', 'width', 'height' ],
      classes: [ 'align-left', 'align-center', 'align-right' ],
    },
    h1: true,
    h2: true,
    h3: true,
    ul: true,
    li: true,
    ol: true,
    figure: true,
    figcaption: true,
  };

It works like this:

  • only tags in the list are allowed;
  • if tag value is true, all attributes and classes are allowed for that html tag; otherwise, you can pass an object specifying which classes and attributes you want to allow for that specific tag.

I basically want to replicate that in the backend with Rails HTML Sanitizer.

What I currently have is a simple PermitScrubber:

class BlogPostScrubber < Rails::Html::PermitScrubber

  def initialize

    super

    self.tags = %w(
      p
      a
      b
      i
      u
      table
      tbody
      tr
      td
      blockquote
      img
      h1
      h2
      h3
      ul
      li
      ol
      figure
      figcaption
    )

  end

end

The problem is: if I specify @attributes in the PermitScrubber, it will allow those attributes for any element; also, I have no idea how to permit only specific CSS classes for certain tags.

Can anyone shed some light on a way to achieve this?

Reply
Join the discussion
Create an account Log in

Want to stay up-to-date with Ruby on Rails?

Join 85,376+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.