【发布时间】:2018-03-05 06:45:14
【问题描述】:
我目前正在尝试向我的节点 API 添加一些身份验证。
现在我正在使用 PassportJS(对这个很新,对我的无能感到抱歉)。
我正在尝试添加本地策略,并在登录时检查用户密码是否合法:
// Local Strategy
passport.use(
new LocalStrategy(async (username, password, done) => {
try {
// Find user by username
const user = await User.findOne({ username })
// No user found
if (!user) {
return done(null, false)
}
console.log('user', user) // Getting output
// Check if password correct
const isMatch = await user.isValidPassword(password)
// Handle if password is not correct
if (!isMatch) {
return done(null, false)
}
// Return user
done(null, user)
} catch (err) {
done(err, false)
}
})
)
我注意到在const isMatch = await user.isValidPassword(password) 上使用await 时,邮递员说:Error: ReferenceError: user is not defined。当我删除await 时,它工作正常,但我可以输入错误的密码,但我仍然可以登录。当我 console.log 时,我可以看到我的 user 对象。
{
"username": "martinnord3",
"password": "this_is_the_wrong_password"
}
这是isValidPassword 函数:
UserSchema.methods.isValidPassword = async function(newPassword) {
try {
return await bcrypt.compare(newPassword, user.password)
} catch (err) {
throw new Error(err)
}
}
我想我缺少一些明显的东西,但我无法解决这个问题。
感谢您抽出宝贵时间阅读本文!
【问题讨论】:
-
user.isValidPassword(password)返回什么?无需等待即可尝试。 -
@Firanolfind 你好!退货是什么意思? :O
标签: javascript node.js jwt passport.js