I have user profiles created by passport, which get stored in mongodb with connect-mongo. If i update the users profile for a session, I have to run req.login()
to trigger passport to update the users session to match the new database info. If I change another user from my admin account I can't run this function, is there a way I can update it for the user, or trigger it to get updated the next time their session gets loaded?
Asked
Active
Viewed 270 times
0

stackers
- 2,701
- 4
- 34
- 66
2 Answers
0
You could pass the whole user object to the session store which will ensure your user object is always up to date with the latest info.
passport.serializeUser(function(user, cb) { cb(null, user); });
passport.deserializeUser(function(user, cb) { cb(null, user); });

Bash
- 1,512
- 2
- 11
- 12
-
My session already seems to contain a complete copy of the user object, it just doesn't get updated. What repercussions would this have? – stackers May 17 '19 at 18:12
-
Well with this serialization and deserialization technique, it'll run this every time the server receives a request from that user. A consequence of this is that it's making a call to the database every time, however I haven't had any issues with performance due to this and haven't seen anyone else have issues with it either. I think your issue is similar to one I had a few years ago, see if this thread helps explain things better https://stackoverflow.com/questions/39193579/passportjs-is-it-possible-to-change-req-user-for-another-user – Bash May 17 '19 at 19:25
0
I ended up having to do it all manually:
- search sessions for one with matching user id
- load latest user info and replace in session
- save new info back to database
var mongoose = require('mongoose'); var Schema = mongoose.Schema;
const SessionSchema = new Schema({_id: String}, { strict: false });
const Session = mongoose.model('sessions', SessionSchema, 'sessions');
var User = require('../queries/single.js');
module.exports = function (userId, callback) {
console.log('finding session for',userId);
Session.findOne({session: {$regex: userId}},null,{lean: true},(err, session)=>{
if (err) return callback(err);
if (!session) return callback('user session not found');
//parse session
var sessionJson = JSON.parse(session.session);
//add reset flag
sessionJson.passport.user.resetSession = true;
//get updated user info
User({_id: sessionJson.passport.user._id}, (err, updatedUser)=>{
if (err) return callback(err);
//add new user info to session json
sessionJson.passport.user = updatedUser;
//save back to session
Session.findOneAndUpdate({_id: session._id},{$set: {session: JSON.stringify(sessionJson)}}, (err, savedSession) => {
if (err) return callback(err);
//success
return callback(null);
});
});
});
};

stackers
- 2,701
- 4
- 34
- 66