发送Cognito身份验证作为承诺,将给出“无法读取未定义的属性'promise'”

时间:2019-07-08 14:40:18

标签: javascript promise aws-lambda amazon-cognito

我正在开发lambda函数以登录到Cognito,但是在等待我的Cognito身份验证时遇到了问题。

我尝试像示例中一样使用代码,传递了一个 onSuccess 和一个 onFailure 函数作为参数,但是该函数是完整的,无需等待。 然后,我试图做出承诺,就像发送SES电子邮件一样,但是它给出了消息“无法读取未定义的属性'promise'”

直到现在我的代码:

'use strict';

global.fetch = require('node-fetch');
let AmazonCognitoIdentity = require('amazon-cognito-identity-js');

function criarResposta( statusCode, retorno ) {
    return {
        statusCode: statusCode,
        body: retorno
    };
}

module.exports.login = async (event) => {
    let enviar_promise = null;
    let nome_usuario = "::USER_NAME::";
    let senha_usuario = "::USER_PASSWORD::";

    let authentication_data = {
        Username : nome_usuario,
        Password : senha_usuario,
    };
    let authentication_details = new AmazonCognitoIdentity.AuthenticationDetails(authentication_data);
    let pool_data = { 
        UserPoolId : '::USER_POOL_ID::',
        ClientId : '::CLIENT_ID::'
    };
    let user_pool = new AmazonCognitoIdentity.CognitoUserPool(pool_data);
    let user_data = {
        Username : nome_usuario,
        Pool : user_pool
    };
    let cognito_user = new AmazonCognitoIdentity.CognitoUser(user_data);

    enviar_promise = cognito_user.authenticateUser( authentication_details ).promise();

    try {
        const dados = await enviar_promise;
        return criarResposta( 200, `{
            "message": "OK"
        }` );
    } catch (err) {
        console.error(err, err.stack);
        return criarResposta( 500, `{
            "message": "Erro interno"
        }` );
    }
};

编辑

我已经根据example更新了我的代码,现在看起来它正在等待响应,并且返回代码200和{message:“ OK”},但是在console.log()上未打印resultado);

代码:

'use strict';

global.fetch = require('node-fetch');
let AmazonCognitoIdentity = require('amazon-cognito-identity-js');
let AWS = require('aws-sdk');

function criarResposta( statusCode, retorno ) {
    return {
        statusCode: statusCode,
        body: retorno
    };
}

module.exports.login = async (event) => {
    let enviar_promise = null;
    let nome_usuario = "::USER_NAME::";
    let senha_usuario = "::USER_PASSWORD::";

    let authentication_data = {
        Username : nome_usuario,
        Password : senha_usuario,
    };
    let authentication_details = new AmazonCognitoIdentity.AuthenticationDetails(authentication_data);
    let pool_data = { 
        UserPoolId : '::USER_POOL_ID::',
        ClientId : '::CLIENT_ID::'
    };
    let user_pool = new AmazonCognitoIdentity.CognitoUserPool(pool_data);
    let user_data = {
        Username : nome_usuario,
        Pool : user_pool
    };
    let cognito_user = new AmazonCognitoIdentity.CognitoUser(user_data);

    try {
        let resultado = await cognito_user.authenticateUser( authentication_details );

        // let access_token = resultado.getAccessToken().getJwtToken();
        // let id_token = resultado.idToken.jwtToken;

        console.log( resultado );

        return criarResposta( 200, `{
            "message": "OK"
        }` );
    } catch (err) {
        console.error(err, err.stack);
        return criarResposta( 500, `{
            "message": "Erro interno"
        }` );
    }
};

编辑2

因此,我编写了一个纯nodejs代码,它返回了访问令牌和令牌ID:

global.fetch = require('node-fetch');
let AmazonCognitoIdentity = require('amazon-cognito-identity-js');
let AWS = require('aws-sdk');

AWS.config.update({
    accessKeyId: '::VALOR::',
    secretAccessKey: '::VALOR::',
    region: 'us-east-2'
});

let enviar_promise = null;
let nome_usuario = "::VALOR::";
let senha_usuario = "::VALOR::";

let authentication_data = {
    Username : nome_usuario,
    Password : senha_usuario,
};
let authentication_details = new AmazonCognitoIdentity.AuthenticationDetails(authentication_data);
let pool_data = { 
    UserPoolId : '::VALOR::',
    ClientId : '::VALOR::'
};
let user_pool = new AmazonCognitoIdentity.CognitoUserPool(pool_data);
let user_data = {
    Username : nome_usuario,
    Pool : user_pool
};
let cognito_user = new AmazonCognitoIdentity.CognitoUser(user_data);

cognito_user.authenticateUser(authentication_details, {
    onSuccess: function (result) {
        let accessToken = result.getAccessToken().getJwtToken();
        let idToken = result.idToken.jwtToken;

        console.log( accessToken );
        console.log( idToken );
    },
    onFailure: function(err) {
        console.log(err);
    },
});

我认为问题在于尝试发送authenticateUser作为承诺,但是我不知道如何让lambda在没有它的情况下等待我的请求

2 个答案:

答案 0 :(得分:0)

'use strict';

global.fetch = require('node-fetch');
let AmazonCognitoIdentity = require('amazon-cognito-identity-js');
let AWS = require('aws-sdk');

function criarResposta( statusCode, retorno ) {
    return {
        statusCode: statusCode,
        body: retorno
    };
}

module.exports.login = async (event) => {
    let enviar_promise = null;
    let nome_usuario = "::USER_NAME::";
    let senha_usuario = "::USER_PASSWORD::";

    let authentication_data = {
        Username : nome_usuario,
        Password : senha_usuario,
    };
    let authentication_details = new AmazonCognitoIdentity.AuthenticationDetails(authentication_data);
    let pool_data = { 
        UserPoolId : '::USER_POOL_ID::',
        ClientId : '::CLIENT_ID::'
    };
    let user_pool = new AmazonCognitoIdentity.CognitoUserPool(pool_data);
    let user_data = {
        Username : nome_usuario,
        Pool : user_pool
    };
    let cognito_user = new AmazonCognitoIdentity.CognitoUser(user_data);

    try {
        let resultado = await cognito_user.authenticateUser( authentication_details ).promise();

        // let access_token = resultado.getAccessToken().getJwtToken();
        // let id_token = resultado.idToken.jwtToken;

        console.log( resultado );

        return criarResposta( 200, `{
            "message": "OK"
        }` );
    } catch (err) {
        console.error(err, err.stack);
        return criarResposta( 500, `{
            "message": "Erro interno"
        }` );
    }
};

答案 1 :(得分:0)

经过更多搜索,我发现可以不同地声明lambda函数并使用回调。对我来说很好。

代码:

'use strict';

global.fetch = require('node-fetch');
let AmazonCognitoIdentity = require('amazon-cognito-identity-js');

module.exports.autenticacao = (event, context, callback) => {
    const dados_requisicao = JSON.parse( event.body );

    let authentication_data = {
        Username : dados_requisicao.usuario,
        Password : dados_requisicao.senha,
    };
    let authentication_details = new AmazonCognitoIdentity.AuthenticationDetails(authentication_data);
    let pool_data = { 
        UserPoolId : '::VALOR::',
        ClientId : '::VALOR::'
    };
    let user_pool = new AmazonCognitoIdentity.CognitoUserPool(pool_data);
    let user_data = {
        Username : dados_requisicao.usuario,
        Pool : user_pool
    };
    let cognito_user = new AmazonCognitoIdentity.CognitoUser(user_data);

    cognito_user.authenticateUser(authentication_details, {
        onSuccess: function (result) {
            let access_token = result.getAccessToken().getJwtToken();
            let id_token = result.idToken.jwtToken;

            callback(undefined, {
                statusCode: 200,
                body: JSON.stringify({
                    message: "OK",
                    accessToken: access_token,
                    idToken: id_token
                }),
            });
        },
        onFailure: function(err) {
            callback({
                statusCode: 500,
                body: JSON.stringify({
                    message: "Erro interno"
                }),
            });
        },
    });
};