【问题标题】:mongodb and authenticate and passport in node.jsmongodb和node.js中的身份验证和护照
【发布时间】:2013-02-23 13:46:50
【问题描述】:

我在 mongodb 中有一个这样的集合

{
   username:silver,
   Email:sil@gmail.com,
   password:silvester,
}

所以要进行身份验证,我将从数据库中获取数据,然后我将使用这样的 if 语句检查给定的电子邮件是否存在

app.post("/login",function(req,res){

   var email=req.body['emailid'];

   collection.find({email:sil@gmail.com}).toArray(function(err,res)
   {
      if(res.length==0){
         console.log("name is not exist");
      }else{
         if(res.email==email){
            console.log("email is exist");
         }else{
            console.log("not exist");
         }
      }
   });
});

所以在这里如何使用护照模块进行身份验证。让我知道它与配置的示例代码。 我正在使用 express3.x 框架。所以如何配置它。

【问题讨论】:

    标签: node.js mongodb authentication passport.js


    【解决方案1】:

    Here 可以阅读本地策略,here 可以阅读配置。

    您的本地策略应如下所示:

    passport.use(new LocalStrategy({
            emailField: 'email',
            passwordField: 'passw',
        },
    
        function (emailField, passwordField, done) {
            process.nextTick(function () {
                db.collection(dbCollection, function (error, collection) {
                    if (!error) {
                        collection.findOne({
                            'email': sil@gmail.com
                            'password': silvester // use there some crypto function
                        }, function (err, user) {
                            if (err) {
                                return done(err);
                            }
                            if (!user) {
                                console.log('this email does not exist');
                                return done(null, false);
                            }
                            return done(null, user);
                        });
                    } else {
                        console.log(5, 'DB error');
                    }
                });
            });
        }));
    

    【讨论】:

    • 我是否应该在 app.post('/login',function(req,res){passport.use(new LocalStrategy({ emailField: 'email', passwordField: ' passw', }, }) 告诉我..
    • 我不确定这是个好主意。另外,不要忘记passport.serializeUser 和passport.deserializeUser。
    • 如何使用passport验证mongodb的数据。
    • 在您的app.post 中,您可以使用passport.authenticate。所有这些信息都在documentation
    • 我的疑问是在提供电子邮件 ID 和密码等登录数据后,我将使用 app.post() 将其发布到服务器,因此在如何传递该数据后,我将在 post 方法中将该值保存在不同的变量中通过使用 passport.use() 或 passport.authenticate() 然后如何检查数据是否存在是数据库(我不是在谈论查询,我在问我必须在哪里编写该查询以及如何比较该数据)我我对 node.js 不熟悉,所以请告诉我。谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-06-22
    • 2013-08-26
    • 2023-04-08
    • 1970-01-01
    • 2011-04-13
    • 2022-01-08
    • 1970-01-01
    相关资源
    最近更新 更多