Отправить аутентификацию cognito, поскольку обещание дает "Не удается прочитать свойство 'обещание' неопределенного" - PullRequest
0 голосов
/ 08 июля 2019

Я разрабатываю лямбда-функцию для входа в Cognito, но у меня возникают проблемы с ожиданием моей аутентификации cognito.

Я попытался использовать код так же, как в примерах, передав в качестве параметра функции onSuccess и onFailure , но функция завершается без ожидания. Затем я попытался дать обещание, точно так же, как отправил электронное письмо SES, но оно выдает сообщение «Невозможно прочитать свойство обещание неопределенного» * ​​1007 *

Мой код до сих пор:

'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"
        }` );
    }
};

EDIT

Я обновил свой код в соответствии с примером , и теперь похоже, что он ожидает ответа и возвращает код 200 и {message: "OK"}, но выводит на консоль неопределенное значение. 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, и он возвращает токен доступа и идентификатор токена:

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 как обещание, но я не знаю, как заставить лямбду ждать мой запрос без него

Ответы [ 2 ]

0 голосов
/ 09 июля 2019

После дополнительного поиска я обнаружил, что можно объявить лямбда-функцию по-другому и использовать обратный вызов. У меня отлично работает.

Код:

'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"
                }),
            });
        },
    });
};
0 голосов
/ 08 июля 2019

'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"
        }` );
    }
};
...