FCC Adv Node Test Issues

Hi! I’m going through the Advanced node and Express part of the curriculum right now and have hit a snag that confuses me greatly.

The challenge Create New Middleware says that my ‘/profile’ does not redirect to ‘/’ when authentication fails/isn’t present. The thing that confuses me is in my own tests in Chrome this absolutely happens and my code is very similar (almost exactly the same even) as the reference code. I decided oh well and continued on but now it’s getting to the point where I can’t pass anything since it keeps thinking the redirections don’t work and that authentication, in general, is not working properly.

I got “A Get request to /profile correctly redirects to / since we are not authenticated” on Create New Middleware as a fail. I am confused by this because I added a console log to the root to see what happens when the tester interacts with the page. Sure enough, it logs twice because it was visited and then redirected to again, yet the that part of the test fails?

I observe all these fails as false since it works correctly on my end. I have attached the entirety of my server.js below, and I’m on checkpoint Registration of New Users.

One final note I want to add is yes I have tried changing the function declarations to the classic function foo() {} style and that made no difference.

'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 ObjectID = require('mongodb').ObjectID;
const mongo = require('mongodb').MongoClient;
const LocalStrategy = require('passport-local');

const app = express();

fccTesting(app); //For FCC testing purposes

app.set('views', './views/pug')
app.set('view engine', 'pug');


app.use('/public', express.static(process.cwd() + '/public'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
    extended: true
}));
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('Datebase error: ' + err);
    } else {
        console.log('Successful database connection');

        passport.use(new LocalStrategy((username, password, done) => {
            db.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 (password !== user.password) {
                    return done(null, false);
                }

                return done(null, user);
            });
        }));

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

        const 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,
                    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.user.username
                });
            });
        app.route('/logout')
            .get((req, res) => {
                req.logout();
                res.redirect('/');
            });
        app.route('/register')
            .post((req, res, next) => {
                    db.collection('users').findOne({
                        username: req.body.username
                    }, (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 {
                                        next(null, user);
                                    }
                                }
                            )
                        }
                    })
                },
                passport.authenticate('local', {
                    failureRedirect: '/'
                }),
                (req, res, next) => {
                    res.redirect('/profile');
                }
            );
        app.use((req, res, next) => {
            res.status(404)
                .type('text')
                .send('Not Found 404');
        });

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

An issue has been opened here.

1 Like