Advanced Node and Express - Implement the Serialization of a Passport User

Hello Everyone,
I am stuck on this challenge can anyone explain me whats wrong in this code?

mongodb.connect(process.env.MONGO_URI, (err, db) => {
    if(err) {
        console.log('Database error: ' + err);
    } else {
        console.log('Successful database connection');
       //serialization and app.listen

}});

app.use(session({
  secret: process.env.SESSION_SECRET,
  resave: true,
  saveUnintialized: true
}));

passport.serializeUser((user, done) => {
  done(null, user._id)                       
})

passport.deserializeUser((id, done) => {
    mongodb.collection('users').findOne(
      {_id: new ObjectId(id)},
        (err, doc) => {
            done(null, doc);
        }
    );
});

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

Uhm ^^
I’m not sure about the whole code, so that’s what i noticed^^

  • First of all i would try to call the passport methods:

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

  • Next, i’d stuck with id ( in mongo _id is accessible through id too if i am not mistaken ).

  • This makes me think too:

findOne({_id: new ObjectId(id)},

Isn’t the id already a mongo ObjectId? I guess that’s why you call _id on serialize right?

  • Last chance:

(err, doc) => {
done(null, doc);
}

You’re not handling the err case ( if(err){stuff} .. or something similar^^)

I’m assuming that mongodb is a valid mongoclient connected to a db ^^

Hi, here is the full code of my server.js file:

'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 mongodb = require('mongodb').MongoClient;
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.get('/', function (req, res) {
  res.render('/app/views/pug/index.pug', {title: 'Hello', message: 'Please login'})
})

mongodb.connect(process.env.MONGO_URI, (err, db) => {
    if(err) {
        console.log('Database error: ' + err);
    } else {
        console.log('Successful database connection');
       //serialization and app.listen

}});

app.use(session({
  secret: process.env.SESSION_SECRET,
  resave: true,
  saveUnintialized: true
}));

passport.serializeUser((user, done) => {
  done(null, user._id)                       
})

passport.deserializeUser((id, done) => {
    mongodb.collection('users').findOne(
      {_id: new ObjectId(id)},
        (err, doc) => {
          if(err){
            return done(err);
          }
            return done(null, doc);
        }
    );
});

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

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

and i cant understand why this test is not passing

I get it thanks for help

1 Like

Hi again, I have a big issue,
i noticed when i am helping one of my friend on his first Advanced Node and Express challenge he shared the link of his glitch project and its different from mine
its like the old challenges glitch project it has two more files, descriptions, and example but my project don’t have any files like routes and auth, description, example it has nothing

here is the link of my project

Uh, honestly i did never used Glitch ( fcc suggested it but was not mandatory to use it ) so i can’t help much on that side.
That said i think that there’s nothing wrong in that: probably your friend is working on a more structured project ( speaking of routes and auth, can’t say much about description and ‘example’ )

One thing unrelated to the post: since you posted the link i tried the live version but this is what happen when i try to register a user:

It seems like there he can’t find SESSION_SECRET as env variable^^

EDIT;
Oh, yeah, it’s present on the .env but it’s empty :stuck_out_tongue:

1 Like

Ohh, so what do i have to add in that env variable

i created a new project and start working on it from the start but again stuck on it

Create New Middleware

shows this error

An attempt to go to the profile at this point should redirect to the homepage since we are not logged in

source code
live

The .env file is used to safely store the sensitive data^^
It seems that there are few preset variables name that you might have fullfilled.
Take this with a grain of salt since i am not sure if glitch do some stuff under the hood, but here’s my thoughts^^

Look at this:
mongo.connect(process.env.DATABASE,

Here you’re asking mongo to connect to ‘something’, but that ‘something’ is not specified. It should be stored into the DATABASE environment variable, which is:

SECRET=
MADE_WITH=
SESSION_SECRET=
DATABASE= // ← empty!

The same with:

app.use(session({
secret: process.env.SESSION_SECRET,

This is what i was speaking before:

process.env.PORT

The PORT env variable is not specified in the .env file but the app works so it seems glitch pass it under the hood ^^

HINTS:

  • To make the app works (the last you posted) extract the routes from the else statement^^ That was enough for me to visualize the login page^^

  • Look at this lesson: FCC - introduction to mongoDB and mongoose
    Once you obtained the URI use it as value of the .env variable^^

  • Add some random value to the other ,env variables

  • Cross your fingers! :stuck_out_tongue:

1 Like

I tried but still its gettin’ so much errors

Do you have another link? The one above does not work anymore :confused:

Yeah,
here is the glitch link

but now i am doing it again
from the start

Hello. I don’t if you have figured it out, but it troubled me as well. I tried a few different ways and the solution was to put your passport.serializeUser(//yourFunction) , as well passport.deserializeUser(//yourFunction) and the app.listen() within the mongo.connect block after the else statement. Hope this helps.

1 Like

Make sure your .env DATABSE variable is stored as a string, e.g.

DATABASE='mongodb+srv://admin:<yourPasswordHere>@sandbox-abcdefghijklmnop.mongodb.net/sandboxName'
3 Likes

@HooriaHic @xxkazunarixx @AndrewAS I’m getting the same error can u please help me how do you solve it.

Server.js 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 ObjectId = require(‘mongodb’).ObjectId;
const mongodb = require(‘mongodb’).MongoClient;
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.get(’/’, function (req, res) {
res.render(’/app/views/pug/index.pug’, {title: ‘Hello’, message: ‘Please login’})
})

mongodb.connect(process.env.DATABASE, (err, db) => {
if(err) {
console.log('Database error: ’ + err);
} else {
console.log(‘Successful database connection’);
//serialization and app.listen

}});

app.use(session({
secret: process.env.PORT,
resave: true,
saveUnintialized: true
}));

passport.serializeUser((user, done) => {
done(null, user._id)
})

passport.deserializeUser((id, done) => {
mongodb.collection(‘users’).findOne(
{_id: new ObjectId(id)},
(err, doc) => {
if(err){
return done(err);
}
return done(null, doc);
}
);
});

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

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

commenting out this block of code did it for me:

app.route('/').get((req, res) => {
  res.render(__dirname + '/views/pug', {title: "Hello", message: "Please login"});
});
1 Like