Mongoid:如何防止通过批量分配创建未定义的字段? [英] Mongoid: How to prevent undefined fields from being created by mass assignment?
问题描述
代码如下:
class M
include Mongoid::Document
field :name
end
params = { name: "foo", age: 20 }
M.create(params)
#=> #<M name: "My Name", age: 20>
请注意,尚未定义age
,但它已保存.
Notice that age
wasn't defined, yet it was saved.
这是有问题的(可能是DoS的来源),因为恶意用户可以在POST中添加任何参数,并且带有大字符串的未知字段可以潜入.(例如name=foo&bogus=#{'x'*1000000}
)
This is problematic (potentially a source of DoS) because a malicious user can add any parameters in POST and unknown fields with a large string can sneak in. (e.g. name=foo&bogus=#{'x'*1000000}
)
到目前为止,除了attr_accessible
我什么都找不到,但是对于Mongoid来说并不是很好,因为您必须始终在所有模型中同时在field
和attr_accessible
中保持相同的字段名称.不干.
So far, I couldn't find anything but attr_accessible
, but it's not really great for Mongoid as you have to maintain the same field names in both field
and attr_accessible
all the time, in all models. Not DRY.
我认为attr_accessible
API非常适合ActiveRecord,因为在 a.中,您没有在模型(DRY)和 b中明确定义字段.确保不存在不存在的字段保存到RDB的机会.但是对于Mongoid,我认为应该有比attr_accessible
更好的解决方案.
I think the attr_accessible
API is great for ActiveRecord, because there a. you don't explicitly define fields in the models (DRY) and b. it's guaranteed there's no chance that a nonexistent field gets saved to RDB. But for Mongoid, I think there should be a better solution than attr_accessible
.
请注意,有一个全局配置设置allow_dynamic_fields
,但它与批量分配无关,因此不在本讨论的范围之内,但是我认为它实际上应该是每个模型的宏,并且还应注意批量分配
Note that there's a global config setting allow_dynamic_fields
but it's not about mass assignment so it's out of the scope in this discussion, however I think it should actually be a per-model macro and should also take care of mass-assignment.
您如何处理这个问题?
推荐答案
我一直在模型中使用attr_accessible
.我很少发现自己包括所有领域都可以访问.通常,总会有一些字段不可进行大规模分配.如果您经常需要包含每个属性,并且担心重复:
I'm always using attr_accessible
in models. I rarely found myself including all fields as accessible. Usually there are always a few fields that shouldn't be accessible for mass assignment. If you often need to include every attribute and you're concerned about duplication:
attr_accessible *fields.keys
这篇关于Mongoid:如何防止通过批量分配创建未定义的字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!