jeudi 16 avril 2015

Session id being same for different client Nodejs

Currently we are setting up session in the cookie using express-session with passport.js and connect-redis to store the data in redis. I have multiple node server serving requests. For each request without a session, I am creating a new session. Sometimes, an existing session id is being assigned to a new request. Before creating a unique session, I am checking whether the cookie is there...if it is, then I am not creating a new session. But while doing so, we are seeing that same session id being shared with different client. How do I know its being same? First user tries to login, it gives successful login and sets up the session and gives the correct information about the user profile. Second user tries to login, it gives a successful login but sets the session as the previous i.e. first user's session , hence the second user sees the first user info in the profile section.


Code for the Session implementation:



function sessionImplementation() {
return function (req, res, next) {
if(/ucompany=s%3A/.test(req.headers['cookie'])){
var cookie = req.headers['cookie'].split("ucompany=s%3A");
var zCookie = cookie[1].split(".");
var genid = zCookie[0];
return session({
genid:function () {
return genid;
},
store: redis,
cookie: {
maxAge: new Date(Date.now() + (7 * 24 * 60 * 60 * 1000))
},
secret: 'ucomp123',
resave: false,
name: "ucompany",
saveUninitialized: true
})(req, res, next)

}
return session({
store: redis,
cookie: {
maxAge: new Date(Date.now() + (7 * 24 * 60 * 60 * 1000))
},
secret: 'ucomp123',
resave: false,
name: "ucompany",
saveUninitialized: true
})(req, res, next)
}
}


What is the issue and how can I fix it?


Update 1 As per @robertklep I have modified my code.



var express = require('express');
var session = require('express-session');
var RedisStore = require('connect-redis')(session);
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var passport = require('passport');

var app = express();
app.use(bodyParser.json());// to support JSON-encoded bodies
app.use(bodyParser.urlencoded({ extended: false }));
app.use(compress());
app.use(cookieParser());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

//app.use(cookieParser());
var redis = new RedisStore({
host:config.redis.url,
port:config.redis.port,
prefix:'sess-'+new Date().getDate()+'-'+(new Date().getMonth()+1)+'-'+new Date().getFullYear()+':'
});
app.use(express.static(path.join(__dirname, 'public')));
app.use(session({
store: redis,
cookie: {
expires: new Date(Date.now() + (7 * 24 * 60 * 60 * 1000)),
maxAge:7 * 24 * 60 * 60 * 1000
},
secret: 'ucomp123',
resave: false,
name: "ucomapny",
saveUninitialized: true
}));

app.use(passport.initialize());
app.use(passport.session());

Aucun commentaire:

Enregistrer un commentaire