Tim Daubenschütz
Tim Daubenschütz

Reputation: 2173

Understanding Node.js processing order

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?

Upvotes: 0

Views: 286

Answers (1)

apsillers
apsillers

Reputation: 115980

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");
        }
    });
};

Upvotes: 1

Related Questions