Saturday, 18 March 2017

Configure passport-local with express

Im trying to use passport-local with express, this is my configuration:

App.js

var app = express();

app.use(require('morgan')('combined'));
app.use(require('cookie-parser')());
app.use(require('body-parser').urlencoded({ extended: true }));
app.use(require('express-session')({ secret: 'keyboard cat', resave: false, saveUninitialized: false }));

app.use(passport.initialize());
app.use(passport.session());

app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(session({
  secret: 'my super secret',
  resave: false,
  saveUninitialized: true
}));

index.js

var MongoClient = require('mongodb').MongoClient, assert = require('assert');
var session = require('express-session');
var passport = require('passport');
var localPassport = require('passport-local').Strategy;

var url = 'mongodb://localhost:27017/mydb';

var router = express.Router();

passport.use(new localPassport(
  function(username, password, cb) {
    console.log(">>>To evaluate : " + username);
    console.log(">>>To evaluate : " + password);
    MongoClient.connect(url, function(err, db) {
      db.collection('users').find({email: username, password: password, verified: true }, {_id=0, email=1, name = 1}).toArray(function(err, results){
        console.log("Fetching results!!!!");
        console.log(results);
        if(results.length >= 1){
          console.log("<<<returning true");
          return cb(null, results[0]);
        }else{
          console.log("<<<returning 00000");
          return cb(null, false);
        }
      });
    });
  }
));

passport.serializeUser(function(user, cb) {
  cb(null, user.id);
});

passport.deserializeUser(function(id, cb) {
  db.users.findById(id, function (err, user) {
    if (err) { return cb(err); }
    cb(null, user);
  });
});


router.get('/invites', function(req, res, next) {
  require('connect-ensure-login').ensureLoggedIn(),
  console.log("~~~~~~ ~ ~~~~~ ~~~~~~~~Fetched!");
  console.log(req);
  res.render('invites.html');
});


router.post('/login', function(req, res, next) {
  //res.render('invites.html');
  //var auth = passport.authenticate('local', { failureRedirect: '/login' });
  passport.authenticate('local')(req, res, function () {
    console.log(">>>Auth: ");
    console.log(req);
            res.redirect('/invites');
        });

});

Ok, let me explain more of the code: the code is executed without problems and the method: passport.use(new localPassport is called correctly (I debugged the variables) and the result is ok

console.log("<<<returning true");
return cb(null, results[0]);

Those lines are displayed in the terminal (and not the else) then I assume that the method is ok.

But, when I'm trying to use: req.user the variable is undefined. I'm not sure why the user session is not stored in the request.

Some ideas?



via MrMins

No comments:

Post a Comment