title: Unable to login a User with passport.js
body: <p>I've decided to start getting seriously interested in <code>NodeJS</code> and I really can't figure out the problem I've stumbled upon. I obviously searched extensively on Google and tried multiple solutions but nothing worked.</p>
  <p>To summarize, I wanted to create a login system via a <code>MongoDB database</code> and I used <code>passport.js</code> to manage the login itself. The problem is that after a valid login from a user, the value of req.isAuthenticated() is always false in the middleware. I also used <code>passport-local-mongoose</code> which allows to generate directly a valid authentication for passport from a mongoose model.</p>
  <h4>app.js :</h4>
  <pre><code>const express = require('express');
  const cookieParser = require('cookie-parser');
  const cookieSession = require('cookie-session');
  const bodyParser = require('body-parser');
  
  const mongoose = require('mongoose');
  const passport = require('passport');
  
  const app = express();
  
  app.use(cookieSession({
      name: 'session',
      secret: 'secretkey',
      secure: false
  }));
  app.use(cookieParser('secretkey'));
  app.use(bodyParser.json());
  app.use(bodyParser.urlencoded({extended: true}));
  app.use(passport.initialize());
  app.use(passport.session());
  
  const User = require('./models/user.js');
  passport.use(User.createStrategy());
  passport.serializeUser(User.serializeUser());
  passport.deserializeUser(User.deserializeUser());
  
  // Connect to MongoDB
  mongoose.connect('mongodb+srv://?retryWrites=true&amp;w=majority')
      .then(() =&gt; console.log('Connecion à MongoDB réussie !'))
      .catch((error) =&gt; console.log('Connexion à MongoDB échouée !\n' + error));
  
  // Configure routes
  app.use((request, response, next) =&gt; {
      response.setHeader('Access-Control-Allow-Origin', '*');
      response.setHeader('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content, Accept, Content-Type, Authorization');
      response.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, PATCH, OPTIONS');
      next();
  });
  app.use('/api', require('./routes/authentication.js'));
  app.use('/api/projects', require('./routes/project.js'));
  app.use('/api/users', require('./routes/user.js'));
  
  module.exports = app;
  </code></pre>
  <h4>models/user.js</h4>
  <pre><code>const mongoose = require('mongoose');
  const {Schema} = require(&quot;mongoose&quot;);
  const uniqueValidator = require('mongoose-unique-validator');
  const passportLocal = require('passport-local-mongoose');
  
  const userSchema = new Schema({
      email: {type: String, required: false},
      picture: {type: String, required: false},
      roles: {type: [String]},
  });
  
  userSchema.plugin(uniqueValidator);
  userSchema.plugin(passportLocal);
  
  module.exports = mongoose.model('user', userSchema);
  </code></pre>
  <h4>routes/authentication.js :</h4>
  <pre><code>const express = require('express');
  const router = express.Router();
  const passport = require(&quot;passport&quot;);
  const User = require('../models/user');
  
  router.post(&quot;/login&quot;, (req, res, next) =&gt; {
      console.log('authentication attempt with username: ' + req.body.username);
      passport.authenticate('local', {username: req.body.username, password: req.body.password}, (err, user, info) =&gt; {
          if (err)
              return next(err);
          if (!user)
              return res.status(400).send([user, &quot;Cannot log in&quot;, info]);
          req.login(user, {}, (error) =&gt; {
              if (error) {
                  console.log('error: ' + error);
                  res.send(&quot;Error while login&quot;);
              } else {
                  console.log('=&gt; authenticated ' + user.username + ': ' + req.isAuthenticated());
                  res.send(&quot;Logged in&quot;);
              }
          });
      })(req, res, next);
  });
  
  router.get('/logout', function (req, res) {
      req.logout();
      console.log(&quot;logged out&quot;)
      return res.send();
  });
  
  const authMiddleware = (req, res, next) =&gt; {
      if (req.isAuthenticated()) {
          return next();
      } else {
          res.status(401).send('You are not authenticated')
      }
  };
  
  router.get(&quot;/user&quot;, authMiddleware, (req, res) =&gt; {
      let user = User.find({'id': req.session._passport._user});
  
      console.log([user, req.session])
      res.send({'user': user})
  });
  
  module.exports = router;
  </code></pre>
  <p>Thank you in advance for your answers!</p>