node.js - 如何比较passport-local-mongoose中的密码
问题描述
我想将登录用户的密码与他们从表单中提供的密码进行比较,因为我需要确保它确实是用户,因为我希望为他们提供启用 2fa 的选项,我相信任何人如果用户登录到仪表板,可以启用它。我正在使用 bcrypt 来比较密码,但它会引发错误。我也在使用 passport-local-mongoose 来注册我的用户和进行身份验证。
router.post("/enableTwoFa/:id", isLoggedIn, isVerified, function(req, res){
if(req.isAuthenticated){
User.findById(req.params.id, function(err,found){
if(err){
res.redirect("back")
res.send('User not found with the proper ID')
} else {
if(req.body.accountPassword){
console.log(found)
bcrypt.compare(req.body.accountPassword,found.password, function(err,success){
if(err){
console.log(err)
res.send('There was a problem somewhere')
} else {
console.log(success)
res.send('password hashed')
}
})
} else {
res.send('Please input your account password!!')
}
}
})
} else {
res.send('You are not authorized for this request')
}
})
它会引发丢失数据和散列的错误。但我不知道如何找到必填字段.. 或者如果护照中有处理此问题的功能,我对此很陌生。
Error: data and hash arguments required
at Object.compare (/home/ubuntu/workspace/bit-main/main/node_modules/bcrypt/bcrypt.js:209:17)
at /home/ubuntu/workspace/bit-main/main/routes/dashboard.js:448:24
at Query.<anonymous> (/home/ubuntu/workspace/bit-main/main/node_modules/mongoose/lib/model.js:3928:16)
at /home/ubuntu/workspace/bit-main/main/node_modules/kareem/index.js:297:21
at /home/ubuntu/workspace/bit-main/main/node_modules/kareem/index.js:135:16
at _combinedTickCallback (internal/process/next_tick.js:73:7)
at process._tickCallback (internal/process/next_tick.js:104:9)
解决方案
在对这个问题做了一些研究之后,我发现在 passport-local-mongoose 中有一个 authenticate() 函数可以处理这个请求,所以不需要使用 bcrypt。它接受 3 cb(hashError,model,passwordError)
。所以我决定回答它,以防有人遇到同样的问题。
router.post("/enable2fa/:id", isVerified, function(req, res){
if(req.isAuthenticated){
User.findById(req.params.id, function(err,found){
if(err){
res.redirect("back")
res.send('User not found with the proper ID')
} else {
if(req.body.accountPassword){
found.authenticate(req.body.accountPassword, function(err,model,passwordError){
if(passwordError){
console.log(err)
res.send('The given password is incorrect!!')
} else if(model) {
console.log(`correct password ${model}`)
*run other code stuff*
res.send('2fa enabled for this account')
}
})
} else {
res.send('Please input your account password!!')
}
}
})
} else {
res.send('You are not authorized for this request')
}
})
推荐阅读
- javascript - javascript:对象和数组操作 i
- python-3.x - 用布尔值计算熊猫
- javascript - OnChanges 不会在部分对象更改时触发
- wolfram-mathematica - 无法在 Show[ 中组合图形对象
- powershell - PowerShell 统计对象的属性值出现次数
- angular - 如何在 Angular Promise 或 observable 中定位错误?
- python - 更改列中的所有第一个值,从其他列分组
- shell - 如何通过浏览器访问您的终端窗口?
- php - 您的 SQL 语法有错误;查看与您的 MariaDB 服务器版本相对应的手册,了解在第 1 行的“1”附近使用的正确语法
- asynchronous - Shiny - 在执行异步任务时更改 actionButton 的颜色