How best to sanitize fields in ruby on rails

后端 未结 2 953
孤独总比滥情好
孤独总比滥情好 2021-01-02 11:01

I currently have a controller capturing some html from TinyMCE on the front end. If I tinker with firebug it is possible to submit script tags and inject alert messages etc

相关标签:
2条回答
  • 2021-01-02 11:13

    I think the way you are doing it is fine, but if you are using before_save then you could potentially still fail validations (since before_save is called after validations). Also, you don't necessarily have to put it into it's own module, it could just be a private method on your class.

    Something like:

    class MyModel < ActiveRecord::Base
    
      before_validation :sanitize_content, :on => :create
    
      private
        def sanitize_content
          self.content = sanitize_tiny_mce(self.content)
        end
        def sanitize_tiny_mce(field)
          ActionController::Base.helpers.sanitize(field,
            :tags => %w(a b i strong em p param h1 h2 h3 h4 h5 h6 br hr ul li img),
            :attributes => %w(href name src type value width height data) );
        end
    
    end
    
    0 讨论(0)
  • 2021-01-02 11:21

    This question seems to be answered but for anyone coming to this you might want to consider using custom mutators to make this more transparent. Something like:

    class MyModel < ActiveRecord::Base
      def content= content
        write_attribute(:content, sanitize_tiny_mce(content)
      end
    
      private
    
      def sanitize_tiny_mce content
        ActionController::Base.helpers.sanitize(field,
            :tags => %w(a b i strong em p param h1 h2 h3 h4 h5 h6 br hr ul li img),
            :attributes => %w(href name src type value width height data)
        );
      end
    end
    

    This will ensure the content is sanitized any time it's changed.

    0 讨论(0)
提交回复
热议问题