Search code examples
node.jsfirebasepassport.jsgoogle-cloud-firestorepassport-local

Firestore + Passport.js session functionality


I am using Passport.js (local) with Firestore to create the backend of a website. Everything is working fine until it't the time to do some session managements. The Passport.js doc. seems to suggest that the session serialization and deserialization are to be used in conjunction with MongoDB. There are no instructions whatsoever on how to implement it on other NoSQL DBs. I did try to implement myself which lead me to here.

The problem is that every query returned by Firestore is in the form of a promise, and there is no way that I can access the result outside the .then() class and therefore unable to serialize and deserialize them in order to create sessions id for individual users. Furthermore, it's simply impossible for me to just call user.id to get the id of the document from Firestore (but it's totally fine with MongoDB).

Is there anyway that I can get the session functionality of Passport.js to work with Firestore?

Any help will be greatly appreciated.

For the full-length code please refer to hastebin.

What the official doc. suggests:

passport.serializeUser(function(user, done) {
  done(null, user.id);
});

passport.deserializeUser(function(id, done) {
  User.findById(id, function(err, user) {
    done(err, user);
  });
}); 

The situation I am facing:

 passport.serializeUser(function(doc, done) {
    done(null, doc.id);
  });
  passport.deserializeUser(function(doc_id, done) {
    DBReg.doc(doc_id)
      .get()
      .then(doc => {
        if (!doc.exists) {
          console.log('Nope');
        } else {
          done(err, doc.data().name);
        }
      });
  });

Functional(working) Output Using MongoDB by console logging req.session:

Session {
  cookie:
   { path: '/',
     _expires: null,
     originalMaxAge: null,
     httpOnly: true },
  flash: {},
  passport: { user: '5afa5ded957b8187e111f966' } }

Note the last line where it starts with passport:

Output that I am Getting Using Firestore:

 Session {
      cookie:
       { path: '/',
         _expires: null,
         originalMaxAge: null,
         httpOnly: true },
      flash: {},

Now the passport: has disappeared

Don't ask me why I didn't use the built-in auth function provided by Firestore. This is my first time working with Firestore, and I was going for its database features; therefore, due to ignorance, the codebase was already 75% done when I realize had Google also provided an auth feature specifically for Firestore.


Solution

  • It's figured out that express.js stores session in the memory. For the session to persists, it better to check out mongo-connect or redis-connect.