Advanced node - registration of new users keeps failing

Tell us what’s happening:
works perfectly, but fails all tests except the first one.
I have changed line 3 of pug files as mentioned
I delete the freeCodeCamp entry on mongoDB and ensure my app is active in glitch before trying each test
I have added delays to routes
I tried downgrading some packages - I think this must be the problem somehow?

All to no avail - anyone have any ideas what can possibly still be wrong?

Your code so far

“use strict”;

const express = require("express");
const fccTesting = require("./freeCodeCamp/fcctesting.js");
const pug = require("pug");
const bodyParser = require("body-parser");
const session = require("express-session");
const passport = require("passport");

const ObjectID = require("mongodb").ObjectID;
const mongo = require("mongodb").MongoClient;
const LocalStrategy = require("passport-local");
const cors = require("cors");
//const bcrypt = require('bcrypt');

const app = express();

require("dotenv").config();

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

if (process.env.ENABLE_DELAYS)
  app.use((req, res, next) => {
    switch (req.method) {
      case "GET":
        switch (req.url) {
          case "/logout":
            return setTimeout(() => next(), 400);
          case "/profile":
            return setTimeout(() => next(), 600);
          default:
            next();
        }
        break;
      case "POST":
        switch (req.url) {
          case "/login":
            return setTimeout(() => next(), 800);
          default:
            next();
        }
        break;
      default:
        next();
    }
  });
//console.log("our env is "+JSON.stringify(process.env.DATABASE));
// DATABASE is my database, but using codecamps db to pass tests
//using DB_URI for testing
mongo.connect(
  process.env.DATABASE,
  //{ useUnifiedTopology: true },
  (err, client) => {
    var db = client.db("pug");
    if (err) {
      console.log(db + "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, user) => {
            done(null, user);
          }
        );
      });

      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);
            } else {
              console.log("successfull login of user: " + JSON.stringify(user));
              return done(null, user);
            }
          });
        })
      );
      
      function ensureAuthenticated(req, res, next) {
        if (req.isAuthenticated()) {
          return next();
        }
        console.log("user not authenticated");
        res.redirect("/");
      }

      app.route("/").get((req, res) => {
        //Change the response to render the Pug template
        res.render(process.cwd() + "/views/pug/index", {
          title: "Home Page",
          message: "login",
          showLogin: true,
          showRegistration: true
        });
      });

      app
        .route("/login")
        .post(
          passport.authenticate("local", { failureRedirect: "/" }),
          (req, res) => {
            console.log("post to /login with " + JSON.stringify(req.body));
            // might need to store user on 'session' variable? var req.session.user=req.user;
            req.session.username = req.user.username;
            console.log("user found? " + JSON.stringify(req.user));
            res.redirect("/profile");
            //  res.send("hi");
          }
        );

      app.route("/profile").get(ensureAuthenticated, (req, res) => {
        const username = req.session.username;
        delete req.session.username;
        
        res.render(process.cwd() +'/view/pug/profile', {username:req.user.username});
        
//        req.logIn(req.user, err => {
//          err
//            ? next(err)
//            : res.render(process.cwd() + "/views/pug/profile", {
 //               title: "Profile Home Page",
 //               username: req.user
  //            });
  //      });
      });

      app.route("/register").post(
        (req, res, next) => {
          //    var hash = bcrypt.hashSync(req.body.password, 12);
          db.collection("users").findOne(
            { username: req.body.username },
            (err, user) => {
              if (err) {
                next(err);
              } else if (user) {
                console.log(
                  JSON.stringify(user.username) + " Already exists in Db"
                );
                req.session.username = user.username;
                res.redirect("/");  // I think should be redirected to /profile...but pass tests
                // res.render(process.cwd() + "/views/pug/index", {
                //       title: 'Hello',
                //       message: 'Already a member',
                //       showLogin: true,
                //       showRegistration: true });
              } else {
                db.collection("users").insertOne(
                  {
                    username: req.body.username,
                    password: req.body.password
                  },
                  (err, user) => {
                    if (err) {
                      res.redirect("/");
                    } else {
                      next(null, user);
                    }
                  }
                );
              }
            }
          );
        },
        passport.authenticate("local", { failureRedirect: "/" }),
        (req, res, next) => {
          res.redirect("/profile");
        }
      );

      app.route("/logout").get((req, res) => {
        console.log("Logged out");
        req.logout();
        res.redirect("/");
      });
      
      app.use((req, res, next) => {
          res.status(404)
            .type('text')
            .send('Not Found');
        });

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

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.89 Safari/537.36.

Challenge: Registration of New Users

Link to the challenge:

Hello there,

I know there are issues with these lessons, but the general principles of how to use the serialisation-registration-deserialisation still stands.

So, I suggest you make sure you understand the topic content, then use the work-arounds to pass the tests:

  1. Add this to your session middleware:
cookie: { secure: false },
  1. Have a look at the tests for each lesson, and add the text the tests are searching for. If you are confident with regex, this is a breeze:
    https://github.com/freeCodeCamp/freeCodeCamp/blob/master/curriculum/challenges/english/06-quality-assurance/advanced-node-and-express/registration-of-new-users.english.md

Hope this helps

fantastic info!
I will try that.

thanks Sky!!!

Hey Guys;
I looked at the 2nd and 3rd tests and it seems all that the test is looking for is the word ‘Profile’ - to indicate we are on the Profile page.
And looks like 4th and 5th tests are just looking for ‘Home’ to indicate “/” index page.

Is that correct? Cuz my code does that right?

I have tried everything , and it all works perfectly, but fails tests. I’m guessing something silly with pug or I need to downgrade my packages or something?

This is my complete project:

Thanks

Yes, you are correct about the tests.

To me, this is looking like a Glitch problem. When I run the tests, they pass intermittently. So, I suggest you make use of trying the project in Repl.it. If you go to the project README.md, you will see a little button saying “run on repl.it”.

Users have had success using that or CodeSandbox.

Hope this helps

That’s a great idea!!!

I’ll try repl.it now.

Thanks again Sky!!!

Paul

Hey Guys;
Strange, but my index page works, but other routes don’t. I built this in Glitch, exported to gitHub, then imported to Redl.it from Git, all seems good but getting this routing error.

Error: Failed to lookup view “/pug/profile” in views directory “/home/runner/authentication/views”

Any ideas how to get it to ‘see’ these files?

This snip img shows my file is there in that directory:

14 days ago ·

·

Hey Sky;
I have re-built in repl.it, resolved the package issues above, and it’s now running perfectly, but is not passing tests.
Any ideas how to get around this?

https://boilerplate-advancednode.pauloconnell.repl.co


const express = require("express");
const fccTesting = require("./freeCodeCamp/fcctesting.js");
const app = express();
const pug = require("pug");
const bodyParser = require("body-parser");
const session = require("express-session");
const passport = require("passport");

const ObjectID = require("mongodb").ObjectID;
const mongo = require("mongodb").MongoClient;
const LocalStrategy = require("passport-local");
const cors = require("cors");
//const bcrypt = require('bcrypt');


require("dotenv").config();


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.use(cors());
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,
    cookie: {secure: false}
  })
   //      {cookie:{secure: false}})
);
app.use(passport.initialize());
app.use(passport.session());


// delays on GET requests as Tests don't allow for API call time
if (process.env.ENABLE_DELAYS)
  app.use((req, res, next) => {
    switch (req.method) {
      case "GET":
        switch (req.url) {
          case "/logout":
            return setTimeout(() => next(), 300);
          case "/profile":
            return setTimeout(() => next(), 300);
          default:
            next();
        }
        break;
      case "POST":
        switch (req.url) {
          case "/login":
            return setTimeout(() => next(), 300);
          default:
            next();
        }
        break;
      default:
        next();
    }
  });


mongo.connect(
  process.env.DATABASE,
  { useUnifiedTopology: true },
  (err, client) => {
    var db = client.db("pug");
    if (err) {
      console.log(db + "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, user) => {
            done(null, user);
          }
        );
      });

      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);
            } else {
              console.log("successfull login of user: " + JSON.stringify(user.username));
              return done(null, user);
            }
          });
        })
      );
      
   

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

      app
        .route("/login")
        .post(
          passport.authenticate("local", { failureRedirect: "/" }),
          (req, res) => {
            console.log("post to /login with " + JSON.stringify(req.body));
           
            //req.session.username = req.user.username;
            //console.log("user found? " + JSON.stringify(req.user));
            res.redirect(200, "/profile" );
        // cut out {username:req.user.username}
            //  res.send("hi");
          }
        );

      app.route("/profile").get(ensureAuthenticated, (req, res) => {
        //const username = req.session.username;
       // delete req.session.username;
        res.render(process.cwd()+ "/views/pug/profile", {username:req.user.username, title:"Profile"});
        
//        req.logIn(req.user, err => {
//          err
//            ? next(err)
//            : res.render(process.cwd() + "/views/pug/profile", {
 //               title: "Profile Home Page",
 //               username: req.user
  //            });
  //      });
      });

      
      app.route('/register')
      .post((req, res, next) => {
          //    var hash = bcrypt.hashSync(req.body.password, 12);
          db.collection('users').findOne(
            { username: req.body.username },
            (err, user) => {
              if (err) {
                next(err);
              } else if (user) {
                console.log(
                  JSON.stringify(user.username) + " Already exists in Db"
                );
                //req.session.username = user.username;
                res.redirect("/");  // I think should be redirected to /profile here
                // res.render(process.cwd() + "/views/pug/index", {
                //       title: 'Hello',
                //       message: 'Already a member',
                //       showLogin: true,
                //       showRegistration: true });
              } else {
                db.collection("users").insertOne(
                  {
                    username: req.body.username,
                    password: req.body.password
                  },
                  (err, user) => {
                    if (err) {
                      res.redirect("/", );
                    } else {
                      // req.session.username = user.username;
                      next(null, user);
                    }
                  }
                );
              }
            }
          );
        },
        passport.authenticate("local", { failureRedirect: "/" }),
        (req, res, next) => {
          
          res.redirect("/profile");
        }
      );

   function ensureAuthenticated(req, res, next) {
        if (req.isAuthenticated()) {
          return next();
        }
        //console.log("user not authenticated");
        res.redirect( "/");
      }

      app.route("/logout").get((req, res) => {
        console.log("Logged out");
        req.logout();
        res.redirect("/");
      });
      
      app.use((req, res, next) => {
          res.status(404)
            .type('text')
            .send('Not Found');
        });

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

Hey paul.

Which tests are you trying to pass?

Hey Sky;
It’s the registering new users, all tests are failing except the first:


But it all works manually.
Any ideas?
I like repl.it better than glitch, and also found chrome was really slow, so switched to Firefox and it’s nice and quick.

Well done, if you have managed to get it to work manually.

In that case, i suggest you go to the tests: https://github.com/freeCodeCamp/freeCodeCamp/blob/master/curriculum/challenges/english/06-quality-assurance/advanced-node-and-express/registration-of-new-users.english.md

Most of them are looking to match regex. So, see if you are missing an exact pattern.

Hey Sky, Thanks again!
Perhaps I’m not sending the proper link to be tested-
I’ve circled(in blue) the url I’m using for the tests, is that what you use too?

I noticed when I’m in Repl.it and logged into the profile page, the URL doesn’t change to /profile(as seen above), but if you open new page it will display the URL with /profile…strange, but I’m not thinking that’s relevant.

Yes, the circled link is the one to use. However, it should not change, based on the fCC tests’ input, because they are nothing but HTTP requests.

So, the way you should be testing, is by manually placing the endpoints in the URL bar.

I can take a look at your code, later today, and make sure there is no funny business happening.

Actually, just submitting it quickly, I see these errors in the browser console:

I would try adding the package cors to your project, and using it in your server.js file:

const cors = require('cors');
app.use(cors());

Let me know if this helps.

If that does not help, please try the following:

  1. Navigate to the freecodecamp/fcctesting.js file
  2. Scroll to the first app.use statement
  3. Replace it with this:
app.use(function (req, res, next) {
      const origin = req.get('origin');
      if (allowedOriginsMatcher.test(origin)) {
            res.setHeader('Access-Control-Allow-Origin', 'https://www.freecodecamp.org');
      }
      res.setHeader('Access-Control-Allow-Credentials', true);
      next();
  });

Actually (I am new to Repl.it), have I changed the code already? I am unsure if the link you provided has allowed me to change your project directly or not.

Hey Sky,
Strange, but I get no errors at all in firefox, which browser did you use to get all those errors? In Chrome I get this strange ‘alert’ regularly:

Also in chrome it has several of these warnings(but not in firefox)…tried tests in firefox, but still no dice.

DevTools failed to load SourceMap: Could not load content for https://repl.it/_next/static/chunks/a0c91d084f5abf86bcd6de9d1202af738467fe79.0c8b8d81dd45a9701339.js.map: HTTP error: status code 404, net::ERR_HTTP_RESPONSE_CODE_FAILURE
boilerplate-advancednode#README.md:1 A cookie associated with a cross-site resource at http://boilerplate-advancednode--pauloconnell.repl.co/ was set without the `SameSite` attribute. It has been blocked, as Chrome now only delivers cookies with cross-site requests if they are set with `SameSite=None` and `Secure`. You can review cookies in developer tools under Application>Storage>Cookies and see more details at https://www.chromestatus.com/feature/5088147346030592 and https://www.chromestatus.com/feature/5633521622188032.```

Sorry, I should have clarified. The errors are on the freecodecamp.org/learn page where you submit the link.

I cannot speak for the SourceMap error, though.

K cool, I’ll have a look.

Thanks :slight_smile:

Great info-I was watching my app console - But now I see the errors on the FCC submit page…
Looks like they are all CORS errors, I’ve console logged what the allow-origin variable value is…and in my console it is:
CORS debug- origin is: https://www.freecodecamp.org

But in the console running the test same output is:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at ‘https://boilerplate-advancednode.pauloconnell.repl.co/register’. (Reason: Credential is not supported if the CORS header ‘Access-Control-Allow-Origin’ is ‘*’).

I tried updating the cors header in the FCC testing file to match the testing origin, but still no dice- got this error message…strange:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://boilerplate-advancednode.pauloconnell.repl.co/_api/server.js. (Reason: CORS header “Access-Control-Allow-Origin” does not match “https://boilerplate-advancednode.pauloconnell.repl.co/_api/server.js”).

Maybe my CORS version of version 2.8.5 needs to be downgraded or something?