如何在AWS Lambda中的块中执行我的Node.js代码

时间:2019-01-11 10:01:31

标签: node.js amazon-web-services aws-lambda

我正在开发代码,以使用AWS Lambda中的NodeJ验证openssl密钥。我需要从DynamoDB中获取公钥,并与给定私钥的用户进行验证。到目前为止,我有两个类,一个是从dynamodb获取数据,第二个是验证公钥和私有。但是由于异步NodeJS首先执行了我的第二个类,并且没有等到我的第一个类从dynamoDB获取数据。

请帮助我按顺序执行代码。

我尝试过Promise,bluebird和callback,但我听不懂

const AWS = require('aws-sdk')
const dynamodb = new AWS.DynamoDB();
var promise = require('promise');
exports.handler = async (event) => {
    var privatek = '-----BEGIN RSA PRIVATE KEY-----\n'+
    'MIICWwIBAAKBgQC2rWURD7fK/3B0W7d36BJnv4ITzSd+K6o+itgHkqe+0EOvoOn2\n'+
    'yHK3J11j2c+BkgAcdfwYaBFhH7Gubvyt0TLAKJvxi6cIbD4DVJqoTwJPzgdCczKZ\n'+
    'AdhevoYam3t/Q454pW5N7IoF5IzMgPypRbPhi7JnkqcE1/CIXC3hrysMeQIDAQAB\n'+
    'AoGANFPlEIcVGdQkDWC8ZF+Y7hkglLV+q5iscq/pA/pRjMoxqVyJyIRQwABJszGQ\n'+
    'TEhbOcveQ8uDtvOSPSpTvSKgy4fxmH0/RuypTYcAD/BN76T1DDODSsyn+KuNOdko\n'+
    'x6bo30wexmBL/itya9VJMBM49iMMYtYBtOuoJGamMc+vUQECQQDxaWk9alNa37Yb\n'+
    'SAfQRGoU7xJvuVQ8qHBY0EgCzYwaMkWuWKkk8GA058PezUxEjwZN8ZRVsYO2YHG1\n'+
    '3w3vcF+ZAkEAwbdf1ZVpPEsVyXeftnnu5uPxjN6SGqojV1M1/QXQJaFVd0SFAWMY\n'+
    'LE1tqFI6KEfQ1huehvwXhja6HU5z4p+f4QJAce/xRpYvHx2koj2dynLvqk+nYOmU\n'+
    'U0igNZqf0grXC+ocLwwTUKbOkUmtjTNRwq3KKPFStBsi8emU4WST/CUKSQJAE2Af\n'+
    'AsLl+rTb4gHIBL1fatKjx14/qNEZpdNZ1AvvzMO9Q6ej0gayVUQNUseer4a3WaL7\n'+
    'kS7Hv5HbvbCqIKGsoQJAS3LAPW5Wpc2rHFJQDryIGdVnZLW6YdFXGudzMRjHsIB0\n'+
    'UMKUywmjRf45ugQMBKJ+iesDwNLmXtOjcB9AdGRz5w==\n'+
    '-----END RSA PRIVATE KEY-----';

     var publick = '-----BEGIN PUBLIC KEY-----\n'+
    'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC2rWURD7fK/3B0W7d36BJnv4IT\n'+
    'zSd+K6o+itgHkqe+0EOvoOn2yHK3J11j2c+BkgAcdfwYaBFhH7Gubvyt0TLAKJvx\n'+
    'i6cIbD4DVJqoTwJPzgdCczKZAdhevoYam3t/Q454pW5N7IoF5IzMgPypRbPhi7Jn\n'+
    'kqcE1/CIXC3hrysMeQIDAQAB\n'+
    '-----END PUBLIC KEY-----';
    console.log(event["pk"]);
    const table = "MARKETPLACE_USER_RELATED_APPS_TABLE"; 
    var dynamo = new Dynamo(table);
    var prik = dynamo.read(dynamo.client());
    console.log(prik);

    var clientid = '12345'; //event['client_id']
    var unique_id = parseInt(Math.random()*10000000000000000).toString();
    var time_stamp = new Date();

    var Authkey = clientid + ':' + unique_id + ':' + time_stamp;
    console.log(Authkey+"Authkey");
    console.log(time_stamp + 'time_stamp');
    var cryp = new CryptoVerify(publick,privatek, Authkey);
    console.log(cryp.hash+'hash key');
    console.log(event['pk'])
    const response = {
    statusCode: 200,
    body: cryp.verify(cryp.signature())

    };
    return response
    };



    function CryptoVerify(publickey, privatekey, authkey)
    {
    this.crypto = require ('crypto')
    this.hash =  this.crypto.createHash('sha256')
                   .update(authkey)
                   .digest('base64');
                   console.log(this.hash+'haskkk');
    this.signature = function(){    
    try{
        var signer = this.crypto.createSign('sha1');
        signer.update(this.hash);
        var sign = signer.sign(privatekey,'base64');
        console.log(sign + "Sign")
    }
    catch(e)
    {
        var sign = "Private key Errpr: Not matching with the Public 
    key\nExact " +e;
    }
    return sign;
    }
    this.verify =  function(sign){
    var verifier = this.crypto.createVerify('sha1');
    verifier.update(this.hash);
    try {
        this.ver = verifier.verify(publickey, sign,'base64');
        console.log(this.ver);
    }
    catch (e){
        console.log("Private key Error: Not matching with the Public 
    key/n Exact Error:"+e);
        this.ver = e
    }
    return this.ver;    
    }

    }

    function Dynamo(table)
    {
     this.params = {Key :{"email_id":{S:"testuser@tml.com"},
                    "app_name":{S:"EDH"}},
             TableName: table};
     this.op = {};
     this.client = function(){
     try{
        var dynamodb = new AWS.DynamoDB();
     }
     catch(e){
        console.log("Error: Class DynamoDB is not defined");
     }
     return dynamodb;};
     this.read =  function(dy){
     try{               
        dy.getItem(this.params, function(err, data){
            if(err) console.log(err, err.stack);
            else {
                this.op = data;
                console.log(this.op);
            }
        });
     }
     catch(e){
        console.log('Please check getIten function to clear the error');
     }
     return this.op;    
     };
     }

我希望先获取dynamoDB值的结果,然后再验证类。

2 个答案:

答案 0 :(得分:0)

使用lambda处理程序的回调版本,或者在使用asyc await时,将所有回调包装为promise或使用Bluebird的promisify all方法实现方法。

const AWS = require('aws-sdk')
const dynamodb = new AWS.DynamoDB();
var promise = require('promise');
exports.handler = async (event) => {
    var privatek = '-----BEGIN RSA PRIVATE KEY-----\n'+
    'MIICWwIBAAKBgQC2rWURD7fK/3B0W7d36BJnv4ITzSd+K6o+itgHkqe+0EOvoOn2\n'+
    'yHK3J11j2c+BkgAcdfwYaBFhH7Gubvyt0TLAKJvxi6cIbD4DVJqoTwJPzgdCczKZ\n'+
    'AdhevoYam3t/Q454pW5N7IoF5IzMgPypRbPhi7JnkqcE1/CIXC3hrysMeQIDAQAB\n'+
    'AoGANFPlEIcVGdQkDWC8ZF+Y7hkglLV+q5iscq/pA/pRjMoxqVyJyIRQwABJszGQ\n'+
    'TEhbOcveQ8uDtvOSPSpTvSKgy4fxmH0/RuypTYcAD/BN76T1DDODSsyn+KuNOdko\n'+
    'x6bo30wexmBL/itya9VJMBM49iMMYtYBtOuoJGamMc+vUQECQQDxaWk9alNa37Yb\n'+
    'SAfQRGoU7xJvuVQ8qHBY0EgCzYwaMkWuWKkk8GA058PezUxEjwZN8ZRVsYO2YHG1\n'+
    '3w3vcF+ZAkEAwbdf1ZVpPEsVyXeftnnu5uPxjN6SGqojV1M1/QXQJaFVd0SFAWMY\n'+
    'LE1tqFI6KEfQ1huehvwXhja6HU5z4p+f4QJAce/xRpYvHx2koj2dynLvqk+nYOmU\n'+
    'U0igNZqf0grXC+ocLwwTUKbOkUmtjTNRwq3KKPFStBsi8emU4WST/CUKSQJAE2Af\n'+
    'AsLl+rTb4gHIBL1fatKjx14/qNEZpdNZ1AvvzMO9Q6ej0gayVUQNUseer4a3WaL7\n'+
    'kS7Hv5HbvbCqIKGsoQJAS3LAPW5Wpc2rHFJQDryIGdVnZLW6YdFXGudzMRjHsIB0\n'+
    'UMKUywmjRf45ugQMBKJ+iesDwNLmXtOjcB9AdGRz5w==\n'+
    '-----END RSA PRIVATE KEY-----';

     var publick = '-----BEGIN PUBLIC KEY-----\n'+
    'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC2rWURD7fK/3B0W7d36BJnv4IT\n'+
    'zSd+K6o+itgHkqe+0EOvoOn2yHK3J11j2c+BkgAcdfwYaBFhH7Gubvyt0TLAKJvx\n'+
    'i6cIbD4DVJqoTwJPzgdCczKZAdhevoYam3t/Q454pW5N7IoF5IzMgPypRbPhi7Jn\n'+
    'kqcE1/CIXC3hrysMeQIDAQAB\n'+
    '-----END PUBLIC KEY-----';
    console.log(event["pk"]);
    const table = "MARKETPLACE_USER_RELATED_APPS_TABLE"; 
    var dynamo = new Dynamo(table);
    var prik = await dynamo.read(dynamo.client());
    console.log(prik);

    var clientid = '12345'; //event['client_id']
    var unique_id = parseInt(Math.random()*10000000000000000).toString();
    var time_stamp = new Date();

    var Authkey = clientid + ':' + unique_id + ':' + time_stamp;
    console.log(Authkey+"Authkey");
    console.log(time_stamp + 'time_stamp');
    var cryp = new CryptoVerify(publick,privatek, Authkey);
    console.log(cryp.hash+'hash key');
    console.log(event['pk'])
    const response = {
    statusCode: 200,
    body: cryp.verify(cryp.signature())

    };
    return response
    };



    function CryptoVerify(publickey, privatekey, authkey)
    {
    this.crypto = require ('crypto')
    this.hash =  this.crypto.createHash('sha256')
                   .update(authkey)
                   .digest('base64');
                   console.log(this.hash+'haskkk');
    this.signature = function(){    
    try{
        var signer = this.crypto.createSign('sha1');
        signer.update(this.hash);
        var sign = signer.sign(privatekey,'base64');
        console.log(sign + "Sign")
    }
    catch(e)
    {
        var sign = "Private key Errpr: Not matching with the Public 
    key\nExact " +e;
    }
    return sign;
    }
    this.verify =  function(sign){
    var verifier = this.crypto.createVerify('sha1');
    verifier.update(this.hash);
    try {
        this.ver = verifier.verify(publickey, sign,'base64');
        console.log(this.ver);
    }
    catch (e){
        console.log("Private key Error: Not matching with the Public 
    key/n Exact Error:"+e);
        this.ver = e
    }
    return this.ver;    
    }

    }

    function Dynamo(table)
    {
     this.params = {Key :{"email_id":{S:"testuser@tml.com"},
                    "app_name":{S:"EDH"}},
             TableName: table};
     this.op = {};
     this.client = function(){
     try{
        var dynamodb = new AWS.DynamoDB();
     }
     catch(e){
        console.log("Error: Class DynamoDB is not defined");
     }
     return dynamodb;};
     this.read =  function(dy){
       return new Promise((resolve, reject) => {
         try{               
        dy.getItem(this.params, function(err, data){
            if(err) console.log(err, err.stack);
            else {
                this.op = data;
                console.log(this.op);
                return resolve(data);
            }
        });
     }
     catch(e){
       console.log('Please check getIten function to clear the error');
       reject('Error')
        
     }
       });
     
     //return this.op;    
     };
     }

答案 1 :(得分:0)

谢谢。通过在互联网上进行更多搜索,我已经找到了解决问题的方法。 AWS本身为每种服务都提供了“承诺”方法。

我只包含了promise函数,如下所示:

dynamodb.getItem(params).promise().then(function(data, err){
     if(err)
       //do something
     else 
       //do something
});