I need associate logged users in my django web app with their socket.io sockets in node.js app, because for real-time part of web i want to use node.js. Session data will be stored in database. I think i can access cookies in browser, so i can send to node.js app cookie value, that acts like user identifier, but i think this isn't good idea. Is there any other way how to do this?
The cookie can be accessed inside the authorization event. So if you're already using a cookie to store session authentication data, it's pretty easy to integrate that into socket.io. There are some pre-built modules for doing this sort of thing, like SessionSockets.
This article gives some insights into how to do it yourself. The most important section is exerpted below:
var parseCookie = require('connect').utils.parseCookie;
sio.set('authorization', function (data, accept) {
// check if there's a cookie header
if (data.headers.cookie) {
// if there is, parse the cookie
data.cookie = parseCookie(data.headers.cookie);
// note that you will need to use the same key to grad the
// session id, as you specified in the Express setup.
data.sessionID = data.cookie['express.sid'];
} else {
// if there isn't, turn down the connection with a message
// and leave the function.
return accept('No cookie transmitted.', false);
}
// accept the incoming connection
accept(null, true);
});
sio.sockets.on('connection', function (socket) {
console.log('A socket with sessionID ' + socket.handshake.sessionID
+ ' connected!');
});