Advanced Node and Express - Serialization of a User Object

As a reminder, this project is being built upon the following starter project on Glitch, or cloned from GitHub.

Serialization and deserialization are important concepts in regards to authentication. To serialize an object means to convert its contents into a small key essentially that can then be deserialized into the original object. This is what allows us to know whos communicated with the server without having to send the authentication data like username and password at each request for a new page.

To set this up properly, we need to have a serialize function and a deserialize function. In passport we create these with passport.serializeUser( OURFUNCTION ) and passport.deserializeUser( OURFUNCTION )

The serializeUser is called with 2 arguments, the full user object and a callback used by passport. Returned in the callback should be a unique key to identify that user- the easiest one to use being the users _id in the object as it should be unique as it generated by MongoDb. Similarly deserializeUser is called with that key and a callback function for passport as well, but this time we have to take that key and return the users full object to the callback. To make a query search for a Mongo _id you will have to create const ObjectID = require('mongodb').ObjectID;, and then to use it you call new ObjectID(THE_ID). Be sure to add MongoDB as a dependency. You can see this in the examples below:

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

NOTE: This deserializeUser will throw an error until we set up the DB in the next step so comment out the whole block and just call done(null, null) in the function deserializeUser.

Submit your page when you think you've got it right.