Thursday 8 June 2017

Node.js Callback not returning value to the calling function. Just timing out

So I think I have this correct but for some reason it is not executing the way I would think. I am just wanting to decode the JWT Token and pass the data back. Here is the code:

var jwtToken = function(message, callback) {
    var tokenArray = message.headers['authorization'];
    var array = tokenArray.toString().split(' ');

    if (array[0] == 'Bearer') {
        var token = array[1];
    } else {
        return callback.status(401).json({message: "bad json token"});
    }

    var map = JSON.parse(process.env.AUTH0_SECRET);

    var decoded = jwt2.decode(token, {complete: true});
    console.log('PAYLOAD:');
    console.log(decoded.payload);
    var clientId = decoded.payload.aud;
    var secret = map[clientId];

    //console.log('ENVIRONMENT SECRET: ' + map);
    //console.log('CLIENT ID: ' + clientId);
    //console.log('MAPPED SECRET: ' + secret);

    jwt2.verify(token, secret, function(err, decode){
        if (err) {
            callback.status(401).json({message: "JSON is incorrect or expired"})
        } else {
            callback = decode;
        }
    });
};

//route to make sure that the API works
app.get('/', function(req,res) {
    jwtToken(req, function(data){
       console.log(data);
       res.json({ message: 'You are connected to the API  ' + data})
    });
});

What I would expect is that I pass in the request into the jwtToken function and I would get back the decoded Token in the callback. I would then send the Response with the message and the decoded Token. What I am getting is the data in the logs from the jwtToken call but then it keeps running till it times out. I am just not sure what I messed up in the Callback that would stop it from sending the result back. Thanks for your help.



via Justin Yanta

No comments:

Post a Comment