Advanced Node and Express - Hashing Your Passwords

Advanced Node and Express - Hashing Your Passwords

Hi, I get the following message after run the test:

You should use hash the password in the registration.

On glitch I have not any error, and the registration-login-logout works fine as expected.

Here is my code:

'use strict';

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

const app = express();

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
}));
app.use(passport.initialize());
app.use(passport.session());

mongo.connect(process.env.DATABASE, (err, db) => {
  if (err) {
    console.log("Database error:", err);
  } else {
    console.log("Successful database connection.");
    const dbo = db.db("cluster0-l7ww6");
    // serialisation and app listen...
    passport.serializeUser((user, done) => {
      done(null, user._id);
    });
    
    passport.deserializeUser((id, done) => {
      dbo.collection("users").findOne({_id: new ObjectID(id)}, (err, doc) => {
        done(null, doc );
      });
    });
    
    passport.use(new LocalStrategy((username, password, done) => {
      dbo.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 (!(bcrypt.compareSync(password, user.password))) return done(null, false);
        return done(null, user);
      });
    }));
    
    const ensureAuthenticated = (req, res, next) => {
      if (req.isAuthenticated()) return next();
      res.redirect("/");
    };
    
    app.route('/')
      .get((req, res) => {
        res.render(__dirname + "/views/pug/index.pug", {
          title: "Home Page ",
          message: "Please login",
          showLogin: true,
          showRegistration: true
        }); 
      })
    ;
    
    app.route("/login")
      .post(passport.authenticate("local", {failureRedirect: "/"}), (req, res) => {
        res.redirect("/profile");
    });
    
    
    app.route("/profile")
      .get(ensureAuthenticated, (req, res) => {
        res.render(__dirname + "/views/pug/profile.pug", {
          username: req.user.username
        });
    });
    
    app.route("/register")
      .post((req, res, next) => {
      dbo.collection("users").findOne({username: req.body.username}, (err, user) => {
        if (err) {
          next(err);
        } else if (user) {
          res.redirect("/");
        } else {
          const hash = bcrypt.hashSync(req.body.password, 8)
          dbo.collection("users").insertOne({
            username: req.body.username,
            password: hash
          }, (err, doc) => {
            if (err) {
              res.redirect("/");
            } else {
              next(null, user);
            }
          });
        }
      });
    }, passport.authenticate("local", {failureRedirect: "/"}), (req, res, next) => {
      res.redirect("/profile");
    });
    
    app.route("/logout")
      .get((req, res) => {
        req.logout();
        res.redirect("/");
    });
    
    // handling missing page(404):
    app.use((request, response, next) => {
      response.status(404)
        .type("text")
        .send("Not found");
    });
    
    app.listen(process.env.PORT || 3000, () => {
      console.log("Listening on port " + process.env.PORT);
    });
  }
});

Have you managed to pass it or no? If yes, what was the trick? Thank you!

Hi,

Yes, I passed the test.
Here is the full source: glitch
I created another module, named auth.js
I hope the source will help you to find the issue.

@lendoo I tried your code it doesn’t pass the tests . I cant pass the tests also. I don’t know what to do

Hi rahmatisina,

I went to check this issue. As I see the app is works well, I can register, I can log in, log out. The database works well… I passed this test with the above linked code. But right now my code also fails on the test

BCrypt should be correctly required and implemented.

Check your code as well. Is your database save the user info? Is the password hashed? Can you register? Can you log in? Log out? If yes, just simple go to the next challenge. Do not worry too much about the fails test. I think so this is not your fault. Probably have to report this issue.

As I see I used the version of 3.0.6
Please check the documentation of bcrypt.
But has been released a new version: 4.0.1
Try your code with the latest version. Also have to modify a bit because this is not compatibility with the previous one.
If still fails on the test but your app works well just go on…

Hi @lendoo ,

Thanks for taking time looking into my code. Yes it works fine. It saves the user and pass in mongo and everything is fine with it. The passwords are all hashed in the database.

Can i get a certificate without passing a test? In that case, i just go through the material and jump to projects. I am a data scientist and this course is taking too much of my time for passing tests.

I used to love this course but recently its getting very confusing for me. I don’t know if other people feel the same.

Yes, you can get the certifications. I have built several project withouth to pass all user stories. Example my Markdown Previewer failed at the test of the first user story. But this is not mean my code is fails in reality. This mean only: impossible to write a test environment what will pass all correct code and will fails wrong code. There is million way to get the exaclty same result in coding. Any code allways will fails on the test howerer the code is good. Just do the best. Belive me, the certificate mean nothings. Only that matters how you resolve a coding problem.