Advanced Node and Express - How to Use Passport Strategies- Express Passport failureRedirect not redirecting

When I add a incorrect user and password instead of redirecting to the home page I stay on the login page and get this error-

MongoError: not authorized on users to execute command { find: “users”, filter: { username: “wade.abel@itdcanada.ca” }, limit: 1, singleBatch: true, batchSize: 1, returnKey: false, showRecordId: false, $clusterTime: { clusterTime: Timestamp(1540491339, 1), signature: { hash: BinData(0, 4DEA07C284F64D0188B7BB5E2381CD87E10620E9), keyId: 6609368517177245697 } }, lsid: { id: UUID(“7dc15d3f-4e58-44d0-87fc-d33957b53955”) }, $db: “users” }
at queryCallback (/rbd/pnpm-volume/ae3b3dc0-f7ec-498b-ace3-a616cd84b8bb/node_modules/.registry.npmjs.org/mongodb-core/3.1.7/node_modules/mongodb-core/lib/cursor.js:248:25)
at /rbd/pnpm-volume/ae3b3dc0-f7ec-498b-ace3-a616cd84b8bb/node_modules/.registry.npmjs.org/mongodb-core/3.1.7/node_modules/mongodb-core/lib/connection/pool.js:532:18
at _combinedTickCallback (internal/process/next_tick.js:132:7)
at process._tickCallback (internal/process/next_tick.js:181:9)

Here is my code-


const express     = require('express');
const bodyParser  = require('body-parser');
const fccTesting  = require('./freeCodeCamp/fcctesting.js');
const pug =require('pug')
const passport= require('passport');
const session= require('express-session');
const mongo = require('mongodb').MongoClient;
const ObjectID = require('mongodb').objectID
process.env.SESSION_SECRET= 'oh so secret'
process.env.DATABASE='mongodb://wade:helloworld1@ds125293.mlab.com:25293/mydatabase';
const LocalStrategy=require('passport-local')

const app = express();
mongo.connect(process.env.DATABASE,{ useNewUrlParser: true },(err,db)=>{
  
  if(err){
    console.log('Database error' + err)
  }else{console.log('connect success')
passport.serializeUser((user,done)=>{
  done(null, user._id)
})

passport.deserializeUser((id,done)=>{
db.collection('users').findOne({
  _id:new ObjectID(id)},(err,doc)=>{
done(null,doc)}
)
})

fccTesting(app); //For FCC testing purposes
app.use('/public', express.static(process.cwd() + '/public'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(passport.initialize())
app.use(passport.session())
app.use(session({
  secret:process.env.SESSION_SECRET,
  resave:true,
  saveUninitialized:true}))
passport.use(new LocalStrategy(
  function(username,password,done){
    db.collection('users').findOne({username:username},function(err,user){
      console.log('User' + username + " attempted to log in");
      if(err){return done(err)}
      if(!user){return done(null,false)}
      if(password !== user.password){return done(null,false)}
    return done(null,user)
    })
  }
))
             
app.set('view engine','pug')

app.route('/')
  .get((req, res) => {
    res.render(process.cwd() + '/views/pug/index.pug',
               {title:'Hello',message:'Please login',showLogin:true});
  });
        
        app.route('/login')
          .post(passport.authenticate('local',{failureRedirect:'/'}),(req,res)=>{
       
        })
          

app.listen(process.env.PORT || 3000, () => {
  console.log("Listening on port " + process.env.PORT);
});
   }})    


Could anyone please steer me in the right direction? I’m not sure what im missing?

Also its actually passing the Free Code Camp tests but it just doesn’t seem right to me. I’m under the impression that it should redirect and show the home page.

Im getting the same error with the Registration of New Users section.It wont access my database and comes with the error

MongoError: not authorized on users to execute command { find: "users", filter: { username: "wade.abel@itdcanada.ca" }, limit: 1, singleBatch: true, batchSize: 1, returnKey: false, showRecordId: false, $clusterTime: { clusterTime: Timestamp(1540577735, 2), signature: { hash: BinData(0, D229341DBA59DDDF694373B3E38A47867A379546), keyId: 6609368517177245697 } }, lsid: { id: UUID("27aa977a-9df7-4e7c-8aad-0824e928647a") }, $db: "users" }
    at queryCallback (/rbd/pnpm-volume/ae3b3dc0-f7ec-498b-ace3-a616cd84b8bb/node_modules/.registry.npmjs.org/mongodb-core/3.1.7/node_modules/mongodb-core/lib/cursor.js:248:25)
    at /rbd/pnpm-volume/ae3b3dc0-f7ec-498b-ace3-a616cd84b8bb/node_modules/.registry.npmjs.org/mongodb-core/3.1.7/node_modules/mongodb-core/lib/connection/pool.js:532:18
    at _combinedTickCallback (internal/process/next_tick.js:132:7)
    at process._tickCallback (internal/process/next_tick.js:181:9)

My code has not really changed form above but here it is anyhow just in case it helps.


'use strict';

const express     = require('express');
const bodyParser  = require('body-parser');
const fccTesting  = require('./freeCodeCamp/fcctesting.js');
const pug =require('pug')
const passport= require('passport');
const session= require('express-session');
const mongo = require('mongodb').MongoClient;
const ObjectID = require('mongodb').objectID
process.env.SESSION_SECRET= 'oh so secret'
process.env.DATABASE='mongodb://wade:Helloworld1@ds125293.mlab.com:25293/mydatabase';
const LocalStrategy=require('passport-local').Strategy

const app = express();
mongo.connect(process.env.DATABASE,{ useNewUrlParser: true },(err,client)=>{
  const db = client.db('users')
  if(err){
    console.log('Database error' + err)
  }else{console.log('connect success')
passport.serializeUser((user,done)=>{
  done(null, user._id)
})

 
passport.deserializeUser((id,done)=>{
db.collection('users').findOne({
  _id:new ObjectID(id)},(err,doc)=>{
done(null,doc)
}
                               
)
})

fccTesting(app); //For FCC testing purposes
app.use('/public', express.static(process.cwd() + '/public'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(passport.initialize())
app.use(passport.session())

app.use(session({
  secret:process.env.SESSION_SECRET,
  resave:true,
  saveUninitialized:true}))

        
        passport.use(new LocalStrategy(
  function(username,password,done){
    db.collection('users').findOne({username:username},function(err,user){
      console.log('User' + username + " attempted to log in");
      if(err){return done(err)}
      if(!user){return done(null,false)}
      if(password !== user.password){return done(null,false)}
    return done(null,user)
      
    })
  }
))
             
app.set('view engine','pug')


  app.get('/',(req, res) => {
    res.render(process.cwd() + '/views/pug/index',
               {title:'Home page',message:'Please login',showLogin:true,showRegistration:true});
  });
       

Please help

Ok I finally figured it out. It may seem silly to people who are more experienced coding but to me it was invisible for a long time.

The problems stemmed from the order in which I had all the code. For starters the middleware I was using was inside where I was connecting to the Mongo database. After I got it outside and above there was still a problem. The


app.use(session({
  secret:process.env.SESSION_SECRET,
   resave: true,
  saveUninitialized: true
 
}))

was below


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

It was actually a valuable lesson for me to nut through. I now know the order and structure is still very important on the server side of Asyc code. Here is the working code-

'use strict';

const express = require('express');
const bodyParser = require('body-parser');
const fccTesting = require('./freeCodeCamp/fcctesting.js');
const pug = require('pug')
const passport = require('passport');
const app = express();
const session = require('express-session');
const mongo = require('mongodb').MongoClient;
const ObjectID = require('mongodb').ObjectId
const LocalStrategy = require('passport-local').Strategy;
fccTesting(app)

process.env.SESSION_SECRET = "lll"
process.env.ENABLE_DELAYS = true
process.env.DATABASE = 'mongodb://wadeabel:Helloworld1@ds125293.mlab.com:25293/mydatabase';

app.set('view engine', 'pug')

app.use('/public', express.static(process.cwd() + '/public'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
    extended: true
}));
app.use(session({
    secret: process.env.SESSION_SECRET,
    resave: true,
    saveUninitialized: true
}))
app.use(passport.initialize())
app.use(passport.session())


function ensureAuthenticated(req, res, next) {

    if (req.isAuthenticated()) {

        return next()
    }


    res.redirect('/')
}


mongo.connect(process.env.DATABASE, {
    useNewUrlParser: true
}, (err, client) => {
    const db = client.db('mydatabase')
    if (err) {
        console.log('Database error' + err)
    } else {
        console.log('connect success')




        passport.serializeUser((user, done) => {
            done(null, user._id)
        })


        passport.deserializeUser((id, done) => {
            db.collection('users').findOne({
                    _id: new ObjectID(id)
                }, function(err, doc) {
                    done(null, doc)

                }

            )
        })


        passport.use(new LocalStrategy(
            function(username, password, done) {
                db.collection('users').findOne({
                    username: username
                }, function(err, user) {
                    console.log('User' + username + " attempted to log in");
                    if (err) {
                        return done(err)
                        console.log(err)
                    }
                    if (!user) {
                        return done(null, false)
                        console.log('ohoh')
                    }
                    if (password !== user.password) {
                        return done(null, false)
                        console.log('ohoh')
                    }
                    console.log('ohoh')
                    return done(null, user)

                })
            }
        ))



        app.get('/', (req, res) => {
            res.render(process.cwd() + '/views/pug/index', {
                title: 'Home page',
                message: 'Please login',
                showLogin: true,
                showRegistration: true
            });
        });


        app.post('/login', passport.authenticate('local', {
            failureRedirect: '/'
        }), (req, res) => {
            res.redirect('/profile')
        })


        app.get('/profile', ensureAuthenticated, (req, res, next) => {

            console.log(req)
            res.render(process.cwd() + '/views/pug/profile', {
                username: req.user.username
            })

        })

        app.route('/register').
        post((req, res, next) => {
                db.collection('users').findOne({
                    username: req.body.username
                }, function(err, user) {
                    if (err) {
                        next(err)
                        console.log(err)

                    } else if (user) {
                        res.redirect('/');
                    } else {
                        console.log('hi')
                        db.collection('users').insertOne({
                                username: req.body.username,
                                password: req.body.password
                            },
                            (err, doc) => {
                                if (err) {
                                    res.redirect('/');
                                    console.log(err)
                                } else {
                                    next(null, user);
                                }
                            }
                        )
                    }
                })
            },
            passport.authenticate('local', {
                failureRedirect: '/'
            }),
            (req, res, next) => {

                console.log('letmeout')
                res.redirect('/profile');
            }
        );




        app.get('/logout', (req, res) => {
            req.logout();
            res.redirect('/');
        })




        app.use((req, res, next) => {
            res.status(404).type('text').send('No Found');
        })


        app.listen(process.env.PORT || 3000, () => {
            console.log("Listening on port " + process.env.PORT);
        });
    }
})
4 Likes