0

I'm having problems understanding the processing order in Node.js. My Problem: I coded a little Application that saves a session in a cookie with the following properties:

session.email = email;
session.randomHash = randomHash;

The randomHash var is a random String that gets generated and saved to a db everytime the user logs in. If a user with a session now wants to view a private page the method checkSession() gets called:

exports.checkSession = function(req, res) {
    if(req.session) {
        var User = mongoose.model("User", userSchema);
        User.count({email: req.session.email, randomHash: req.session.randomHash}, function(err, count) {
            if(count === 0) {
                return false;
            }
            if(count === 1) {
                return true;
            }
        });
    }
    else {
        return false;
    }
};

The method compares the randomHash of the cookie with the randomHash value of the Db. This method is called in a route:

exports.init = function(req, res) {
    if(hashing.checkSession(req, res)) {
        res.render("controlpanel", {title: "Controlpanel", email: req.session.email});
    }
    else {
        res.send("Sorry but you are not logged in. Go to /login");
    }   
};

Now there must be the problem. Because of Nodes non-blocking style the method gets called but doesn't finish before the if-statement is executed. What can i do about it?

2
  • 1
    Welcome to the callback hell ! Commented Jan 28, 2013 at 14:46
  • callbacks are hardly 'hell' Commented Jan 28, 2013 at 15:19

1 Answer 1

1

The return value in your User.count callback is not the return value of checkSession. The User.count callback doesn't run until after checkSession has finished.

Pass a callback to checkSession and call it in User.count:

exports.checkSession = function(req, res, callback) {
    if(req.session) {
        var User = mongoose.model("User", userSchema);
        User.count({email: req.session.email, randomHash: req.session.randomHash}, function(err, count) {
            if(count === 0) {
                callback(false);
            }
            if(count === 1) {
                callback(true);
            }
        });
    }
    else {
        callback(false);
    }
};

And call it like:

exports.init = function(req, res) {
    hashing.checkSession(req, res, function(result) {
        if(result) {
            res.render("controlpanel", {title: "Controlpanel", email: req.session.email});
        }
        else {
            res.send("Sorry but you are not logged in. Go to /login");
        }
    });
};
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.