Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NodeJS with express-sessions and express-mysql-session isn't setting the sessions. Where did I screw up?

Trying to get sessions working using Node.js and Express for my personal project. I'm using a MySQL database as my session store, and have installed the following modules:

  • express
  • body-parser, to get POST data
  • mysql, to connect to my DB
  • cors
  • express-session
  • express-mysql-session
  • bcrypt, to compare POSTed data with DB hashes

I'm sending a POST request containting login info through javascript from a page, which I compare with an hash from the database. If it matches, I create the session for the user. I want to prevent the user from logging in again if it has a session, but it looks like the session cookie isn't being stored. I verified this by looking at req.session, but the user object I created never appears there.

Records in the database are being created: if I login with correct data, a new record is created. I'm not sure if this is supposed to happen but if I login again with the same user it creates a new record.

Here's what I've got:

var express    = require('express');
var app        = express();
var bodyParser = require('body-parser');
var mysql      = require('mysql');
var cors       = require('cors');
var session    = require('express-session');
var MySQLStore = require('express-mysql-session')(session);
var bcrypt     = require('bcrypt');

var options = { ... };
var pool = mysql.createPool(options);
var sessionConnection = mysql.createConnection(options);

var sessionStore = new MySQLStore({
    expiration: 10800000,
    createDatabaseTable: true,
    schema: {
        tableName: 'USERS_SESSIONS',
        columnNames: {
            session_id: 'session_id',
            expires: 'expires',
            data: 'data'
        }
    }
}, sessionConnection);

// i'll change key & secret later
app.use(session({
    key: '69Atu22GZTSyDGW4sf4mMJdJ42436gAs',
    secret: '3dCE84rey8R8pHKrVRedgyEjhrqGT5Hz',
    store: sessionStore,
    resave: false,
    saveUninitialized: true
}));

app.use(cors());

...

var router = express.Router();

router.post('/login', function(req, res){
    if (req.session.user){
         console.log('already logged in');
    }else{
        // get connection from pool, retrieve user record
        // PLAIN is password from request, row.HASH is the record's hash
        bcrypt.compare(PLAIN, row.HASH, function(err, match){
            // do error handling
            // when match = true do this

            req.session.user = {
                id: row.ID,
                nickname: row.NICK,
                isAuthed: true
            };
            res.sendStatus(200); // else send 401
            return;
        });
    }
});

After successfully logging in, I check my session like this:

router.get('/session', function(req, res){
    res.json(req.session);
});

And I get the following:

{"cookie":{"originalMaxAge":null,"expires":null,"httpOnly":true,"path":"/"}}

As you can see there's no user object. I'm not getting any errors and I can't figure out where's the problem.

like image 276
Khryus Avatar asked Oct 29 '22 13:10

Khryus


1 Answers

var cookieParser = require('cookie-parser');

Please add app.use(cookieParser()); before

app.use(session({
    key: '69Atu22GZTSyDGW4sf4mMJdJ42436gAs',
    secret: '3dCE84rey8R8pHKrVRedgyEjhrqGT5Hz',
    store: sessionStore,
    resave: false,
    saveUninitialized: true
}));

For detailed documentation https://www.npmjs.com/package/cookie-parser

like image 51
Asif Saeed Avatar answered Nov 15 '22 06:11

Asif Saeed