如何最有效地净化Ruby on Rails中的字段 [英] How best to sanitize fields in ruby on rails
问题描述
我现在有一个控制器捕获从TinyMCE的一些HTML的前端。如果我鼓捣萤火虫有可能提交脚本标记注入警报消息等的屏幕。
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 on to the screen.
编辑:目前我使用了sanitize帮助解决这个模型中的:
edit: Currently I am fixing this in the model by using the sanitize helper:
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的,所以我可以很容易地指定保存在一个类似的方式来验证之前,这样做是为了这个问题和其他领域?
This feels messy in the controller. Is there a better way? I.e. somehow integrate this ActiveRecord so I can easily specify to do this to this and other fields before saving in a similar way to validation?
感谢您的任何建议。
编辑:
在这里取得一些进展。
在我的/利布斯我有
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
然后在我的模型中code退化为
Then in my Models the code collapses to
class MyModel < ActiveRecord::Base
include ::SanitizeUtilities
...
before_save :sanitize_content
...
def sanitize_content
self.content = sanitize_tiny_mce(self.content)
end
end
这似乎是掉不想要的标记没有太多的大惊小怪。
This seems to strip out unwanted markup without too much fuss.
pretty的新轨道太紧张我可能会做一些错误。任何人都可以看到潜在的缺点吗?
Pretty new to rails so nervous I might be doing something wrong. Can anybody see potential drawbacks here?
再次感谢
推荐答案
我认为你正在做的方式是好的,但如果您使用的是 before_save
,那么你可以可能仍然无法验证(因为 before_save
验证之后被调用)。此外,你不必把它变成它自己的模块,它可能只是对你的类的私有方法。
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.
是这样的:
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
这篇关于如何最有效地净化Ruby on Rails中的字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!