Here I am using get of socket-io and on every page reload it is giving me new values ( Ideally it should come from session and should be same ). Can you please point-out the reason?
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io').listen(server);
var _ = require('lodash');
var q = require('q');
server.listen(3000);
var userCounter = 0;
app.use(express.cookieParser());
app.use(express.cookieSession({secret: 'secret', key: 'express.sid', cookie:{ path: '/', httpOnly: true, maxAge: (1000*3600*24)} }));
app.use(express.static('public'))
.use(function (req, res) {
res.end('File not available\n');
});
function getUserName(socket) {
var deferred = q.defer();
socket.get('userName', function (err, Name) {
if (err || !Name) { // PROBLEM: It always goes in to this IF
var userName = "Userno: " + (userCounter + 1);
userCounter++;
socket.set('userName', userName, function () {
deferred.resolve(userName);
});
} else {
deferred.resolve(Name);
}
});
return deferred.promise;
}
io.sockets.on('connection', function (socket) {
getUserName(socket).
then(function (userName) {
socket.emit("welcome", userName);
_(io.sockets.sockets).forEach(function (eSocket) {
if (socket !== eSocket)
eSocket.emit("userAdded", userName);
});
socket.on('disconnect', function () {
socket.get('userName', function (err, userName) {
io.sockets.emit('userRem', userName);
});
});
});
});
You haven’t implemented any session authentication for your
socket.io. By default every connection to yoursocket.iois a new connection, although it has the same cookie ( session_id in your cookie ). There is a special option forsocket.ioto pass every request through authentication function something like:Things you should do to make it work ( I will not write this as a code, becuase there are a lot of modifications needed ) :
httpconnection within express ( every user should be given an username for their unique session );nowjsbut it’s the sessionStore code you have to look ). Actually it’s better if you place your sessionStore in some database, not in your MemoryStore.socket.ioauthorization sub to reach this sessionStore and get the username, then place it as a parameter for this socket as usual :socket.set('name', ....Pretty much that’s it. It’s not as hard as it sounds, but that’s the proper way of doing this.
Further reading :
Update :
Look at this answer it will be very helpful for you
Securing Socket.io
Update II :
I’ve created a Gist file here with that code https://gist.github.com/1b17fd2a7b324cb3411a