1

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 :)

Alex
  • 1,157
  • 3
  • 11
  • 25
  • possible duplicate of [socket.io and express 4 sessions](http://stackoverflow.com/questions/23494016/socket-io-and-express-4-sessions) – laggingreflex Feb 07 '15 at 19:11
  • As I mentioned, some of the code bits in my post are from that question. I furthermore explain in my post why this does not solve my problem... – Alex Feb 07 '15 at 19:43

1 Answers1

-1

In your Session Initialisation change default httpOnly: false settings to true.

Since, it is strict httpOnly it is denying AJAX request.

In your app.js or server.js where you're initialising Session do something like this.

var session = expressSession({ secret: 'secret key', key: 'express.sid', resave: false, saveUninitialized: true, cookie: {httpOnly: false} });

Note: cookie: { httpOnly: false } is important, rest code is for example.

Thanks.