23

I know that I can use

function(req, res) {
    req.session
}

using express. However I need to access the session outside of the response function. How would I go about doing that?

I'm using socket.io to pass information for adding posts and comments. So when I receive the socket.io message on the server-side, I need to verify the person posting the information by using the session. However since this is being done via socket.io there is no req/res.

MrBojangles
  • 1,423
  • 3
  • 14
  • 16
  • What I ended up doing was just giving each user a uuid at login and changing it fairly often, then using that in the socket messages to verify that they really were who they said they were. – MrBojangles Oct 29 '11 at 00:05

4 Answers4

12

I think I have a different answer.

code:

var MongoStore = require('connect-mongo')(session);
var mongoStore = new MongoStore({
    db:settings.db,            //these options values may different
    port:settings.port,
    host:settings.host
})
app.use(session({
    store : mongoStore
    //here may be more options,but store must be mongoStore above defined
}));

then you should define a session key at req,just like :

code:

req.session.userEmail;

finally,you can get it this way:

code:

var cookie = require("cookie"); //it may be defined at the top of the file
io.on("connection",function(connection){

 var tS = cookie.parse(connection.handshake.headers.cookie)['connect.sid'];
 var sessionID = tS.split(".")[0].split(":")[1];
 mongoStore.get(sessionID,function(err,session){
      console.log(session.userEmail);
 });
}

I had test it yesterday, it worked well.

Saif
  • 6,804
  • 8
  • 40
  • 61
qin jie
  • 121
  • 1
  • 2
7

Using socket.io, I've done this in a simple way. I assume you have an object for your application let's say MrBojangle, for mine it's called Shished:

/**
 * Shished singleton. 
 *
 * @api public
 */
function Shished() {
};


Shished.prototype.getHandshakeValue = function( socket, key, handshake ) {                          
    if( !handshake ) {
        handshake = socket.manager.handshaken[ socket.id ];                                         
    }
    return handshake.shished[ key ];                                                                
};                                                                                                  

Shished.prototype.setHandshakeValue = function( socket, key, value, handshake ) {                   
    if( !handshake ) {
        handshake = socket.manager.handshaken[ socket.id ];                                         
    }
    if( !handshake.shished ) {
        handshake.shished = {};                                                                     
    }
    handshake.shished[ key ] = value;                                                               
};

Then on your authorization method, I'm using MongoDB for session storage:

io.set('authorization', function(handshake, callback) {
    self.setHandshakeValue( null, 'userId', null, handshake );
    if (handshake.headers.cookie) {
        var cookie = connect.utils.parseCookie(handshake.headers.cookie);
        self.mongoStore()
        .getStore()
        .get(cookie['connect.sid'], function(err, session) {
            if(!err && session && session.auth && session.auth.loggedIn ) {
                self.setHandshakeValue( null,
                            'userId',
                            session.auth.userId,
                            handshake );
            }
        });
    }

Then before saving a record in the model, you can do:

model._author = shished.getHandshakeValue( socket, 'userId' );

vimdude
  • 4,447
  • 1
  • 25
  • 23
1

I believe checking socket.handshake should get you the session:

io.sockets.on('connection', function(socket) { 
  console.log(socket.handshake.sessionID);
});

When the client establishes a socket connection with your socket.io server, the client sends a WebSocket handshake request. What I'm doing above is grabbing the session ID from the handshake.

tez
  • 574
  • 6
  • 13
0

Assuming your socket.io code looks kinda like this:

io.on('connection',
function(client) {
  console.log(client.request)
});

The request is client.request as shown in the example above.

Edit: As a separate thing, maybe this would help: https://github.com/aviddiviner/Socket.IO-sessions

Harry
  • 52,711
  • 71
  • 177
  • 261
  • I was really excited when I read your response, but after printing the contents of the "client.request" variable I found that for some reason they are passing just about everything other then the session. Not sure why the session information isn't included, it seems like where it should be. Any other ideas? – MrBojangles Jun 19 '11 at 13:20
  • 1
    @user776796 you should be able to access the cookie `client.request.headers.cookie`, and use it to check your session store. – Harry Jun 20 '11 at 15:47
  • Unfortunately not. "headers.cookie" is there with my cookies listed, however my session information is not included in it. – MrBojangles Jun 21 '11 at 13:14