Advanced Node and Express - Registration of New Users

Tell us what’s happening:

I cannot pass the tests, first is the /register route, then tests number 4 and 5 which is “Logout should work” and “Profile should no longer work after logout” respectively.

This is my complete code:

'use strict';
require('dotenv').config();
const express = require('express');
const myDB = require('./connection');
const fccTesting = require('./freeCodeCamp/fcctesting.js');
const session = require('express-session');
const passport = require('passport');
const { ObjectID } = require('mongodb');
const LocalStrategy = require('passport-local');
const cors = require('cors');
const app = express();
app.use(cors({
  origin: function(origin, callback) {
    const allowedOrigins = [
      'https://www.freecodecamp.org',
      // Using a RegExp to match any subdomain of gitpod.io
      // This is crucial for dynamic Gitpod URLs like 3000-your-username-xyz.ws-us120.gitpod.io
      new RegExp('^https://.*\\.gitpod\\.io$')
    ];

    if (!origin) {
      // Allow requests with no origin (e.g., same-origin requests, or internal server-to-server)
      callback(null, true);
      return;
    }

    // Check if the origin matches any of the allowed patterns
    const isAllowed = allowedOrigins.some(pattern => {
      if (typeof pattern === 'string') {
        return pattern === origin;
      } else if (pattern instanceof RegExp) {
        return pattern.test(origin);
      }
      return false;
    });

    if (isAllowed) {
      callback(null, true); // Allow the origin
    } else {
      // Disallow the origin. Provide a clearer error message than a generic Error.
      callback(new Error(`Not allowed by CORS. Origin: ${origin}`));
    }
  },
  credentials: true, // Allow cookies to be sent
  methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'], // Explicitly allowed HTTP methods
  allowedHeaders: ['Content-Type', 'Authorization', 'X-Requested-With', 'Cookie'] // Explicitly allowed headers
}));
app.set('view engine', 'pug');
app.set('views', './views/pug');

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

app.use(passport.initialize());
app.use(passport.session());

fccTesting(app); // For fCC testing purposes
app.use('/public', express.static(process.cwd() + '/public'));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

myDB(async client => {
  const myDataBase = await client.db('database').collection('users');

  app.route('/').get((req, res) => {
    res.render('index', {
      title: 'Connected to Database',
      message: 'Please log in',
      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('profile', { username: req.user.username });
  });

  app.get('/logout', (req, res) => {
  req.logout(); // no callback in v0.4.x
  req.session.destroy((err) => {
    if (err) {
      console.log('Session destruction error:', err);
    }
    res.redirect('/');
  });
});

  app.route('/register')
  .post((req, res, next) => {
    myDataBase.findOne({ username: req.body.username }, (err, user) => {
      if (err) {
        next(err);
      } else if (user) {
        res.redirect('/');
      } else {
        myDataBase.insertOne({
          username: req.body.username,
          password: req.body.password
        },
          (err, doc) => {
            if (err) {
              res.redirect('/');
            } else {
              // The inserted document is held within
              // the ops property of the doc
              next(null, doc.ops[0]);
            }
          }
        )
      }
    })
  },
    passport.authenticate('local', { failureRedirect: '/' }),
    (req, res, next) => {
      res.redirect('/profile');
    }
  );

  app.use((req, res, next) => {
    res.status(404)
      .type('text')
      .send('Not Found');
  });

  passport.use(new LocalStrategy((username, password, done) => {
    myDataBase.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);
    });
  }));

  passport.serializeUser((user, done) => {
    done(null, user._id);
  });
  
  passport.deserializeUser((id, done) => {
    myDataBase.findOne({ _id: new ObjectID(id) }, (err, doc) => {
      done(null, doc);
    });
  });

}).catch(e => {
  app.route('/').get((req, res) => {
    res.render('index', { title: e, message: 'Unable to connect to database' });
  });
});

function ensureAuthenticated(req, res, next) {
  if (req.isAuthenticated()) {
    return next();
  }
  res.redirect('/');
};
  
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Listening on port ${PORT}`);
});

I have checked the link to projects completed up to this point:

and even the code given there could not pass.
P.S. I can manually Login, Register, or Logout. The profile page is displayed correctly. I just can’t pass the test suite from FCC.

###Your project link(s)

solution: https://3000-freecodecam-boilerplate-ynu0cibmjmd.ws-us120.gitpod.io

Your browser information:

User Agent is: Mozilla/5.0 (X11; Linux x86_64; rv:139.0) Gecko/20100101 Firefox/139.0

Challenge Information:

Advanced Node and Express - Registration of New Users