From 5e142b240c5ff366ddf52e4dbbfe53b99e2d90bd Mon Sep 17 00:00:00 2001 From: Perkles Date: Fri, 3 May 2024 13:28:29 -0300 Subject: [PATCH 1/3] actions: adiciona novas variaveis de ambiente Adiciona novas variaveis de ambiente ao workflow e modifica tagret branch --- .github/workflows/main.yaml | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/.github/workflows/main.yaml b/.github/workflows/main.yaml index f66db39..13543de 100644 --- a/.github/workflows/main.yaml +++ b/.github/workflows/main.yaml @@ -6,7 +6,7 @@ name: Deploy AWS Lambda Function usando SAM on: push: branches: - - action-test + - main permissions: id-token: write @@ -28,4 +28,10 @@ jobs: # Build inside Docker containers - run: sam build # Prevent prompts and failure when the stack is unchanged - - run: sam deploy --no-confirm-changeset --no-fail-on-empty-changeset --resolve-s3 \ No newline at end of file + - run: | + sam deploy \ + --no-confirm-changeset --no-fail-on-empty-changeset --resolve-s3 \ + --parameter-overrides \ + USERPOOL_ID=${{ secrets.USERPOOL_ID }} \ + CLIENT_ID=${{ secrets.CLIENT_ID }} \ + REGION=${{ secrets.REGION }} \ No newline at end of file From f7d49b0fb2e90b4219c7c9f9e80d3f99afaea70f Mon Sep 17 00:00:00 2001 From: Perkles Date: Sat, 4 May 2024 17:40:22 -0300 Subject: [PATCH 2/3] refina logica geral --- authenticate/app.js | 152 ++++++++++++++++++++++++++++---------------- template.yaml | 3 +- 2 files changed, 98 insertions(+), 57 deletions(-) diff --git a/authenticate/app.js b/authenticate/app.js index 3c2be10..2a4869e 100644 --- a/authenticate/app.js +++ b/authenticate/app.js @@ -11,80 +11,120 @@ * */ -const { InitiateAuthCommand, CognitoIdentityProviderClient, AdminInitiateAuthCommand, SignUpCommand } = require("@aws-sdk/client-cognito-identity-provider"); +const { CognitoIdentityProviderClient, AdminInitiateAuthCommand, SignUpCommand, AdminGetUserCommand, AdminConfirmSignUpCommand } = require("@aws-sdk/client-cognito-identity-provider"); const userPoolId = process.env.USERPOOL_ID || 'default_value'; const clientId = process.env.CLIENT_ID || 'default_value'; const region = process.env.REGION || 'default_value'; const cognitoClient = new CognitoIdentityProviderClient({region: region}); +const senhaPadrao = "Mudar#123" module.exports.lambdaHandler = async (event, context) => { - const cpf = event.cpf; // Obtenha o parâmetro CPF da requisição - - // if (!cpf) { - // return { - // statusCode: 400, - // body: JSON.stringify({ error: "CPF is required" }), - // }; - // } + const [cpf, email] = validaDadosDeEntrada(event) try { - // Verifica se o usuário com esse CPF já existe no banco de dados - const existeUsuarioNoBanco = true - if (existeUsuarioNoBanco) { - const authParams = { - AuthFlow: "ADMIN_NO_SRP_AUTH", - UserPoolId: userPoolId, - ClientId: clientId, - AuthParameters: { - USERNAME: cpf, - PASSWORD: cpf, - }, - }; - - const authCommand = new AdminInitiateAuthCommand(authParams); - const authResult = await cognitoClient.send(authCommand); - + if(cpfExisteNoBancoDeDadosDaAplicacao(cpf)) { + if(await usuarioCadastradoCognito(email)) { + return await autenticaUsuarioCognito(email) + }else{ + await cadastraUsuarioNoUserPool(email) + return await autenticaUsuarioCognito(email) + } + }else { return { - statusCode: 200, - body: JSON.stringify({ token: authResult.AuthenticationResult.IdToken }), - }; - } else { - // Se o usuário não existir, cadastra Banco - // Deopois cadastra no Cognito - - const signUpParams = { - ClientId: clientId, - Username: cpf, - Password: cpf, - }; - - const signUpCommand = new SignUpCommand(signUpParams); - await cognitoClient.send(signUpCommand); - - // Autentica o novo usuário - const authParams = { - AuthFlow: "ADMIN_NO_SRP_AUTH", - UserPoolId: userPoolId, - ClientId: clientId, - AuthParameters: { - USERNAME: cpf, - PASSWORD: cpf, - }, + statusCode: 401, + body: JSON.stringify({ error: "AWS Lambda: CPF inexistente no banco da aplicação" }), }; + } + } catch (error) { + return { + statusCode: 500, + body: JSON.stringify({ error: error.message }), + }; + } +}; - const authCommand = new AdminInitiateAuthCommand(authParams); - const authResult = await cognitoClient.send(authCommand); +const validaDadosDeEntrada = (event) => { + if (!event.body) { + return { + statusCode: 400, + body: JSON.stringify({ message: "AWS Lambda: O corpo da requisição esta vazio" }), + }; + } + try { + body = JSON.parse(event.body); + const {cpf, email} = body + if(!((cpf && cpf != "") && (email && email != ""))) { return { - statusCode: 200, - body: JSON.stringify({ token: authResult.AuthenticationResult.IdToken }), + statusCode: 400, + body: JSON.stringify({ error: "AWS Lambda: Dados de entrada invalidos" }), }; } + return [cpf, email] } catch (error) { return { - statusCode: 500, - body: JSON.stringify({ error: error.message }), + statusCode: 400, + body: JSON.stringify({ error: "AWS Lambda: Falha ao extrair corpo da requisição" }), }; } +} + +const cpfExisteNoBancoDeDadosDaAplicacao = (cpf) => { + return true +} + +const usuarioCadastradoCognito = async (email) => { + try { + const response = await cognitoClient.send(new AdminGetUserCommand({ + UserPoolId: userPoolId, + Username: email, + })); + return true + } catch (error) { + return false + } }; + +const cadastraUsuarioNoUserPool = async (email) => { + try{ + const signUpParams = { + ClientId: clientId, + Username: email, + Password: senhaPadrao, + }; + + const signUpCommand = new SignUpCommand(signUpParams); + await cognitoClient.send(signUpCommand); + + await cognitoClient.send(new AdminConfirmSignUpCommand({ + UserPoolId: userPoolId, + Username: email, + })); + } catch (error) { + return { + statusCode: 400, + body: JSON.stringify({ error: "AWS IAM: Falha ao cadastrar usuário" }), + }; + } +} + +const autenticaUsuarioCognito = async (email) => { + const authParams = { + AuthFlow: "ADMIN_NO_SRP_AUTH", + UserPoolId: userPoolId, + ClientId: clientId, + AuthParameters: { + USERNAME: email, + PASSWORD: senhaPadrao, + }, + }; + + const authCommand = new AdminInitiateAuthCommand(authParams); + const authResult = await cognitoClient.send(authCommand); + + return { + statusCode: 200, + body: JSON.stringify({ token: authResult.AuthenticationResult.AccessToken}), + }; +} \ No newline at end of file diff --git a/template.yaml b/template.yaml index aa7751d..6dd68df 100644 --- a/template.yaml +++ b/template.yaml @@ -17,6 +17,7 @@ Resources: CodeUri: authenticate/ Handler: app.lambdaHandler Runtime: nodejs18.x + # Role: !GetAtt AuthenticationFunctionRole.Arn Architectures: - x86_64 Events: @@ -24,7 +25,7 @@ Resources: Type: Api # More info about API Event Source: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#api Properties: Path: /authenticate - Method: get + Method: post Environment: Variables: USERPOOL_ID: ${{ secrets.USERPOOL_ID }} From ba25d1886640e4cb66d4c5fddc6a7f584bca8dc8 Mon Sep 17 00:00:00 2001 From: Perkles Date: Sat, 4 May 2024 20:38:45 -0300 Subject: [PATCH 3/3] adequa nome de variaveis ao fazer o deploy da lambda --- .github/workflows/main.yaml | 9 ++++----- authenticate/app.js | 11 +++++------ template.yaml | 6 +++--- 3 files changed, 12 insertions(+), 14 deletions(-) diff --git a/.github/workflows/main.yaml b/.github/workflows/main.yaml index 13543de..ccb9583 100644 --- a/.github/workflows/main.yaml +++ b/.github/workflows/main.yaml @@ -29,9 +29,8 @@ jobs: - run: sam build # Prevent prompts and failure when the stack is unchanged - run: | - sam deploy \ - --no-confirm-changeset --no-fail-on-empty-changeset --resolve-s3 \ + sam deploy --no-confirm-changeset --no-fail-on-empty-changeset --resolve-s3 \ --parameter-overrides \ - USERPOOL_ID=${{ secrets.USERPOOL_ID }} \ - CLIENT_ID=${{ secrets.CLIENT_ID }} \ - REGION=${{ secrets.REGION }} \ No newline at end of file + UserPoolId=${{ secrets.USERPOOL_ID }} \ + ClientId=${{ secrets.CLIENT_ID }} \ + Region=${{ secrets.REGION }} \ No newline at end of file diff --git a/authenticate/app.js b/authenticate/app.js index 2a4869e..ef24abc 100644 --- a/authenticate/app.js +++ b/authenticate/app.js @@ -13,9 +13,9 @@ const { CognitoIdentityProviderClient, AdminInitiateAuthCommand, SignUpCommand, AdminGetUserCommand, AdminConfirmSignUpCommand } = require("@aws-sdk/client-cognito-identity-provider"); -const userPoolId = process.env.USERPOOL_ID || 'default_value'; -const clientId = process.env.CLIENT_ID || 'default_value'; -const region = process.env.REGION || 'default_value'; +const userPoolId = process.env.UserPoolId || 'default_value'; +const clientId = process.env.ClientId || 'default_value'; +const region = process.env.Region || 'default_value'; const cognitoClient = new CognitoIdentityProviderClient({region: region}); const senhaPadrao = "Mudar#123" @@ -53,8 +53,7 @@ const validaDadosDeEntrada = (event) => { }; } try { - body = JSON.parse(event.body); - const {cpf, email} = body + const {cpf, email} = JSON.parse(event.body) if(!((cpf && cpf != "") && (email && email != ""))) { return { statusCode: 400, @@ -76,7 +75,7 @@ const cpfExisteNoBancoDeDadosDaAplicacao = (cpf) => { const usuarioCadastradoCognito = async (email) => { try { - const response = await cognitoClient.send(new AdminGetUserCommand({ + await cognitoClient.send(new AdminGetUserCommand({ UserPoolId: userPoolId, Username: email, })); diff --git a/template.yaml b/template.yaml index 6dd68df..3e71e5a 100644 --- a/template.yaml +++ b/template.yaml @@ -28,9 +28,9 @@ Resources: Method: post Environment: Variables: - USERPOOL_ID: ${{ secrets.USERPOOL_ID }} - CLIENT_ID: ${{ secrets.CLIENT_ID }} - REGION: ${{ secrets.REGION }} + UserPoolId: ${{ secrets.USERPOOL_ID }} + ClientId: ${{ secrets.CLIENT_ID }} + Region: ${{ secrets.REGION }} # Outputs: # # ServerlessRestApi is an implicit API created out of Events key under Serverless::Function