How to store sync session variables between Express and Socket.io in a single page application?

I have a pretty simple single page application. I am using middleware to attach my express session to my socket. The problem I'm running into is that the middleware runs before the user logs in. I can't seem to find a better way to update the socket with the new session information. If I refresh the site after logging in, it works, but it is by no means perfect. Is there a way to control when the socket actually connects? I'm kind of like a noob, so there might be another way to handle this that I haven't thought of.

Here's my server code:

// socket.io middleware
io.use(function(socket, next) {
    socket.session = {};

    var req = {
        "headers": {
            "cookie": socket.request.headers.cookie
        }
    }

    cookieParser()(req, null, function(){
        if( req.cookies['connect.sid'] ){
            var ifs = req.cookies['connect.sid'].slice(2);
            var c = cookieThing.unsign(ifs, config.secret)

            db.sessions.findOne({_id:c}, function(err,res){
                if( !err && res != null ){
                    var temp = JSON.parse(res.session);
                    for( var key in temp ){
                        if( key != 'cookie'){
                            console.log( 'setting ' + key + ': ' + temp[key] );
                            socket.session[key] = temp[key];
                        }
                    }
                }
                next();
            })

        } else {
            // no cookie
        }
    });
});

// user connects to socket
io.on('connection', function(client){
    console.log( client.session );
});

      

Customer:

<script type="text/javascript" src="/socket.io/socket.io.js"></script>
<script type="text/javascript">
    var server = io.connect();
    // a bunch of server.on() and server.emit() statements below here
</script>

      

+3


source to share


1 answer


Once you get a successful login, you need to pass socket.io to restart the session.

customer:

socket.emit('ReloadSession');

      



Server:

var express_session = require('express-session');
var sessionMiddleware = express_session({/*session config*/});

// socket.io middleware
io.use(function(socket, next) {
    var res = {};
    socket.handshake.url = '/';
    sessionMiddleware(socket.handshake,res,function(){
        socket.session = socket.handshake.session;
        socket.session.id = socket.handshake.sessionID;
        next();
    });
});

// user connects to socket
io.on('connection', function(client){
    console.log( client.session );
    socket.on('ReloadSession',function(data){
       socket.session.reload(function(){});
    });
});

      

0


source







All Articles