Saturday, 6 May 2017

Node.js is not saving user session

I've worked a lot with nodejs in building session systems but for some reason this simply is not working and I can't figure out why, I don't know if I'm missing something.

Here is the code (I'm still testing some things so the code is not ideal at all but should be functional for the session):

var express = require('express');
var app = require('express')();
var io_session = require("express-socket.io-session");
var e_session = require("express-session");

var MemoryStore = e_session.MemoryStore;

var enableCORS = function(req, res, next) {

    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
    res.header('Access-Control-Allow-Headers', 'Origin, Accept, Content-Type, Authorization, Content-Length, X-Requested-With, *');

        // intercept OPTIONS method
    if ('OPTIONS' == req.method) {
        res.sendStatus(200);
    } else {
        next();
    };
};

var e_session = e_session({
    secret: "eaifgneaifiea30r3jafeaofoeakfoeak",
    store: new MemoryStore(),
    resave: false,
    saveUninitialized: true,
    cookie: { 
        secure: false,
        maxAge: 24*60*60*1000 //1 minute
   } 
});


app.use(function(req, res, next) {      
  ///console.log('Current User:', req);
  next();
});

app.use(e_session);
app.use(enableCORS);

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

app.use(morgan('dev'));

app.post("/TEST_start_login",function(req,res){

    console.log("starting login");

    req.session.alias = ["lol"];
    req.session.user = "WTF";

    console.log("req.session:",req.session);

    to_send = JSON.stringify(returnValues("success","login_registered",{}));

    res.send(to_send);

});

app.post("/TEST_test_login",function(req,res){

    console.log("SESSION:",req.session);
    res.status(200).send();

});

As you can see in the last two methods I save two variables to the session so I can test if the user is logged in or not.

Here is my javascript in the frontend that tests for this:

function sendToServer (object,type,callback,url) {

    if(url == undefined) {
        url = "";
    }

    if(typeof type == undefined) {
        type = "POST";
    }

     $.ajax({
                url: 'http://localhost:8080'+url,
                type: type,
                contentType: 'application/json; charset=utf-8',
                data: JSON.stringify(object),
                success: callback

            });
}

function login() {

    var data = {}

    sendToServer(data,"POST",function(data) {

        //return
        data = JSON.parse(data);

        console.log("returned from login:",data);

    },"/TEST_start_login");

}

function checkSession() {

    var data = {}

    sendToServer(data,"POST",function(data) {

        console.log("returned from login:",data);

    },"/TEST_test_login");

}

And here is the output int he server of executing login and checkSession:

login:

req.session: Session { cookie: { path: '/', _expires: 2017-05-07T16:32:43.377Z, originalMaxAge: 86400000, httpOnly: true, secure: false }, alias: [ 'lol' ], user: 'WTF' }

Variables 'alias' and 'user' are set on session.

check_session:

SESSION: Session { cookie: { path: '/', _expires: 2017-05-07T16:32:45.547Z, originalMaxAge: 86400000, httpOnly: true, secure: false } }

as you can see, going through 'TEST_test_login' route in nodejs no longer shows the variables...

I really am not understanding why this is happening. Can someone please help me figuring this out?

Thank you very much



via Fane

No comments:

Post a Comment