在 sequelize.js 中使用 build 方法时是否需要验证、清理或转义数据
我有一个 node/express/sequelize 应用程序.我正在使用 sequelize 中的 build 方法来创建我的 foo 模型的实例.
I have a node / express / sequelize app. I am using the build method in sequelize to create an instances of my foo model.
Foo 控制器
exports.create = function(req, res) {
var foo = db.Foo.build(req.body);
foo.save().then(function(){
// do stuff
});
}
Foo 模型
module.exports = function(sequelize, DataTypes) {
var Foo = sequelize.define('Foo',
{
bar: DataTypes.STRING,
baz: DataTypes.STRING
}
构建方法是否会检查我保存的数据是否干净,或者我是否需要在这里采取一些额外的预防措施?
Does the build method check that the data I am saving is clean or do I need to take some extra precautions here?
推荐答案
我更喜欢在路由中做二次验证,因为:
I prefer to make secondary validation in routes, because:
1) 将数据存储在数据库中是您可以使用这些数据执行的众多操作之一.如果您仅在数据库中验证,那么在其他地方您将获得未验证的数据.例如,在将其保存到数据库之前,您可能需要进行一些计算或连接.
1) Storing data in a database is one of many things you can do with this data. If you only validate in database then in other places you get not validated data. For example you may need some computation or concatenation before saving it in a database.
2) 或者当您在多条路线中使用一种 sequelize 模型(例如,客户路线和合作伙伴路线中的用户模型)并且您想要制定不同的验证规则时.
2) or when you use one sequelize model in many routes (e.g. User model in customer route and partner route) and you want to make different validation rules.
我总是在 sequelize 模型中设置验证,但这是使用最大允许条件"进行验证(例如,用户名字段永远不会大于 200 个字符并且它是字符串).我也进行路由验证.它更加具体和具体(例如,在客户路线中,用户名最大为 100,但在合作伙伴路线中,用户名可能有 150 个字符,并且还检查此字符串的内容).
I always set validation in sequelize models, but this is validation with 'maximum allowable conditions' (e.g. username field never be larger then 200 chars and it is string). I make also routes validation. It is more specific and concrete (e.g. in customer route username max large is 100 but in partner route username may have 150 chars and also check content of this string).
最后,严格回答您的问题:sequelize 验证主要用于验证格式.这还不够.看看我的回答 NodeJS/express - 公共 API 端点的安全性一>如果您在没有正确验证的情况下保存数据然后提供此数据,那么您将面临 XSS 攻击.
And finally, the strict answer for your question: sequelize validation is mostly for validating format. And this is not enough. Look at my answer NodeJS/express - security for public API endpoint if you save data without correct validation and then serve this data then you are exposed to XSS attack.
相关文章