Issue with 'How to use Passport strategies' in Advanced Node and Express

Issue with 'How to use Passport strategies' in Advanced Node and Express
0.0 0

#1

I’m having an issue with this challenge how to use passport strategies, as my test fails on second requirement. It says that I need to redirect to ‘/’ after login request. As far as I can see, I’m redirecting it, but the test still fails.
And here is my code:

'use strict';

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

const app = express();

fccTesting(app); //For FCC testing purposes

app.use(cors());
app.use('/public', express.static(process.cwd() + '/public'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));


// set up a template engine
app.set('view engine', 'pug');

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


// connect to database
mongo.connect(process.env.DATABASE, (err, db) => {
  if (err) {
    console.log('Database error: ' + err);
  } else {
    console.log('Successful database connection');
    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);
      });
    });
    
    
    passport.use(new LocalStrategy((username, password, done) => {
      db.collection('users').findOne({ username: username }, (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.route('/')
      .get((req, res) => {
      res.render(process.cwd() + '/views/pug/index', { 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');
      });
    
    app.listen(process.env.PORT || 3000, () => {
      console.log("Listening on port " + process.env.PORT);
    });
  }
});

I would appreciate any help…


#2

Try changing the title on your homepage to “Home page”. It should work.


#3

thanks, it worked! :smiley: