Still quite new to nodejs, so I frequently get tripped up by the whole asynchronous thing. I am attempting to hash a password before storing it in the database, using bcrypt and bookshelf. Pretty straight forward right...
I am calling the save action like so,
create(data) {
this.logger.info(`creating account`);
return bookshelf.transaction(trx => {
return new Account().save(data, { method: 'insert', transacting: trx });
});
}
and in the account model, I intercept the save action
initialize: function() {
let _this = this;
const saltRounds = 10;
_this.on('creating', function () {
bcrypt.genSaltSync(saltRounds, function(err, salt) {
bcrypt.hashSync(_this.get('password'), salt, function (err, hash) {
if (err) throw err;
_this.set('password', hash);
});
});
});
}
Everything i've looked up so far says this should work, but the plain text password is still getting saved into the database instead of the hashed password. What am I doing wrong?
You're using synchronous functions, but passing them callbacks, which won't get called (and therefore, the password won't be replaced).
Try this:
initialize: function() {
const saltRounds = 10;
this.on('creating', () => {
let salt = bcrypt.genSaltSync(saltRounds);
let hash = bcrypt.hashSync(this.get('password'), salt);
this.set('password', hash);
});
}
Or replacing the synchronous functions with async ones, using promises (which are supported by both bcrypt
and bookshelf
):
initialize: function() {
const saltRounds = 10;
this.on('creating', () => {
return bcrypt.genSalt(saltRounds).then(salt => {
return bcrypt.hash(this.get('password'), salt);
}).then(hash => {
this.set('password', hash);
});
});
}
我不确定,但我相信错误是因为您使用的是es6 let而不是var,所以此上下文会延迟
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.