there were many questions about this topic around , but none could solve my problem , i developed an express app and my authentication method was to write to session object and using redis-store . it worked perfect during development ,
but the first time i deployed my site for some tests ( using modulus ) i get an error that req.session is undefined . the code still works fine when i run this on localhost .
this is actually my first web project and there were so many obvious points and tricks that i didn't know and had to learn through the way . maybe i'm missing something simple and obvious here , don't know !
package.josn dependencies :
"dependencies" : {
"express" : "~3.4.4",
"mongoose" : "~3.6.2",
"socket.io":"1.x" ,
"bcrypt-nodejs" : "0.0.3",
"connect-redis": "1.4.x" ,
"body-parser" : "1.4.3" ,
"cookie-parser": "~1.0.0",
"express-session": "~1.0.0"
} ,
app configuration
var express = require('express') ;
var app = express() ;
var http = require('http') ;
var io = require('socket.io') ;
var bodyParser = require('body-parser');
var mongoose = require('mongoose') ;
var mongoose1 = require('mongoose') ;
var bcrypt = require('bcrypt-nodejs') ;
var PORT = process.env.PORT || 8080 ;
var server = http.createServer(app) ;
var RedisStore = require('connect-redis')(express);
app.configure(function () {
app.use(express.static(__dirname + "/static" )) ;
app.use( express.cookieParser() );
app.use(express.bodyParser()) ;
app.use(express.session({
store: new RedisStore({
host: 'localhost',
port: 6379,
db: 2,
pass: '****'
}),
secret: '12345qwr'
})
);
}) ;
and when i reach req.session.[] in my server , app crashed and restarts because req.session in undefined . for example when I click on a login button and a post request is sent to "/api/login" or ..
app.post('/api/login' , function (req, res) {
UserDBModel.findOne({ username : req.body.user } , function (err, user) {
if (err) { res.json(err) ; }
if ( user ) {
if ( bcrypt.compareSync( req.body.pass , user.password ) ) {
req.session.Auth = { username : user.username , password : user.password } ;
//app crashes here with error : TypeError: Cannot set property 'Auth' of undefined
}) ;
ps. to authenticate , i store an "Auth" object in my session containing username and hashed password of logged in users .
Instead of app.use(express.session( try to use: app.use(express.cookieSession()); then the request.session object will be accessible...