Advanced Node and Express - How to Use Passport Strategies

Advanced Node and Express - How to Use Passport Strategies
0

#1

Unknown authentication strategy “local” error.
I even compared with the solution provided on gitHub here .
Still not getting it where is the actual problem. Help me out.
My code so far,

'use strict';

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

const app = express();

fccTesting(app); //For FCC testing purpose
app.use(cors());
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());


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

mongo.connect(process.env.DATABASE, (err, db) => {
  if(err) console.log('Database error', err);
  else {
    passport.serializeUser((user, done) => {
      done(null, user._id);
    });
    
    app.listen(process.env.PORT || 3000, () => {
      console.log("Listening on port " + process.env.PORT);
    });
    
    passport.deserializeUser((id, done) => {
      db.collection('users').fineOne({_id: new ObjectID(id)}, (err, doc) => {
    });
      
    passport.use(new LocalStrategy(function(username, password, done) {
      db.collection('users').findOne({username: username}, (err, user) =>{
        console.log(username, 'tried to log in');
        
        if(err) return done(err);
        if(!user) return done(null, false);
        if(!password) return done(null, false);
        return done(null, user)
      });
    }));
  });
    
  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) => {
    res.redirect('/profile');
  });
    
    app.route('/profile').get((req, res) => {
      res.render(process.cwd() + '/views/pug/profile.pug')
    });
  }
});

Problem link

Glith url of my solution.

Thanks in advance!!!


#2
const LocalStrategy = require('passport-local').Strategy;

Try just

const LocalStrategy = require('passport-local');

#3

I tried that first. This one I used after seeing in stackoverflow. Both does not work.