Registration of New Users-Advanced Node and Express

Still can not find out what is wrong with the code I have written,can you please help?
I cannot pass Login Should Work and Register Should Work.
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 mongoClient       = require('mongodb').MongoClient;
const ObjectID    = require('mongodb').ObjectID;
const LocalStrategy = require('passport-local');

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());

mongoClient.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(
          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: 'Home Page', message: '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(process.cwd() + '/views/pug/profile', {username: req.body.username, title: 'Profile Page'});
          });
      
        app.route('/register')
          .post((req, res, next) => {
              db.collection('users').findOne({ username: req.body.username }, function (err, user) {
                  if(err) {
                      next(err);
                  } else if (user) {
                      res.redirect('/');
                  } else {
                      db.collection('users').insertOne(
                        {username: req.body.username,
                         password: req.body.password},
                        (err, doc) => { 

                            if(err) {
                                res.redirect('/');
                            }  else {
                                res.redirect('/profile');
                            }
                        }
                      )
                  }
              })},
            passport.authenticate('local', { failureRedirect: '/' }),
            (req, res, next) => {
                res.redirect('/profile');
            }
        );
      
        app.route('/logout')
          .get((req, res) => {
              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);
        });  
}});

1 Like

Try:

const cors = requires(‘cors’);

The tests for this unit rely on cors but don’t explicitly direct it to be required, and don’t include it in the formatted starting packet. Some people have pointed this out as a flaw (and there certainly are flaws in the unit), but if we want to code professionally then incomplete requirements is something we’ll need to grow a thick skin to :). From that perspective, it’s a feature.

If this doesn’t solve the problem, search the forum for Advanced Node and Express – leaving out ‘Registration of New Users’. This unit of FCC is relatively new and has undergone some overhauls. A few tips for this lesson are buried in threads about the unit in general.

You may also need to rename the Home Page to “Home page” in the html file. The tests run a regex for that (case insensitive I believe) but never instruct you to change it.

2 Likes

Barayturk, did you ever manage to solve the issue?

Not yet…:tired_face::tired_face::tired_face::tired_face::tired_face::tired_face::tired_face::tired_face::tired_face::tired_face::tired_face:

make sure:
index.pug line3=> title Home Profile
profile.pug line3=> title Profile Home

1 Like