Node.js – Break out of callback function and return true/false in the parent functon

Node.js – Break out of callback function and return true/false in the parent functon

Problem

I’m using the Node Express framework to build an API and I run into a problem regarding the Basic Auth functionality. I need to run an SQL query to retrieve information about a user and validate their credentials. The issue occurs after the query has been completed. The SQL data is sent into a callback function as shown below. I want to do all the validation inside that callback but I want to break out of the SQL callback and return true/false from the express.basicAuth() function. I have tried setting a global variable and then accessing it outside of the SQL callback but sometimes the query might not have finished by the time that it gets the block that accesses that global variable. Thanks in advance for your help.

var auth = express.basicAuth(function(user, pass) {

    // Query to select information regarding the requested user
    /* Query here to find the requested user's data */

    client.query(query, function (err, rows, fields) {
        if (err) throw err;
        GLOBAL.sql = rows; 

        /* I want to break out of this query callback function and return true from this auth variable */

    });

       // Sometimes the query isn't completed when it gets to this stage
       console.log(JSON.stringify(GLOBAL.sql));


});
Problem courtesy of: ShaneCurran

Solution

express.basicAuth also supports asynchronous operation:

var auth = express.basicAuth(function(user, pass, next) { 
  ...
  client.query(query, function (err, rows, fields) { 
    if (err)
      next(err);
    else
    if (/* authentication successful */)
      next(null, user); // <-- sets 'req.remoteUser' to the username
    else
      next(null, false);
  });
});
Solution courtesy of: robertklep

Discussion

Leave a Reply

Your email address will not be published. Required fields are marked *