简体   繁体   中英

Get Session Variable in middleware function in express js

I am working on a website with the help of express.js and mongodb .

To use this website persistently I am using express-session v1.11.3. And, to check if a user is logged in or not, I have created a middleware function. In this function I am trying to get a session but it always returns Undefined .

When login to the router, I have an initialized session variable with user obj. as below:

//users router
router.all('/login', function(req, res) {
    var db = req.db;
    .....
    ........
     //on successfully login
     req.session.user = user;
     res.redirect('/dashboard');
});

After I created this middleware function in the users.js router file to authenticate. Here is the code of this function:

function requiredAuthentication(req, res, next) {
    if (req.session.user) {
        next();
    } else {
        res.redirect("/users/login");
    }
}

Now, I am trying to get users listing and only authenicated users get this:

router.get('/index',requiredAuthentication, function(req, res, next) {
    var db = req.db;
    db.collection('users').find().toArray(function(err, users) {
        if (err) {
            res.render('error', {error: err});
        }else {
            res.render('users/index', {users: users});
        }
    });
});

But it's not working properly.

The code parts that you've posted seems ok, the problem might be in other code that is not visible here.

First of all make sure that you've assigned the req.session.user correctly, inside the asynchronous callback where user is fetched from the db.

Also check whether the express-session middleware is included properly, don't forget to use(session) middleware, like:

var express = require('express');
var session = require('express-session');

var app = express();

app.use(session({
  secret: 'keyboard cat',
  resave: false,
  saveUninitialized: true
}));

Also, try to include and use(express-cookies) middleware, this was an issue in previous express versions, but now it's used automatically by express-session .

a good practice would be to also check if a session exists before you check if a user is added to a session var.

if (req.session && req.session.user) {
   //do something
} 

that could also indicate more on where the problem lays.

also . try putting the function in the controller and see if it still doesn't work for you. (instead of passing it in the route)

check to see if you correctly applied all the modules needed (express-session - and is up to date and not corrupted. (update to latest version if no)

make sure your middleware is set correctly

app.use(session({
  secret: '',
  saveUninitialized: true/false,
  resave: true/false 
}));

if you did checked all of the above, take a look at the console of your server. does it output any error regarding the session var or decleration.? if so please post

hope this guide you somehow. cheers

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