sanitize inline css with rails

Hi! You can simply use the sanitize(…) helper in your views to whitelist allowed tags and attributes… but what to do if you need to sanitize the content of a style attribute?  I found a solution to sanitize inline css with rails. This may not be the best solution available, but I didn’t find another solution (like an argument for sanitize helper).

Put this code in your config/enviroment.rb

# ALLOWED CSS PROPERTIES 
HTML::WhiteListSanitizer.allowed_css_properties = Set.new(%w(text-align font-weight text-decoration font-style))
# ALLOWED CSS PROPERTIES - acts like property_name-*, for example `text` allows text-align, text-deco...
HTML::WhiteListSanitizer.shorthand_css_properties = Set.new(%w())

Remember to restart your application, enviroment.rb must be reloaded also in development mode.

Have a nice day!

About Autore

Amo internet e le opportunità che ci offre. Grazie anche a te, che fai parte di questo mondo fantastico.

2 responses to “sanitize inline css with rails”

  1. Cyle says :

    Does this work in Rails 3?

    • Giulio Turetta says :

      Yes, it works also with rails3

      Example:

      config/application.rb

      require File.expand_path('../boot', __FILE__)
      
      # bla bla bla (...)
      
      module TestSanitize
        class Application < Rails::Application
          # bla bla bla (...)
      
          # allow a minimal set of attributes
          config.action_view.sanitized_allowed_attributes = 'id', 'class', 'style'
        end
        # setup whitelists
        HTML::WhiteListSanitizer.allowed_css_properties = Set.new(%w(color text-align font-weight text-decoration font-style))
        HTML::WhiteListSanitizer.shorthand_css_properties = Set.new(%w())
      end
      

      Tested with rails 3.2.1 and ruby 1.9.2p290

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: