简体   繁体   中英

Issue with client-session middleware: req.session_state = undefined after being set

I've hit a bit of a problem getting client-session middleware working in Express. In short the session_state doesn't seem to be accessible when redirecting to new route after being set. For reference I have followed this video tutorial (client-session part starts 36:00 approx.) and double checked my steps but still encountering problems. Middleware is set up as follows:

var sessions = require('client-sessions');

Instantiated with code from the Express website.

app.use(sessions({
 cookieName: 'session',
 secret: 'iljkhhjfebxjmvjnnshxhgoidhsja', 
 duration: 24 * 60 * 60 * 1000,
 activeDuration: 1000 * 60 * 5 
}));

I have the sessions middleware placed between bodyParser and routes if that makes any difference.

Here are the sections my routes/index.js pertaining to the issue. The req.session_state seems to get set ok and the correct user details log to the console.

// POST login form
router.post('/login', function(req, res) {
  User.findOne( { email: req.body.email }, function(err,user){
    if(!user) {
      console.log("User not found...");
      res.render('login.jade', 
         { message: 'Are you sure that is the correct email?'} );
    } else {
        if(req.body.password === user.password) {

        // User gets saved and object logs correctly in the console
            req.session_state = user;
            console.log("session user...", req.session_state);

            res.redirect('/dashboard'); 
        }
    }
    //res.render('login.jade', { message: 'Invalid password'} );
  });
});

However, something is going wrong when the res.redirect('/dashboard'); is run because the session_state is not accessible when it hits that route. Here is the code for the /dashboard route.

router.get('/dashboard', function(req, res) {

   // OUTPUT = 'undefined' ???
   console.log("dash...", req.session_state);

   // 'if' fails and falls through to /login redirect
   if(req.session && req.session_state){
       console.log("dash route...", req.session_state);
       User.findOne( { email: req.session_state.email }, function
        (err, user){
         if(!user){
            req.session.reset();
            res.redirect('/login');
         } else {
            res.locals.user = user;
            res.render('dashboard.jade')
         }
      });
   } else {
    res.redirect('/login');
   }
   //res.render('dashboard', { title: 'Your Dashboard' });
});

Basically, the object stored in session_state is not accessible after the /dashboard redirect. I've been trying to debug it for a day or so without any luck. Any help much appreciated. Sorry if I am missing something obvious. Just getting my feet wet with session middleware so maybe I haven't fully grasped Session or I am overlooking something. Thanks in advance!

I've updated my answer with code that should help you set the cookie and an alternative session manager known as a token. In this example I've provided to parts to a middle ware one part which attaches the cookie (this can be expanded on to determine your use case) and the second part which checks the token for expiration or what ever else might be in there (ie audience, issuer, etc.)

 app.use('/js/',function(req, res, next) {
//check if the request has a token or if the request has an associated username
         if(!req.headers.cookie){

            console.log('no cookies were found')

            var token = jwt.sign({user_token_name:req.body.user_name},app.get('superSecret'), {
                expiresIn: 1 *100 *60 // expires in 1 mintue can be what ever you feel is neccessary
            });
             //make a token and attach it to the body
             // req.body.token = token // this is just placing the token as a payload
             res.cookie('austin.nodeschool' , token,{ maxAge: 100000, httpOnly: true }) //this sets the cookie to the string austin.nodeschool
         }
        if(req.body.user_name){
             next()
         }else{
             res.send('request did not have a username').end() // this is here because my middleware also requires a username to be associated with requests to my API, this could easily be an ID or token.
         }
    },function(req, res, next) {
//    console.log(req.headers)  this is here to show you the avilable headers to parse through and to have a visual of whats being passed to this function
            if(req.headers.cookie){
                console.log(req.headers.cookie) //the cookie has the name of the cookie equal to the cookie.
                var equals = '=';
                var inboundCookie = req.headers.cookie
                var cookieInfo = splitCookie(inboundCookie,equals) //splitCookie is a function that takes the inbound cookie and splits it from the name of the cookie and returns an array as seen below.
                console.log(cookieInfo)
               var decoded = jwt.verify(cookieInfo[1], app.get('superSecret'));

                console.log(decoded)
                // You could check to see if there is an access_token in the database if there is one
                // see if the decoded content still matches. If anything is missing issue a new token
                // set the token in the database for later assuming you want to       
                // You could simply check if it's expired and if so send them to the login if not allow them to proceed through the route. 
            }
    next()
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM