Bcrypt Compare Always Returns False
bcrypt.compare() always comes back false with this code in the user model. This is with bcrypt-nodejs. User.pre('save', function (callback) { this.password = bcrypt.hashSync(this
Solution 1:
Here's a working version of your code. I am not sure what all is happening behind the scenes with your methods so I made that part up.
To prove it works add this to a file called index.js and run it with "node index.js".
It will output this:
We got a match! trueorfalse? true
Here's the code.
var bcrypt = require('bcrypt');
var Q = require('Q');
var salt = bcrypt.genSaltSync(10);
process.env.JWT_SECRET = 'Much_Secretive,_Such_Obscure';
functionSuperUser () {
this.pre = function (password, callback) {
this.password = bcrypt.hashSync(password, salt);
callback.call(this, password);
};
this.methods = {};
}
varUser = newSuperUser();
User.methods.verifyPassword = function ( password ) {
const self = this;
return Q.Promise( (resolve, reject) => {
bcrypt.compare( password, self.password, (error, isMatch) => {
if (error) reject( newError("Error checking user password."));
console.log("We got a match! true or false? " + isMatch);
resolve(isMatch);
});
});
};
User.pre('save', function (password) {
this.methods.verifyPassword.call(this,password);
});
Without seeing your full implementation it's hard to know for sure, but there is probably a reference to 'this' that is not the 'this' you would expect it to be.
Baca Juga
- Node.js & Mysql - Error: 1251 - Client Does Not Support Authentication Protocol Requested By Server; Consider Upgrading Mysql Client
- Socket.io Connection Keep Increasing Each Time A New Connect Has Been Made
- Bcrypt.compare() Is Asynchronous, Does That Necessarily Mean That Delays Are Certain To Happen?
I use function.call a couple times to get around that.
Solution 2:
The solution was if (!this.isModified('password')) return callback()
, shown below in full.
User.pre('save', function (callback) {
if (!this.isModified('password')) return callback()
this.password = bcrypt.hashSync(this.password, bcrypt.genSaltSync(10))
this.token = jwt.sign(this.email, process.env.JWT_SECRET)
callback()
})
This is because this fires more than once in the save process. So it was effectively hashing the password, then on the second round, hashing the hash.
Post a Comment for "Bcrypt Compare Always Returns False"