【问题标题】:passport.js - authenticate users from MongoDB with passport-localpassport.js - 使用本地护照验证来自 MongoDB 的用户
【发布时间】:2015-01-07 03:15:40
【问题描述】:

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

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

当我通过pair email:pass 进行身份验证时,我将默认的passport-local 函数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.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) 行(从这个列表中删除)并且它列出了所有用户的数据。

我做错了什么?

【问题讨论】:

    标签: node.js mongodb passport.js


    【解决方案1】:

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

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

    但是,通过将 find 调用更改为:让 mongo 为您进行搜索会更有效:

    collection.findOne({email: email}, {}, function(err, user) {
        if (user) {
            // email was found case
            ...
        }
        ...
    }
    

    【讨论】:

    • 谢谢,你的技巧帮助我消除了第二个错误,但第一个仍然存在......
    • 抱歉,我对 Passport 不熟悉,所以无法为您提供帮助。
    猜你喜欢
    • 2016-02-29
    • 1970-01-01
    • 2017-08-12
    • 1970-01-01
    • 2016-10-19
    • 1970-01-01
    • 2016-10-29
    • 2017-03-21
    • 1970-01-01
    相关资源
    最近更新 更多