So, for learning purposes, I am writing a chat application with Node and Express. I use MongoDB/Mongoose, Passport for authentification, and socket.io for the actual chat part of the app.
I have a working registration/login/logout system. My problem is in the socket.io code. When I emit a message from a client, I want to know in the sever-side code, from what user the message originated. So, in PHP for example, I would save the user name in a session variable upon login, and later use it from somehwere else. So I attempted to do something similar here:
router.post('/',
passport.authenticate('local',{ failureRedirect: '/login', failureFlash: true }),
function(req, res) {
User.findOneAndUpdate({_id: req.user._id}, { lastConnection: new Date() }, {} ,function (err, user) {
req.flash('welcomeMessage', 'Welcome ' + user.name + '!');
req.session.user=user.name; //Here I try saving the user name
req.session.cookie.user=user.name; //Same here, for testing purposes
res.redirect('/');
});
});
But how do I access this data from within socket.io? In another Stackoverflow question, someone provided the following code for exposing the express session to socket.io:
io.use(function(socket, next) {
var req = socket.handshake;
var res = {};
cookieParser(req, res, function(err) {
if (err) return next(err);
session(req, res, next);
});
});
This permits me to access the session:
io.sockets.on('connection', function (socket) {
//Express session:
console.log("Session: ", socket.handshake.session);
Which gives me this output:
Session: {cookie:
{ path: '/',
_expires: null,
originalMaxAge: null,
httpOnly: true
}
}
This does not contain the added data. My guess is, this is the session at the point where my application starts, before I did performed a login, and therefore before any data was added to the session.
Unfortunately, I'm at a loss on how to proceed. I'm grateful for any suggestion :)