mongodb and authenticate and passport in node.js

纵饮孤独 提交于 2019-12-10 21:32:34

问题


i have a collection like this in mongodb

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

so to authenticate i will fetch data from database and then i will check given email is exist or not with if statement like this

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");
         }
      }
   });
});

so here how to use passport module for authentication.let me know it with sample code with configuration. i am using express3.x framework .so how to configure it also.


回答1:


Here you can read about local strategies, and here about configure.

Your local strategy should look like this:

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');
                }
            });
        });
    }));


来源:https://stackoverflow.com/questions/15286824/mongodb-and-authenticate-and-passport-in-node-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!