My API uses SailsJs and MongoDb. For user creation, I am using the beforeCreate lifecycle callback
to run bcrypt to hash my password field.
I encounter this wierd error, wherein if I set my encrPassword field to
{required : true}
my code stops working and emits the following error :
{
"error": "E_VALIDATION",
"status": 400,
"summary": "1 attribute is invalid",
"model": "User",
"invalidAttributes": {
"encrPassword": [
{
"rule": "string",
"message": "Value should be a string (instead of null, which is an object)"
},
{
"rule": "required",
"message": "\"required\" validation rule failed for input: null\nSpecifically, it threw an error. Details:\n undefined"
}
]
}
here is my code sample :
attributes: {
fullname : {type : 'string'},
username : {type : 'string', unique:true, required:true},
encrPassword : {type : 'string'}, // ==> this works
// encrPassword : {type : 'string', required:true}, ==> this doesn't
},
insert : function(req, cb){
console.log('Insert ', req);
if(typeof req.fullName == 'string' && typeof req.username == 'string'){
User.findOne({username : req.username}).exec(function(err, res){
if(!res){
User.create(req).exec(function(err, resp){
console.log('create', null, resp);
if(err)
cb(err);
else cb(null, resp);
});
}
else cb({message: 'already eists'})
});
}
else cb({message: 'Bad Request'});
},
beforeCreate : function(req, next){
console.log('In bcrypt');
bcrypt.genSalt(10, function(err, salt){
if(err) return next(err);
bcrypt.hash(req.password, salt, function(err, hash){
if(err) return next(err);
req.encrPassword = hash;
delete req.password;
console.log('Leaving BCrypt');
next();
});
});
}
ps. I rigorously checked for typos; any typos or syntax errors in the above sample are the result of editing to hide any code i wouldnt want to share
Validation is done before calling beforeCreate
.
There is no encrPassword
at that moment, hence the error.