Advanced Node and Express - Create New Middleware Test bug

Tell us what’s happening:
The automated test is failing even though the functionality is in place. In particular, it seems to not be picking up the /profile to / redirect.

Your code so far
“use strict”;

const express = require(“express”);
const fccTesting = require("./freeCodeCamp/fcctesting.js");
const pug = require(“pug”);
const passport = require(“passport”);
const session = require(“express-session”);
const mongoose = require(“mongoose”);
const ObjectID = require(“mongodb”).ObjectID;
const mongo = require(“mongodb”).MongoClient;
const LocalStrategy = require(“passport-local”);
require(“dotenv”).config;

const app = express();

fccTesting(app); //For FCC testing purposes
app.use("/public", express.static(process.cwd() + “/public”));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
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());

function ensureAuthenticated(req, res, next) {
if (req.isAuthenticated()) {
return next();
}
res.redirect(’/’);
}

mongo.connect(process.env.DATABASE, (err, client) => {
if (err) {
console.log("Database error: " + err);
} else {
console.log(“Successful database connection”);
let db = client.db(“FreeCodeCamp”);
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(
  function(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.listen(process.env.PORT || 3000, () => {
  console.log("Listening on port " + process.env.PORT);
});

}
});

app.route("/").get((req, res) => {
//Change the response to render the Pug template
res.render(‘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(ensureAuthenticated, (req, res) => {
res.render(‘pug/profile.pug’);
});

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36.

Challenge: Create New Middleware

Link to the challenge:

Hi there,

Try to edit your post and add all of the code in formatted text because its too hard to understand what’s going on.

Regards,
Abhishek

"use strict";

const express = require("express");
const fccTesting = require("./freeCodeCamp/fcctesting.js");
const pug = require("pug");
const passport = require("passport");
const session = require("express-session");
const mongoose = require("mongoose");
const ObjectID = require("mongodb").ObjectID;
const mongo = require("mongodb").MongoClient;
const LocalStrategy = require("passport-local");
require("dotenv").config;

const app = express();

fccTesting(app); //For FCC testing purposes
app.use("/public", express.static(process.cwd() + "/public"));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
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());

function ensureAuthenticated(req, res, next) {
  if (req.isAuthenticated()) {
    return next();
  }
  res.redirect('/');
}

mongo.connect(process.env.DATABASE, (err, client) => {
  if (err) {
    console.log("Database error: " + err);
  } else {
    console.log("Successful database connection");
    let db = client.db("FreeCodeCamp");
    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(
      function(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.listen(process.env.PORT || 3000, () => {
      console.log("Listening on port " + process.env.PORT);
    });
    
  }
});



app.route("/").get((req, res) => {
  //Change the response to render the Pug template
  res.render('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(ensureAuthenticated, (req, res) => {
    res.render('pug/profile.pug');
});

Hello there,

We are sorry for any frustrations this may be causing, but there are many known issues with the Advanced Node and Express section which as scheduled to be fixed: https://github.com/freeCodeCamp/freeCodeCamp/pull/39080

You can search through the mentioned issues, as there are many work arounds for now.

Hope this helps

Add the following to your index.pug file

h1 Home Page

The test looks for “Home Page” text in the “/” route even though it is not mentioned in the task description.

2 Likes

Thanks! This worked.