How to initiate serializeUser method when user data has changed?

111 Views Asked by At

I use passportjs with passport-local strategy to authenticate users in my project. Official serializeUser deserializeUser approach is the following:

// serialize and deserialize
passport.serializeUser(function(user, done) {
   done(null, user._id);
});

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

But due to performance reason I need to prevent query User.findById to my MongoDB database so I use the following approach:

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

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

But now I came up with the following problem: what if user change their data like name, age etc. How how could I update these without logout?

Actually I need to execute passport.serializeUser manually some how?

1

There are 1 best solutions below

0
On

If you're using a database session store then you're still just retrieving the entire user.toJSON() from database upon every deserializeUser call, something you thought you were avoiding but actually are not.

If you're not using a database session store, then you may be storing it all in a cookie or something which seems highly unsafe, as user object may contain sensitive information like password-hash.

If you just want to store users in memory, you should do just that. Create a cache that holds user objects.

var Users = {};

passport.serializeUser(function(user, done) {
    Users[user._id] = user; // store in cache
    done(null, user._id);
});

passport.deserializeUser(function(id, done) {
    if(Users[id]) return done(null, Users[id]); // retrieve from cache
    User.findById(id, function(err, user){
        if(err) return done(err);
        Users[id] = user; // store in cache now if wasn't already found
        done(null, user);
    });
});