exports.handler = function()

in lambda/apigw-sap-idoc-authorizer/index.js [20:81]


exports.handler = function(event, context, callback) {        
    try{
        var authData = {} 
        var auth = event.headers.authorization
        //Get Authorization information from the request headers
        if (!auth){
            auth = event.headers.Authorization
            if (!auth){
                console.log("The request didn't have an authorization header. Hence, cannot approve the request") 
                callback("Unauthorized") 
            }
        }
        //Auth is base64 encoded. So decode it here
        var creds = auth.split(' ')[1]
        var credastxt = (new Buffer(creds, 'base64')).toString().split(':')
        authData.username = credastxt[0] 
        authData.password = credastxt[1] 

        if(!authData.username || authData.username==""){
            console.log("The request didn't have an user name. Hence, cannot approve the request") 
            callback("Unauthorized") 
        }
        if(!authData.password || authData.password==""){
            console.log("The request didn't have a password. Hence, cannot approve the request") 
            callback("Unauthorized") 
        }
        // Get Query String parameters
        var qp = event.queryStringParameters 
        if(!qp.upid || qp.upId==""){
            console.log("No Cognito User Pool ID provided in the request. Hence, cannot approve the request") 
        }
        if(!qp.cid || qp.cid==""){
            console.log("No Cognito Client ID provided in the request. Hence, cannot approve the request") 
        }
        authData.userpoolid = qp.upid // Cognito User Pool ID
        authData.clientid = qp.cid // Uesr Pool Client ID
        authData.bucket = qp.bn // IDOC bucket

        // Make async call to get token
        token(authData).then(tokenData =>{
            if(tokenData.success){
                // Valid token received, so all good
                callback(null, allow('me', event.methodArn)) 
            }else{
                // Cognito auth failed, so may be Access key and secret key were provided
                credentials(authData).then(credData=>{
                  if(credData.success){
                    //Credentials were successful
                    callback(null, allow('me', event.methodArn)) 
                  }else{
                    callback("Unauthorized") 
                  }
                })
            }
        })
        
    }catch(ex){
        console.log("Exception in authorizing the call: ", ex) 
        callback("Unauthorized") 
    }
    
}