gpt4 book ai didi

node.js - passport.js - 使用 passport-local 从 MongoDB 验证用户

转载 作者:可可西里 更新时间:2023-11-01 10:34:08 27 4
gpt4 key购买 nike

我的 MongoDB 中有一个简单的用户集合。我使用 mongo-native 驱动程序。

{
"email": "johndow@example.com",
"password": "123456",
"_id": {
"$oid": "50658c835b821298d3000001"
}
}

当我通过 pair email:pass 进行用户身份验证时,我将默认的 Passport 本地函数 findByUsername 重写为:

function findByEmail(email, fn) {
db.collection("users", function(err, collection) {
collection.find({}, {}, function(err, users) {
users.each(function(err, user) {
if (user.email === email) {
return fn(null, user);
}
});
return fn(null, null);
});
});
}

只需从数据库中获取所有用户,并检查 - 如果 user.email == 提供的电子邮件,则返回用户对象。

我使用MongoDB的_id参数作为用户的id,所以我修改了这两个函数:

passport.serializeUser(function(user, done) {
done(null, user._id);
});

passport.deserializeUser(function(id, done) {
findById(id, function(err, user) {
done(err, user);
});
});

这是我的 Passport 本地策略代码:

passport.use(new LocalStrategy( function(email, password, done) {
process.nextTick(function() {
console.log('initialize findByEmail() for "',email,'"');
findByEmail(email, function(err, user) {
if (err) {
return done(err);
}
if (!user) {
console.log('Unknown user ' + email)
return done(null, false, {
message: 'Unknown user ' + email

});
}
if (user.password != password) {
console.log('Invalid password')
return done(null, false, {
message: 'Invalid password'
});
}
//сonsole.log('ALL VERIFIATION PASSED');
return done(null, user);
})
});
}));

我从登录页面发布数据:

app.post('/login', passport.authenticate('local', {
failureRedirect: '/',
failureFlash: true
}), function(req, res) {
res.redirect('/desk');
});

我明白了

Error: Can't set headers after they are sent.

然后我得到

TypeError: Cannot read property 'email' of null

最后一个错误真的很奇怪,因为 findByEmail 有 console.log(user) 行(从这个列表中删除)并且它列出了所有用户的数据。

我做错了什么?

最佳答案

它没有很好的文档记录,但 cursor.each 为其回调的第二个参数提供了一个 null 值,以指示游标没有更多可用文档。它仅在 documentation 的示例中提到.

因此,在您的情况下,您应该在 users.each 回调中检查 user !== null

但是,通过将 find 调用更改为:

让 mongo 为您搜索会更有效:
collection.findOne({email: email}, {}, function(err, user) {
if (user) {
// email was found case
...
}
...
}

关于node.js - passport.js - 使用 passport-local 从 MongoDB 验证用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12639476/

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