title: How can I manage sessions with Passport JS for some routes using express?
body: <p>I got below <strong><code>express</code></strong> <strong><code>node.js</code></strong> <em>server code</em> using <strong><code>Passport</code></strong>. At it my whole routes definition depends upon a MongoDB connection using <strong><code>mongo-db</code></strong> but model used by Passport is done through another connection by <strong><code>mongoose</code></strong>. I mention these two details cause I think it should also be coded in a better way.</p>
  
  <p><strong>However, the main problem is that even though Passport it's doing it's work, I still can go to <code>localhost/registro</code> directly no matter I didn't <em>logged in</em> first.</strong></p>
  
  <p>When someone tried to access to <code>localhost/registro</code> it should be redirected to start page if a login and authentication wasn't done first.</p>
  
  <p>I care about a safe implementation of it, I'd also like to have some information about the <em>user</em> during the session time.</p>
  
  <p>I'm quite confused about what I should try, cookies, sessions, etc. Apart that in new express version middlewares work different than before.</p>
  
  <p>This is my <code>server.js</code>:</p>
  
  <pre><code>var express =       require('express')
  var mongodb =       require('mongodb')
  var mongoose =      require('mongoose')
  var bodyParser =    require('body-parser')
  var passport =      require('passport')
  var LocalStrategy = require('passport-local').Strategy;
  
  var app = express()
  
  var BSON = mongodb.BSONPure
  
  app.use(passport.initialize());
  app.use(passport.session());
  
  app.use(express.static(__dirname+"/public"))
  app.use(bodyParser())
  
  var MongoDBClient = mongodb.MongoClient
  
  mongoose.connect('mongodb://localhost/psicologosTuxtepecDB')
  
  var Schema = mongoose.Schema
  var userCredential = new Schema({
  
      username:   String,
      password:   String
  
  },  {
      collection:     'members'
  })
  
  var userCredentials = mongoose.model('members', userCredential)
  
  passport.serializeUser(function(user, done) {
    done(null, user);
  })
  
  passport.deserializeUser(function(user, done) {
    done(null, user);
  })
  
  passport.use(new LocalStrategy(function(username, password, done) {
    process.nextTick(function() {
      userCredentials.findOne({
        'username': username, 
      }, function(err, user) {
        if (err) {
          return done(err);
        }
  
        if (!user) {
          return done(null, false);
        }
  
        if (user.password != password) {
          return done(null, false);
        }
  
        return done(null, user);
      });
    });
  }));
  
  MongoDBClient.connect("mongodb://localhost/psicologosTuxtepecDB", function (error, psicologosTuxtepecDB) {
  
      if (error) {
  
          console.log("We've got a connection error, so far we should take this function better for a correct debug")
      }
  
      else {
  
          console.log("Connection to psicologosTuxtepecDB has been successful")
  
          // Seleccionamos una colección
          var psicologosCollection = psicologosTuxtepecDB.collection("psicologos")
  
          app.get('/registro', function(request,response) {
  
              response.sendfile("public/html/registro.html")
          })
  
          // Cuando nos hagan una petición HTTP de tipo POST en la ruta psicologos...
          app.post("/psychos", function(request, response) {
  
              var psychologist = {
  
                  personalData:           request.body._personalData,
                  professionalData:       request.body._professionalData,
                  professionalInterests:  request.body._professionalInterests
              }
  
  
              psicologosCollection.insert(psychologist, function(error, responseFromDB) {
  
                  if (error) {response.send(responseFromDB)}
  
                  console.log("Se ha insertado: "+ JSON.strinfigy(responseFromDB))
                  response.send(responseFromDB)
              })
          })
  
          app.get("/psychos/:id", function(request, response) {
  
              var id = new BSON.ObjectID(peticion.params.id)
  
              psicologosCollection.findOne( 
                                              {'_id':id},
                                              function(error,responseFromDB) { if (error) {response.send(responseFromDB)} response.send(responseFromDB)}
                                          )
          })
  
          app.get("/psychos", function(request,response) {
  
              psicologosCollection.find().toArray(function(error,responseFromDB) {
                  if (error) {response.send(responseFromDB)}
                  response.send(responseFromDB)
              })
          })
  
          app.post('/login',
            passport.authenticate('local', {
              successRedirect: '/loginSuccess',
              failureRedirect: '/loginFailure'
            })
          )
  
          app.get('/loginFailure', function(req, res, next) {
              res.redirect('/')
          })
  
          app.get('registro', function(request, response) {
              response.sendfile('public/html/registro.html')
          })
  
          app.get('/loginSuccess', function(req, res, next) {
            res.redirect('/registro')
  
      })      
  
      app.listen(80, function () {
          console.log("app escuchando en el puerto Maricela fecha de nacimiento DDMM")
      })
  }
  
  })
  </code></pre>
  
  <p><strong>These are my Passport statements:</strong></p>
  
  <pre><code>app.use(passport.initialize());
  app.use(passport.session());
  passport.serializeUser(function(user, done) {
    done(null, user);
  })
  
  passport.deserializeUser(function(user, done) {
    done(null, user);
  })
  
  passport.use(new LocalStrategy(function(username, password, done) {
    process.nextTick(function() {
      userCredentials.findOne({
        'username': username, 
      }, function(err, user) {
        if (err) {
          return done(err);
        }
  
        if (!user) {
          return done(null, false);
        }
  
        if (user.password != password) {
          return done(null, false);
        }
  
        return done(null, user);
      });
    });
  }));
  </code></pre>