Ad

Getting Weird Output When Authenticating User In Node

- 1 answer

I've created a function which grabs the users email & password and then runs a couple of checks in the database to see if the details are valid. If the details are valid then the user will get parsed back an API key.

But for some reason, some functions are getting called before others and I'm getting undefined on a variable which is suppose to be returning the userObj.

In the function I've added console logs 0, 1, 2, 4, and 5 so you can see the weird outputs I'm getting when I call the function. I will include my code and console output below! I'm using sequalize for my models, I know they are returning the right data because I've tested it. I'm also using promises.

Code:

var auth = {

  login: function(req, res) {

    var email = req.body.email || '';
    var password = req.body.password || '';

    // If nothing parsed, return json obj
    if (email == '' || password == '') {
      console.log("1");
      res.status(401);
      res.json({
        "status": 401,
        "message": "Invalid credentials"
      });
      return;
    }

    // Fire a query to your DB and check if the credentials are valid
    var dbUserObj = auth.validateUser(email, password);
    console.log("0 _____");
    console.log(dbUserObj); // I am returning undefined??? Why the!


    if (!dbUserObj) { // If authentication fails, we send a 401 back
      res.status(401);
      res.json({
        "status": 401,
        "message": "Invalid credentials"
      });
      return;
    }

    console.log("1 ____");
    authToken.create({ userId: dbUserObj.userId, token: genToken(dbUserObj)}).then(function(results){
      res.json("token", results.token);
    }); 
    console.log("2 ____");

  },
  validateUser: function(email, password) {
    // console.log(email + " pass: " + password);
    console.log("3 ____");

    user.findAll({
      where: {
        email : email,
        password : password
      },
      raw: true
    }).then(function(results) {
        console.log("4 _____");
        console.log(results);
        return results;
        // results prints out with all the correct values!!!!!!!!!!
    }).catch(function (err) {
      return err;
      console.log(err);
    });

    console.log("5 _____");
  },

Console output:

You can see that I'm getting undefined on the dbUserObj object, but I honestly don't know why because I'm printing out the results BEFORE I'm actually returning them (As you can see below).

3 ____
5 _____
0 _____
undefined
POST /login/ 401 1.341 ms - 46
Executing (default): SELECT `userId`, `name`, `password`, `email`, `authKey`, `profilePic`, `coverPic`, `description`, `createdAt`, `updatedAt` FROM `user` AS `user` WHERE `user`.`email` = '[email protected]' AND `user`.`password` = 'f6588fc86e19db0936d9b7e8fd3d6c6544af6cdcc3ce161da88adcdb4b952adb';
4 _____ RESULTS ARE BELOW  ----
[ { userId: 1,
    name: 'James',
    password: 'f6588fc86e19db0936d9b7e8fd3d6c6544af6cdcc3ce161da88adcdb4b952adb',
    email: '[email protected]',
    authKey: '$$$Ddjjdafjjadsfjadsjfjadfsj2',
    profilePic: 'default.png',
    coverPic: 'default.png',
    description: 'This user doesn\'t have a description!',
    createdAt: Wed Dec 23 2015 12:48:35 GMT+1100 (AEDT),
    updatedAt: Wed Dec 23 2015 12:48:35 GMT+1100 (AEDT) } ]

As you can see in the above console output, some logs are logging out before and after they should be? Does anyone know why this's happening!?

Ad

Answer

You're having issues with Async.

Have validate user return the promise:

validateUser: function(email, password) {
    // console.log(email + " pass: " + password);
    console.log("3 ____");

    return user.findAll({
      where: {
        email : email,
        password : password
      },
      raw: true
    });

In your login function, you can then then the results of that function.

login: function(req, res) {

    var email = req.body.email || '';
    var password = req.body.password || '';

    // If nothing parsed, return json obj
    if (email == '' || password == '') {
      console.log("1");
      res.status(401);
      res.json({
        "status": 401,
        "message": "Invalid credentials"
      });
      return;
    }

    // Fire a query to your DB and check if the credentials are valid
    auth.validateUser(email, password)
    .catch(function() { 
            //.. handle error
        }
    .then(function(results) {
        var dbUserObj = results;

        console.log("0 _____");
        console.log(dbUserObj); // I am returning undefined??? Why the!


        if (!dbUserObj) { // If authentication fails, we send a 401 back
        res.status(401);
        res.json({
            "status": 401,
            "message": "Invalid credentials"
        });
        return;
        }

        console.log("1 ____");
        authToken.create({ userId: dbUserObj.userId, token: genToken(dbUserObj)}).then(function(results){
        res.json("token", results.token);
        }); 
        console.log("2 ____");
      }
  },

BONUS ANSWER:

You were getting undefined because this line here:

then(function(results) {
        console.log("4 _____");
        console.log(results);
        return results;
        // results prints out with all the correct values!!!!!!!!!!

This was returning the results to the "then" function which was creating another promise resolved with your dbobject, but then you didn't return it to the top function. Using promises in a function that doesn't return a promise or call a callback is a good red flag you're doing something wrong.

Ad
source: stackoverflow.com
Ad