1
votes

This is my Library function file named verifyToken.js

require('dotenv').config();
const CognitoExpress = require("cognito-express");

//Initializing CognitoExpress constructor
const cognitoExpress = new CognitoExpress({
    cognitoUserPoolId: process.env.USER_POOL_ID, // User Pool id (created via Console->Cognito Manage User Pool)
    region: process.env.REGION, //User Pool Region
    tokenUse: "id", //Possible Values: access | id
    tokenExpiration: 3600000 //Up to default expiration of 1 hour (3600000 ms)
});

//Our middleware that authenticates all APIs under our 'authenticatedRoute' Router
module.exports = function(){
    this.verifyToken=(function(token, req, res) {

        //I'm passing in the id token in header under key Token
        let TokenFromClient = token;

        //Fail if token not present in header. 
        if (!TokenFromClient) return "Token missing from header";

        cognitoExpress.validate(TokenFromClient, function(err, response) {

            //If API is not authenticated, Return 401 with error message. 
            if (err) {
                return res.send({success:false, msg:"Token Authenication Error", Error:err});
            }

            //Else API has been authenticated. Proceed.
            return res.send({success:true, msg:"Token Authenication result", result: response});
        });
    });
}

I am calling this function from controller

var verify_tokenController = {};

//Verify AWS token recieved through client header by calling verifyToken Library function
verify_tokenController.verify = function(req, res) {

    //Import verifyToken Library function
    require('../library/verifyToken')();

    var auth = verifyToken(req.header('Token'), req, res);
    console.log(auth);
};

module.exports = verify_tokenController;

But I am always receiving undefined at console. How to return err or response back to the calling controller. Both of the return variable are JSON object type.

1

1 Answers

0
votes

It is becuase cognitoExpress.validate is an async operation. it will run and the callback of this function will run. But by the time this all happens. Your following line

console.log(auth); gets hit already and you see undefined becuase you are actually not returning anything from verifyToken method at that time.

This how javascript and async operations work.

You can either use the callback approach but that's not what I would recommend. So I'm modifying your code with promises and see if it works for you.

Your verifyToken.js should look as follow:

require('dotenv').config();
const CognitoExpress = require("cognito-express");

//Initializing CognitoExpress constructor
const cognitoExpress = new CognitoExpress({
    cognitoUserPoolId: process.env.USER_POOL_ID, // User Pool id (created via Console->Cognito Manage User Pool)
    region: process.env.REGION, //User Pool Region
    tokenUse: "id", //Possible Values: access | id
    tokenExpiration: 3600000 //Up to default expiration of 1 hour (3600000 ms)
});

//Our middleware that authenticates all APIs under our 'authenticatedRoute' Router
module.exports = function(){
    this.verifyToken=(function(token, req, res) {
        return new Promise(function(resolve, reject) {
          //I'm passing in the id token in header under key Token
          let TokenFromClient = token;

          //Fail if token not present in header. 
          if (!TokenFromClient) return "Token missing from header";

          cognitoExpress.validate(TokenFromClient, function(err, response) {

              //If API is not authenticated, Return 401 with error message. 
              if (err)  {
                reject(err);
              } else {
                //Else API has been authenticated. Proceed.
                resolve(response);
              }                            

          });
        });            
    });
}

Your controller should look like as follow:

var verify_tokenController = {};

//Verify AWS token recieved through client header by calling verifyToken Library function
verify_tokenController.verify = function(req, res) {

    //Import verifyToken Library function
    require('../library/verifyToken')();

    verifyToken(req.header('Token'), req, res)
      .then(function(response){
        console.log(resposne, 'response')
        res.send({success:true, msg:"Token Authenication result", result: response});    
      })
      .catch(function(err) {
        res.send({success:false, msg:"Token Authenication Error", Error:err});
      });    
};

module.exports = verify_tokenController;

Try the above solution.