Reputation: 3055
I have comparePassword
function runs inside checkLogin
in synchronous way, but the debugging output shows the opposite, what is my mistake here?
comparePassword = (password, salt, passwordHash) => {
crypto.pbkdf2(password, salt, 10000, 64, "sha512", (err, derivedKey) => {
//console.log('dump comparePassword: ', err);
if (err) {
return {
status: 500,
error: "Internal server error",
detail: "Server couldn't check your credential at the moment"
};
} else {
console.log(
"dump dump === : ",
passwordHash === derivedKey.toString("hex") ? true : false
);
if (derivedKey.toString("hex") == passwordHash) {
console.log("return return return1: ", true);
return true;
}
console.log("return return return2: ", true);
return false;
}
});
};
// Check credentials of a seller
exports.checkLogin = async (username, password) => {
let result = 0;
try {
const record = await Seller.findOne({
raw: true,
attributes: { exclude: ["birth", "createdAt", "updatedAt"] },
where: { email: username }
});
if (record !== null) {
let passwordRes = await comparePassword(
password,
record.salt,
record.password
);
console.log("dump passwordRes: ", passwordRes);
if (typeof passwordRes === "object") {
return passwordRes;
}
if (passwordRes) {
delete record.password;
delete record.salt;
return { seller: record };
}
}
} catch (error) {
console.log("error while checking seller credential: ", error);
result = {
status: 500,
error: "Internal server error",
detail: "Server couldn't check your credential at the moment"
};
}
return result;
};
Output:
dump passwordRes: undefined
dump dump === : true
return return return1: true
Expectation:
dump dump === : true
return return return1: true
dump passwordRes: true
Upvotes: 0
Views: 40
Reputation: 1725
Return a promise or simply make it async:
comparePassword = async (password, salt, passwordHash) =>{}
Upvotes: 0
Reputation: 4054
I think you can not await a callback in comparePasswort
without wrapping it in a promise.
Try something like
comparePassword = (password, salt, passwordHash) => new Promise((resolve, reject) => {
crypto.pbkdf2(password, salt, 10000, 64, 'sha512', (err, derivedKey) => {
// ...
resolve(true); // or reject(false)
})
})
Upvotes: 1
Reputation: 14904
comparePassword
should return an promise so await
can wait till the promise is resolved or rejected
comparePassword = (password, salt, passwordHash) => {
return new Promise((resolve, reject) => {
crypto.pbkdf2(password, salt, 10000, 64, "sha512", (err, derivedKey) => {
if (err) {
reject({
status: 500,
error: "Internal server error",
detail: "Server couldn't check your credential at the moment"
});
} else {
if (derivedKey.toString("hex") == passwordHash) {
resolve(true);
}
resolve(false);
}
});
});
};
Upvotes: 1