silvesterprabu
silvesterprabu

Reputation: 1457

mongodb and authenticate and passport in node.js

i have a collection like this in mongodb

{
   username:silver,
   Email:[email protected],
   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:[email protected]}).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.

Upvotes: 3

Views: 4737

Answers (1)

msmirnov
msmirnov

Reputation: 121

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': [email protected]
                        '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');
                }
            });
        });
    }));

Upvotes: 3

Related Questions