Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Express change session every request

I have a function to login

app.post('/doLogin', function(req,res){
        db.users.findOne({username: req.body.username}, function(err, user) {
            if( err ) {
                console.log("Login fail");
            } 
            else if (user != null) {
                if (req.body.password == user.password) {
                    req.session.user_role = "user";
                    req.session.save();
            } else {
                req.session.user_role = "null";
                console.log("Wrong login");
            }
        }
        res.send({redirect: "/"});
    });

});

This function is used to save a variable into session req.session.user_role = "user"; But when the new request to check user logged in or not

app.get('/', function(req,res){
    redis.get('sess:' + req.session.id, function(err, result){
        console.log("Get session: " + util.inspect(JSON.parse(result),{ showHidden: true, depth: null }));
    });
    if ((req.session.user_role == "user")) {
          console.log("Logged in");
    } else {
        console.log("Logged out");
    }
});

Then return always is "Logged out", because the session is changed. I use Redis to store session, I think it is Redis fault because when I stop using Redis, it's OK Please help me!

like image 934
BlueS Avatar asked Nov 28 '22 07:11

BlueS


1 Answers

Express-session uses the cookie to set or get the session id from the client

as stated on the documentation

Please note that secure: true is a recommended option. However, it requires an https-enabled website, i.e., HTTPS is necessary for secure cookies. If secure is set, and you access your site over HTTP, the cookie will not be set.

Remember the below points:

  • If you are not hosting on HTTPS connection cookie secure flag should be set to false.

  • If the you are using a proxy thats hosted on the HTTPS you should set trust proxy to 1. Refer the documentation


Below option will resolve the issue of session ID reset for every request

cookie: { secure: false }

for example:

app.use(session({
  // your settings
  cookie: { secure: false }
}))

like image 91
NiRUS Avatar answered Dec 01 '22 00:12

NiRUS