node.jsmongodbexpresssessionconnect-mongo

Can I force a session to update from the server side?


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?


Solution

  • I ended up having to do it all manually:

    1. search sessions for one with matching user id
    2. load latest user info and replace in session
    3. 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);
                });
    
            });
        });
    };