Search code examples
javascriptnode.jsexpress-session

Cannot set property 'X' of undefined in specific route with req.session


Currently working with:

  • NodeJS
  • Express
  • MySQL
  • Express-session
  • Express-mysql-session

Recently I'm doing a simple login form with redirect and I would like to have a session created when the user is successfully connected.

When on password verification success I tried doing:

req.session.authenticated = true;

But this gives me the error:

Cannot set property 'authenticated' of undefined

For handling session I have the following code:

server.js

var express    = require('express');   
var session = require('express-session');
var MySQLStore = require('express-mysql-session')(session);
var options = {
    host: 'localhost',
    port: 3306,
    user: 'myuser',
    password: 'mypassword',
    database: 'mydb_repo'
};
var router = express.Router();            
var sessionStore = new MySQLStore(options);
router.use(session({
    key: 'session_cookie_name',
    secret: 'session_cookie_secret',
    store: sessionStore,
    resave: false,
    saveUninitialized: false,
    path: "/",
    // How frequently expired sessions will be cleared; milliseconds:
    checkExpirationInterval: 900000,
    // The maximum age of a valid session; milliseconds:
    expiration: 86400000
}));
// middleware to use for all requests
router.use(function(req, res, next) {
    if (req.url === '/bakery' && (!req.session || !req.session.authenticated)) {
        res.send('unauthorised');
        return;
    }else{
      // do logging
      var ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress;
      console.log('-- EVENT -- The wolf is in the pen. '+ip);
      next(); // make sure we go to the next routes and don't stop here
    }
});
require('./routes')(router);

/routes/index.js

var fs = require('fs');
module.exports = function(router){
    fs.readdirSync(__dirname).forEach(function(file) {
        if (file == "index.js") return;
        var name = file.substr(0, file.indexOf('.'));
        require('./' + name)(router);
    });
}

/routes/oven.js

module.exports = function(router){
    router.get('/oven/', function(req, res){
      var text = fs.readFileSync('./app/views/oven.html','utf8')
      var content = text.replace("[TITLE]", "Cookie Touch");
        res.send(content);
    });
    router.route('/oven')
      .post(function(req, res) {
        var email = req.body.inputEmail;
        var pass = req.body.inputPassword;
        console.warn("-- WARN -- A new cookie in the Oven: "+email);
        authentificate(email, pass, req, res);
      });
}
function authentificate(email, pass, req, res){
    //get salt and hash passes (long code)
    checkPass(email, hash_f, res);
  });
}
function checkPass(email, hash, req, res){
  connection.query('SELECT password AS pass FROM user WHERE email="'+email+'"', function (error, results, fields) {
    if (results[0].pass == hash){
      req.session.authenticated = true;
      res.redirect('/api/bakery');
      console.log("Successfully authentificated!");
    }else{
      res.send("Wrong Password");
      console.log("Wrong Password");
    }
  });
}

I have tried adding the definition of the session and the router.use in the oven.js but no success instead of doing router.use(session... I also tried doing app.use(session...


Solution

  • You are using checkPass with just three params checkPass(email, hash_f, res) where as you should be passing four params. ie req is not passed.

    function authentificate(email, pass, req, res){
        //get salt and hash passes (long code)
        checkPass(email, hash_f, req, res)
      });
    }