Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

socket.io and session?

I'm using express framework. I want to reach session data from socket.io. I tried express dynamicHelpers with client.listener.server.dynamicViewHelpers data, but i can't get session data. Is there a simple way to do this? Please see the code

app.listen(3000);  var io = require('socket.io'); var io = io.listen(app);  io.on('connection', function(client){     // I want to use session data here     client.on('message', function(message){         // or here     });     client.on('disconnect', function(){         // or here     });  }); 
like image 933
sfs Avatar asked Jan 09 '11 18:01

sfs


2 Answers

This won't work for sockets going over the flashsocket transport (it doesn't send the server the needed cookies) but it reliably works for everything else. I just disable the flashsocket transport in my code.

To make it work, in the express/connect side, I explicitly define the session store so I can use it inside socket:

MemoryStore = require('connect/middleware/session/memory'), var session_store = new MemoryStore(); app.configure(function () {   app.use(express.session({ store: session_store })); }); 

Then inside my socket code, I include the connect framework so I can use its cookie parsing to retrieve the connect.sid from the cookies. I then look up the session in the session store that has that connect.sid like so:

var connect = require('connect'); io.on('connection', function(socket_client) {   var cookie_string = socket_client.request.headers.cookie;   var parsed_cookies = connect.utils.parseCookie(cookie_string);   var connect_sid = parsed_cookies['connect.sid'];   if (connect_sid) {     session_store.get(connect_sid, function (error, session) {       //HOORAY NOW YOU'VE GOT THE SESSION OBJECT!!!!     });   } }); 

You can then use the session as needed.

like image 168
pr0zac Avatar answered Oct 08 '22 20:10

pr0zac


The Socket.IO-sessions module solution exposes the app to XSS attacks by exposing the session ID at the client (scripting) level.

Check this solution instead (for Socket.IO >= v0.7). See docs here.

like image 43
Jeffer Avatar answered Oct 08 '22 19:10

Jeffer