Reputation: 51
For a project, I need to have users and i want to stock an encrypted password in the database.
So I need your help because i need to encrypt password when I add an user, but I have an error into the terminal when I launch sails lift
:
In model `user`:
The `toJSON` instance method is no longer supported.
Instead, please use the `customToJSON` model setting.
Configuration:
I'm using the Sails 1.0 Beta
and Bcrypt 1.0.2
.
Model 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();
}
});
});
}
};
I think I'm using an old way to encrypt the password, but I don't know or don't find an another way to do this.
Thanks in advance
Upvotes: 1
Views: 3767
Reputation: 834
I think You should do the following and remember put this customToJSON function after the attributes:{...},
attributes:{...},
customToJSON: function() {
// Return a shallow copy of this record with the password and ssn removed.
return _.omit(this, ['password'])
}
Upvotes: 2
Reputation: 46
I know that this question is old, but hopfully this will shed some light.
As of Sails 1.0, instance methods are no longer supported. The documentation suggests that you should use customToJSON
instead, but it doesn't clarify that you should use it outside of the attributes.
customToJSON allows you to stringify the data with a custom function before sending it.
In your case, you'll want to omit the password.
With customToJSON you can use the this
keyword to access the returned object. It's advised not to mutate this object, intsead create a copy.
So for your example you'd use:
module.exports = {
attributes: {...},
customToJSON: function() {
return _.omit(this, ['password'])
},
beforeCreate: function(user, cb) {...}
};
Upvotes: 1
Reputation: 631
The error you see has nothing to do with the encryption. Look in your model and take note of the toJSON function. As the error message indicates, this is an instance method and it is no longer supported. So do as suggested: use the customToJSON
model setting. I am sure you will find it in the documentation.
Upvotes: 0