Reputation: 5215
I am implementing the Promise interface in my application with bcrypt
.
When I am trying to compare a password, I get false back, even though its the same password.
const bcrypt = require('bcrypt');
const saltRounds = 10;
const password = 'secret';
const resHash = ''
/**
* Generate Password
*/
bcrypt.hash(password, saltRounds).then((res) => {
console.log(res)
this.resHash = res
}).catch(err => {
console.log(err)
})
/**
* Compare Password
*/
bcrypt.compare(password, resHash).then((res) => {
console.log("Comparison result: " + res)
}).catch(err => {
console.log(err)
})
I am getting the following output:
Comparison result: false
boolean
$2a$10$n0mnrLHT3rRkREKB8RJXouMFrhNQjqOFeN7Sq.a.BYXigdBhcBkfq
Any suggestions what I am doing in the above example wrong?
Upvotes: 0
Views: 690
Reputation:
You have to use the bcrypt generated salt first before feeding it to the hash method.
const bcrypt = require('bcrypt');
const saltRounds = 10;
const password = 'secret';
let resHash = '';
bcrypt.genSalt(saltRounds).then(generatedSalt => {
bcrypt.hash(password, generatedSalt).then(res => {
console.log(res)
resHash = res;
}).catch(err => {
console.log(err);
});
}).catch(err => {
console.log(err);
});
// a promise is async. this will not sequentially be executed
// to test. use delay
setTimeout(function () {
bcrypt.compare(password, resHash).then(res => {
console.log("Comparison result: " + res)
}).catch(err => {
console.log(err)
});
}, 2000);
Check Bcrypt Github Page for more info.
Upvotes: 1
Reputation: 9920
If you're executing the above code just like you have it here, it won't work as the password comparison is firing immediately and not waiting for the first promise to resolve. In addition, you're setting this.resHash
, instead of attempting to set to the constant resHash
, which should be let resHash
.
const bcrypt = require('bcrypt');
const saltRounds = 10;
const password = 'secret';
let resHash = ''
/**
* Generate Password
*/
bcrypt.hash(password, saltRounds).then((res) => {
resHash = res;
return bcrypt.compare(password, resHash);
}).then(matches => {
console.log('Matches', matches) // true
}).catch(err => {
console.log(err)
})
Upvotes: 1