Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nodejs express req.session not storing my variable

I'm setting a basic admin auth, when the user is logged in, I call this function in the authcallback :

function checkAdmin (req) {
  Admin.findOne( { user : req.user.id },function ( err, admin, count ){
    req.session.isAdmin = true;
    console.log("session : %j",req.session);
  })
}

And then I do

res.redirect('/')

The code inside the index controller :

console.log("session : %j",req.session);
  res.render('index', { title: 'Accueil',message: req.flash('info') });

And this is what I get in the console :

session : {"cookie":{"originalMaxAge":null,"expires":null,"httpOnly":true,"path"
:"/"},"passport":{"user":"5079832df1e9a6485e000001"},"flash":{},"isAdmin":true}

session : {"cookie":{"originalMaxAge":null,"expires":null,"httpOnly":true,"path"
:"/"},"passport":{"user":"5079832df1e9a6485e000001"},"flash":{}}

I don't get why the session doesn't store the isAdmin value.

I've read some other questions saying that the app.use(app.router) place could be a cause but I do :

app.use(cookieParser)
app.use(express.session({store: session_store }));
app.use(passport.initialize())
app.use(passport.session())


// routes should be at the last
app.use(app.router)

It must be kind of idiot I guess ..

like image 739
Sladix Avatar asked Nov 30 '12 21:11

Sladix


1 Answers

Well,

Finally I found why this wasn't working. I did the res.redirect outside my Admin.findOne function. So the client was redirected before the session variable was set.

This authCallbackFunction is working :

exports.authCallback = function (req, res, next) {
  //Check if the logged in user is an admin
  Admin.findOne( { user : req.user.id },function ( err, admin, count ){
    var old = req.session;
      if(!err && admin)
        req.session.isAdmin = true;
      res.redirect('/')
  })
}

And when the user logout, don't forget to regenerate the session

// logout
exports.logout = function (req, res) {
  req.session.regenerate(function(){
    req.logout()
    res.redirect('/login')  
  })

}
like image 198
Sladix Avatar answered Oct 13 '22 11:10

Sladix