Advanced-node-and-express/create-new-middleware

Challenge: create-new-middleware

Link to the challenge:
https://www.freecodecamp.org/learn/information-security-and-quality-assurance/advanced-node-and-express/create-new-middleware

This is working properly in practice but does not pass the test. (A Get request to /profile should correctly redirect to / since we are not authenticated.)

What should i do instead?

code so far


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 LocalStrategy = require("passport-local");
const app = express();
const mongo = require("mongodb").MongoClient;
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.set("view engine", "pug");

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

const url = process.env.DATABASE_URI;

mongo.connect(url,{ useUnifiedTopology: true }, function(err, client) {
  if (err) {
    console.log(err);
    return;
  }
  console.log("Connected successfully to server");

  const db = client.db("test");
  app.use(passport.initialize());
  app.use(passport.session());
  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 }, 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);
      });
    })
  );

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

  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(ensureAuthenticated, (req, res) => {
    res.render(process.cwd() + "/views/pug/profile");
  });

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

2 Likes

Try to put

app.route("/")

last (after ā€œ/profileā€).

didnt work. but thanks

found the problem. The test expects for the title variable to be ā€˜Home Pageā€™. had to change it in the index route. (title: ā€œHome pageā€)

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

That did not work for me, but this did

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

i do not understand. where does it request the user to put { title: 'Home Page '} ??