sailsjs:避免保存某些表单输入到数据库中
问题描述:
我正在尝试创建一个注册页面,跟在irl nathans guide之后。现在一切正常,但sail.js似乎将数据库中的所有内容都保存起来。举个例子,我有这样的形式:sailsjs:避免保存某些表单输入到数据库中
<form class="form-signup" name="signup-form" action="/user/create" method="POST">
<input type="text" name="username" placeholder="<%= __('username') %>"> %>">
<input type="text" name="email" placeholder="<%= __('email') %>">
<input type="password" name="password" placeholder="<%= __('password') %>">
<input type="password" name="confirmation" placeholder="<%= __('confirm-password') %>">
<input class="button" type="submit" value="<%= __('signup') %>"/>
<input type="hidden" name="_csrf" value="<%= _csrf %>"/>
</form>
在这个例子中节省了密码,并在数据库中,该密码确认它不应该。
在我的User.js模型中,我有以下属性,但这些只是保存在两个密码旁边。我也有一个encryptedPassword,如果它们匹配,它会加密密码。
module.exports = {
attributes: {
username: {
type: 'string',
required: true,
unique: true
},
email: {
type: 'string',
required: true,
isEmail: true,
unique: true
},
encryptedPassword: {
type: 'string'
},
// more unimportant code here.
}
我想知道是否它可以防止sails.js无论何时提交表单保存在数据库中的两个未加密的口令。我知道我可以从数据库中删除它,但是,这看起来很愚蠢。
在数据库中保存的记录,提交时:
{
"username": "testuser",
"password": "2",
"confirmation": "2",
"email": "[email protected]",
"createdAt": 1496268539155,
"updatedAt": 1496268539155,
"encryptedPassword": "$2a$10$BkwvQnu3TA4DQ1kDMZmi6O7Z/K5uX90fHi/6zkZF.nkKi8MU.zWTS",
"id": "592f3efbaa4d2563e159dc20"
}
因为我加密密码,它不应该也节省了未加密的密码,只是因为他们是提交表单的一部分。我如何阻止它这样做?
答
谢谢你的答案,但是,我设法通过传递一个对象到.create()函数来解决问题。该对象包含我想要保存的所有参数,而不是使用req.params.all()。
var userObj = {
username : req.param('username'),
firstname : req.param('firstname'),
encryptedPassword : password,
surname : req.param('surname'),
email : req.param('email')
}
答
当您设置您的数据库连接(connections.js或在您的/env/development.js)指定模式:真
例如:
someDbServer: {
adapter: 'sails-mongo',
host: 'localhost',
port: 27017,
user: 'username',
password: 'pwd',
database: 'db_name',
schema: true
}
设置模式,以真正意味着只有可以插入模型js文件中的属性。
为了加密您的密码,您需要在beforeCreate和beforeUpdate中执行此操作。看看生命周期回调 - sailsjs lifecycle callbacks
可能会将所有传入的req.param保存到控制器中的数据库中。 –
您可以使用'beforeCreate'回调从'values'对象中删除密码。 请参阅:http://sailsjs.com/documentation/concepts/models-and-orm/lifecycle-callbacks – khushalbokadey