[英]Sails.js - Encrypt password
對於一個項目,我需要有用戶,我想在數據庫中存儲加密的密碼。
所以我需要你的幫助,因為我需要在添加用戶時加密密碼,但是當我啟動sails lift
時,我的終端有錯誤:
In model `user`:
The `toJSON` instance method is no longer supported.
Instead, please use the `customToJSON` model setting.
組態:
我正在使用Sails 1.0 Beta
和Bcrypt 1.0.2
。
型號User.js
/**
* User.js
*
* @description :: A model definition. Represents a database
table/collection/etc.
* @docs :: https://sailsjs.com/docs/concepts/models-and-
orm/models
*/
var bcrypt = require('bcrypt');
module.exports = {
attributes: {
firstname: {
type: 'string'
},
lastname: {
type: 'string'
},
password: {
type: 'string'
},
email: {
type: 'string',
unique: true
},
code: {
type: 'string',
unique: true
},
referring: {
type: 'string'
},
comment: {
type: 'text'
},
// Add reference to Profil
profil: {
model: 'profil'
},
toJSON: function() {
var obj = this.toObject();
delete obj.password;
return obj;
}
},
beforeCreate: function(user, cb) {
bcrypt.genSalt(10, function(err, salt) {
bcrypt.hash(user.password, salt, function(err, hash) {
if (err) {
console.log(err);
cb(err);
} else {
user.password = hash;
cb();
}
});
});
}
};
我想我使用舊方法加密密碼,但我不知道或沒有找到另一種方法來做到這一點。
提前致謝
我認為您應該執行以下操作並記住將此customToJSON函數放在attributes:{...},
attributes:{...},
customToJSON: function() {
// Return a shallow copy of this record with the password and ssn removed.
return _.omit(this, ['password'])
}
我知道這個問題已經過時了,但很多時候這將會有所啟發。
從Sails 1.0開始,不再支持實例方法。 文檔建議您應該使用customToJSON
,但它沒有說明您應該在屬性之外使用它。
customToJSON允許您在發送數據之前使用自定義函數對數據進行字符串化。 在您的情況下,您將要省略密碼。 使用customToJSON,您可以使用this
關鍵字來訪問返回的對象。 建議不要改變這個對象,intsead創建一個副本。
因此,對於您的示例,您將使用:
module.exports = {
attributes: {...},
customToJSON: function() {
return _.omit(this, ['password'])
},
beforeCreate: function(user, cb) {...}
};
您看到的錯誤與加密無關。 查看您的模型並記下toJSON函數。 如錯誤消息所示,這是一個實例方法,不再支持它。 按照建議這樣做:使用customToJSON
模型設置。 我相信你會在文檔中找到它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.