7

我目前有一个控制器从前端的TinyMCE捕获一些HTML。如果我用萤火虫修补,可以提交脚本标记并将警报消息插入到屏幕上。如何最好的消毒轨道上的红宝石字段

编辑:目前,我在模型中使用了sanitize帮助解决这个:

require 'action_view' 

class NotesController < AuthApplicationController 

    include ActionView::Helpers::SanitizeHelper 
... 
    def update 
    params[:note][:content] = sanitize(params[:note][:content], 
     :tags => %w(a object p param h1 h2 h3 h4 h5 h6 br hr ul li img), 
     :attributes => %w(href name src type value width height data)); 

    @note.update_attributes(params[:note]) 

这种感觉在控制器中凌乱。有没有更好的办法?即以某种方式整合了这个ActiveRecord,所以我可以很容易地指定在对这个和其他字段执行此操作之前,以类似的方式进行验证?

感谢您的任何建议。

编辑:

在这里取得了一些进展。

在我的/利布斯我有

module SanitizeUtilities 
    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 

然后在我的模型代码折叠到

class MyModel < ActiveRecord::Base 
    include ::SanitizeUtilities 
... 
    before_save :sanitize_content 
... 
    def sanitize_content 
    self.content = sanitize_tiny_mce(self.content) 
    end 

end 

这似乎是掉不想要的标记没有太过计较。

对轨道很新,很紧张我可能会做错事。任何人都可以在这里看到潜在的缺点吗?

再次感谢

+0

在rails中处理这个问题的更常用的方法是接受来自客户端的任何垃圾并保存(安全,小心避免SQL注入)。然后在需要展示的时候进行清理。 – noodl

+2

对我来说这似乎很奇怪,为什么我会提交脏数据?如果我将数据读回到多个地方,这会增加错过清理工作的机会和机会。 – Chris

+0

@noodl同意克里斯在这一个。预先清除数据意味着你只需要进行一次这个过程。不删除意味着每次显示数据时都必须执行此过程。就像克里斯说的那样,你可能忘记保护观点。 – iwasrobbed

回答

11

我认为你正在做的方式是好的,但如果你正在使用before_save,那么你可能仍然无法验证(因为before_save被验证之后调用)。另外,你不一定要把它放到它自己的模块中,它可能只是你班上的私人方法。

喜欢的东西:

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

大概是'on:[:create,:update]'也是......其他任何最佳实践? – Meekohi

1

这个问题似乎回答,但任何人来此,你可能要考虑使用自定义存取器,使这个更加透明。例如:

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 

这将确保内容在任何时候被改变时被消毒。