Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access session in express, outside of the req?

Tags:

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.

like image 544
MrBojangles Avatar asked Jun 18 '11 17:06

MrBojangles


People also ask

Can I use express session in production?

With a negative final score, it's clear that express-session is not optimal for production apps – especially ones that care about user security and will likely scale with time.

Where is express session stored?

Where is the session data stored? It depends on how you set up the express-session module. All solutions store the session id in a cookie, and keep the data server-side. The client will receive the session id in a cookie, and will send it along with every HTTP request.

How do I use session storage in express?

We can use the express-session package to keep session cookie data on the server-side. There're many options like the content of various cookie attributes and the time to expiry. Other settings like the ID, whether to save cookie only in HTTPS and so on can be set. The cookies will be stored in a session store.

How do you access session variables in node JS?

Show activity on this post. var express = require('express'); var session = require('express-session'); var app = express(); app. use(session({secret:'XASDASDA'})); var ssn ; app. get('/',function(req,res){ ssn=req.


2 Answers

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.

like image 157
qin jie Avatar answered Sep 19 '22 10:09

qin jie


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' );

like image 28
vimdude Avatar answered Sep 17 '22 10:09

vimdude