gpt4 book ai didi

javascript - 如何在 Sequelize.then 中执行 bcrypt.compare?

转载 作者:行者123 更新时间:2023-11-30 19:59:50 25 4
gpt4 key购买 nike

我正在尝试构建一个登录页面,我在其中使用 Sequelize 从 mysql 数据库获取散列密码,然后调用 bcrypt compare 对密码进行去散列处理,并将其与用户的登录输入进行比较以进行身份​​验证。

但是,bcrypt compare 的执行速度总是比 return 慢,导致值始终为“”。我知道这与异步行为有关,但我不知道如何正确编写此代码以使其工作。

     authenticate: (req, res) => {

let userDetails = req.query;

User.findOne({
where: {
username: userDetails.username
}
})
.then((user) => {
// How can I make this so, correctPassword() finishes
// and then the authenticated variable will be either false or true?

let authenticated = correctPassword(userDetails.password, user.password);
return authenticated;
})
.then((authenticated) => {
// right now authenticated is "" in client side console.

res.send(authenticated);
})
.catch((error) => {
console.log('there was an error: ', error);
});
}
}

const correctPassword = (enteredPassword, originalPassword) => {
return bcrypt.compare(enteredPassword, originalPassword, (err, res) =>{
return res;
});
}

最佳答案

你快到了。您正确地凭直觉认为 correctPassword 是异步执行的,尽管它写得好像是同步的。

首先,让我们将 correctPassword 设为一个 promise,这样我们就可以使用 async/await 或对其调用 .then

const correctPassword = (enteredPassword, originalPassword) => {
return new Promise(resolve => {
bcrypt.compare(enteredPassword, originalPassword, (err, res) =>{
resolve(res)
});
})
}

接下来,您有两种方法可以确保代码中的操作顺序正确执行:

(推荐)使用 async/await 语法允许我们编写看起来同步的代码:

authenticate: async (req, res) => {
let userDetails = req.query;
try {
const user = await User.findOne({
where: {
username: userDetails.username
}
});

const authenticated = await correctPassword(userDetails.password, user.password);

res.send(authenticated);
} catch(e) {
res.status(400).send(e)
}
}

继续使用 promise :

authenticate: (req, res) => {
let userDetails = req.query;
User.findOne({
where: {
username: userDetails.username
}
}).then(() => {
correctPassword(userDetails.password, user.password)
.then(authenticated => {
res.send(authenticated)
})
.catch(e => {
res.send(e)
})
})
}

关于javascript - 如何在 Sequelize.then 中执行 bcrypt.compare?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53509726/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com