Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find a session from MongoDB collection using Express and MongoStore

I am implementing a session store using Node/Express/Mongo. My problem is that I cannot retrieve any sessions from my sessions collection, so I am unable to determine whether a user has already logged in.

I am using MongoSkin, MongoStore, and mongo-connect, although I don't mind using Mongoose and other tools.

Here is my debug output:

// Check whether the current user has a session.
// If so, adds "currentUser" to the request.
// Else, redirect to the login page.
function loadUser(req, res, next) {
    console.log("loadUser: checking loadUser...");
    var db = req.db;
    console.log("current req.session.token:");
    console.log(req.session.token);
    console.log("current req.session:");
    console.log(req.session);
    if (req.session.token) {
        // Look up the session id in the database 'sessions' collection.
        db.collection('sessions').findOne({token : req.session.token}, function(err, user) {
            console.log("found user by looking up token:");
            console.log(user);
            if (user) {
                req.currentUser = user;
                next();
            } else {
                console.log("token not in 'sessions', redirecting...");
                res.redirect('/login/webapp_login.html');
            }
        });
    } else {
        console.log("no token, redirecting...");
        res.redirect('/login/webapp_login.html');
    }
}

And here is the console output:

loadUser: checking loadUser...
current req.session._id:
53acb8e1b7b297dc29681def
current req.session:
{ cookie: 
   { path: '/',
     _expires: null,
     originalMaxAge: null,
     httpOnly: true },
  isLogged: 21,
  username: 'sessiontest1',
  token: '57a6dfe0bea9150bd4e2d1f76974e88b',
}
found user by looking up token:
null
token not in 'sessions', redirecting...

Along with:

        db.collection('sessions').find(req.session._id, function(user) {

I also tried:

db.collection('sessions').findOne({session:{token:req.session.token}}, function(err, user) {

but I still get null and the function redirects. Am I missing something? Any suggestions would be helpful. I am using MongoSkin, although I am open to solutions in Mongoose as well.

Additionally, I know that my database is configured correctly because I checked the command line:

> db.sessions.find().pretty()
{
        "_id" : "vnftBGNFVQ3S4lHiIB_omOxWDu01kFuH",
        "session" : "{\"cookie\":{\"originalMaxAge\":null,\"expires\":null,\"httpOnly\":t
rue,\"path\":\"/\"},\"isLogged\":6}",
        "expires" : ISODate("2014-07-09T03:44:54.863Z")
}
{
        "_id" : "-AMKc_kIzOOAn_eQJ6RJpvTgWoargLaJ",
        "session" : "{\"cookie\":{\"originalMaxAge\":null,\"expires\":null,\"httpOnly\":t
rue,\"path\":\"/\"},\"isLogged\":20,\"username\":\"sessiontest1\",\"token\":\"57a6dfe0bea
9150bd4e2d1f76974e88b\"}",
        "expires" : ISODate("2014-07-11T06:35:14.835Z")
}

What is going wrong, and why can't I retrieve a session from my sessions collection?

Update running

db.collection('sessions').find({"session" : /./}, function(err, user) {

gives me an output, so I believe the problem is matching a record with a field within the session field's string. The session field, shown in the database output above, is problematic because it one long string and not a nested JSON.

Also, my sessions records are inserted automatically after adding this to my app.js:

app.use(expressSession({
    secret: 's3cretc0de',      
    store: new MongoStore({
        url: mongoUrl      
    }, function () {
        console.log("db session connection open");
    })
}));

And I added the token and username fields within my router, shown below:

router.get('/verify', function(req, res) {
    req.session.username = username;
    req.session.token = req.query.token;
}

Am I missing something? Any help would be greatly appreciated.

like image 447
modulitos Avatar asked Jun 27 '14 07:06

modulitos


1 Answers

When you use MongoStore for storing your session data you don't need to query the MongoDB directly. The module does everything for you.

You can just use req.session to get your session data.

So in your routes you can do something like:

app.get('/', function(req, res){
  // check if the username is set in the session
  if (!req.session.username) {
    // redirect it to login page
    res.redirect('/login');
  } else {
    // do something
  }
});

app.post('/login', function(req, res) {
    // you would check check the username & password here
    // if (username == '...' /&& password ...)

    // set the username in the session session 
    req.session.username = username; 
});
like image 141
Christian P Avatar answered Oct 19 '22 01:10

Christian P