我尝试设置重置密码功能。用户将在其电子邮件中收到包含令牌的链接以重置其密码。链接看起来像这样:
http://localhost:3000/api/users/reset?token=dasdasad&id=5cb99eee1e7de74d69bbf426
其中token是由crypto.randombyte生成的秘密重置令牌,ID是用户的obejectID。
这是我的重置密码功能的一步:
我尝试在一个查询中执行步骤2 - 4但它不起作用。不知何故,即使重置令牌错误,用户也总是能够在数据库中更新他们的密码。
这是我的代码
// setup find criteria
const criteria = {
$and: [
{_id: oid},
{reset_token: query.token}
]
}
// hashing new password
bcrypt.genSalt(saltRounds, (error, salt) => {
bcrypt.hash(form.newPassword, salt, (error, hash) => {
form.newPassword = hash;
// update new password into DB and delete reset token
users.updateOne(criteria, {$set:{password:form.newPassword}, $unset:{reset_token:""}} )
.then(response => {
return res.status(201).json(`Your password has been reset successfully!`);
})
.catch(error => res.status(500).json('Sorry something is wrong. Please try again later.'));
});
})
.catch(error => {
res.status(500).json('Sorry something is wrong, please try again later or contact us for further assistance');
})
我希望当用户提供错误的令牌时,用户将收到错误消息并且无法更新数据库。
谢谢。抱歉英文不好。
如果查询不匹配,updateOne
不会失败。即使它与任何行都不匹配,也不会调用catch
。这是为真正的灾难性故障保留的(例如数据库连接失败)。如果你想知道一行是否更新,请检查你的.modifiedCount
中的.matchedCount
或response
的.then
。