Trying to use model within post-confirmation function

Viewed 731

When the user is registered with the method Auth.signup and this one confirmed the code received by email. I want to execute the post-confirmation trigger and update a User table made through the method @model on the schema.graphql file.

I updated the Auth like this:

andres@DESKTOP-CPTOQVN:~/TeVi$ amplify update auth
Please note that certain attributes may not be overwritten if you choose to use defaults settings.

You have configured resources that might depend on this Cognito resource.  Updating this Cognito resource could have unintended side effects.

Using service: Cognito, provided by: awscloudformation
 What do you want to do? Walkthrough all the auth configurations
 Select the authentication/authorization services that you want to use: User Sign-Up, Sign-In, connected with AWS IAM controls (Enables per-user Storage features for images or other content, Analytics, and more)
 Allow unauthenticated logins? (Provides scoped down permissions that you can control via AWS IAM) Yes
 Do you want to enable 3rd party authentication providers in your identity pool? No
 Do you want to add User Pool Groups? No
 Do you want to add an admin queries API? No
 Multifactor authentication (MFA) user login options: OFF
 Email based user registration/forgot password: Enabled (Requires per-user email entry at registration)
 Please specify an email verification subject: Your verification code
 Please specify an email verification message: Your verification code is {####}
 Do you want to override the default password policy for this User Pool? No
 Specify the app's refresh token expiration period (in days): 30
 Do you want to specify the user attributes this app can read and write? No
 Do you want to enable any of the following capabilities? 
 Do you want to use an OAuth flow? No
? Do you want to configure Lambda Triggers for Cognito? Yes
? Which triggers do you want to enable for Cognito Post Confirmation
? What functionality do you want to use for Post Confirmation Create your own module
Succesfully added the Lambda function locally
? Do you want to edit your custom function now? No
Successfully updated resource tevi locally

Some next steps:
"amplify push" will build all your local backend resources and provision it in the cloud
"amplify publish" will build all your local backend and frontend resources (if you have hosting category added) and provision it in the cloud

And then I did amplify push. Then when the function was completed, I updated this one like this:

andres@DESKTOP-CPTOQVN:~/TeVi$ amplify update function
Using service: Lambda, provided by: awscloudformation
? Please select the Lambda Function you would want to update teviPostConfirmation
? Do you want to update permissions granted to this Lambda function to perform on other resources in your project? Yes
? Select the category storage
? Storage has 12 resources in this project. Select the one you would like your Lambda to access User:@model(appsync)
? Select the operations you want to permit for User:@model(appsync) create, update

You can access the following resource attributes as environment variables from your Lambda function
        API_TEVI_GRAPHQLAPIIDOUTPUT
        API_TEVI_USERTABLE_ARN
        API_TEVI_USERTABLE_NAME
        ENV
        REGION
? Do you want to invoke this function on a recurring schedule? No
? Do you want to edit the local lambda function now? No
Successfully updated resource

Then I did amplify push and I got this error:

andres@DESKTOP-CPTOQVN:~/TeVi$ amplify push
✔ Successfully pulled backend environment dev from the cloud.

Current Environment: dev

| Category | Resource name        | Operation | Provider plugin   |
| -------- | -------------------- | --------- | ----------------- |
| Function | teviPostConfirmation | Update    | awscloudformation |
| Auth     | tevi                 | No Change | awscloudformation |
| Api      | tevi                 | No Change | awscloudformation |
| Storage  | s3c1026a67           | No Change | awscloudformation |
? Are you sure you want to continue? Yes
⠼ Updating resources in the cloud. This may take a few minutes...Error updating cloudformation stack
✖ An error occurred when pushing the resources to the cloud

Circular dependency between resources: [functionteviPostConfirmation, authtevi, UpdateRolesWithIDPFunctionOutputs, apitevi, UpdateRolesWithIDPFunction]
An error occured during the push operation: Circular dependency between resources: [functionteviPostConfirmation, authtevi, UpdateRolesWithIDPFunctionOutputs, apitevi, UpdateRolesWithIDPFunction]

This is the backend-config.json I have right now:

{
    "auth": {
        "tevi": {
            "service": "Cognito",
            "providerPlugin": "awscloudformation",
            "dependsOn": [
                {
                    "category": "function",
                    "resourceName": "teviPostConfirmation",
                    "triggerProvider": "Cognito",
                    "attributes": [
                        "Arn",
                        "Name"
                    ]
                }
            ]
        }
    },
    "api": {
        "tevi": {
            "service": "AppSync",
            "providerPlugin": "awscloudformation",
            "output": {
                "authConfig": {
                    "additionalAuthenticationProviders": [
                        {
                            "authenticationType": "AWS_IAM"
                        }
                    ],
                    "defaultAuthentication": {
                        "authenticationType": "AMAZON_COGNITO_USER_POOLS",
                        "userPoolConfig": {
                            "userPoolId": "authtevi"
                        }
                    }
                }
            }
        }
    },
    "storage": {
        "s3c1026a67": {
            "service": "S3",
            "providerPlugin": "awscloudformation"
        }
    },
    "function": {
        "teviPostConfirmation": {
            "build": true,
            "providerPlugin": "awscloudformation",
            "service": "Lambda",
            "dependsOn": [
                {
                    "category": "api",
                    "resourceName": "tevi",
                    "attributes": [
                        "GraphQLAPIIdOutput"
                    ]
                }
            ]
        }
    }
}

Amplify CLI Version 4.21.3

Expected behavior Work with the post-confirmation function and create or update content on the User table with this one.

How can I fix it :/?

1 Answers

As it has been discussed in the related GitHub ticket, we can solve this problem by invoking a function from another.

First, we assume that you used amplify update auth and added Cognito Post Confirmation function to add the user to a group.

Also it seems you followed the this tutorial to make a function for adding user to a custom model after confirmation event. However, you cannot follow the last step of this tutorial as only one function can be bind to the Post confirmation trigger. So let us bind our first function to Post confirmation trigger and keep this new function unbind. I assume that you named this recent function as addusertotable.

If you have added a function with amplify update auth, you will have a file which is called add-to-group.js, modify the function as follow:

/* eslint-disable-line */ const aws = require('aws-sdk');

// My defined function starts here
var addUserToTable = function (event, context) {
  // Call function to add user to table Users
  var lambda = new aws.Lambda({
    region: process.env.AWS_REGION
  });

  var params = {
    FunctionName: 'addusertotable-' + process.env.ENV,
    InvocationType: 'RequestResponse',
    Payload: JSON.stringify(event, context)
  };

  lambda.invoke(params, function (err, data) {
    if (err) {
      console.error(err);
    } else {
      console.log(params.FunctionName + ': ' + data.Payload);
    }
  });
};
// My defined function ends here

exports.handler = async (event, context, callback) => {
  // Call function to add user to table Users
  addUserToTable(event, context); // this is also my code to call my defined function
  // Rest are original code from amplify template 
  // Add group to the user
  const cognitoidentityserviceprovider = new aws.CognitoIdentityServiceProvider({ apiVersion: '2016-04-18' });
  const groupParams = {
    GroupName: process.env.GROUP,
    UserPoolId: event.userPoolId,
  };

  const addUserParams = {
    GroupName: process.env.GROUP,
    UserPoolId: event.userPoolId,
    Username: event.userName,
  };

  try {
    await cognitoidentityserviceprovider.getGroup(groupParams).promise();
  } catch (e) {
    await cognitoidentityserviceprovider.createGroup(groupParams).promise();
  }

  try {
    await cognitoidentityserviceprovider.adminAddUserToGroup(addUserParams).promise();
    callback(null, event);
  } catch (e) {
    callback(e);
  }
};

As it has been discussed here, we need to add a segment to the lambda policy that allows us to invoke the secondary lambda function (i.e. addusertotable).

Then find the xyzPostConfirmation-cloudformation-template.json file, and then change its PolicyDocument entry like this:

"PolicyDocument": {
          "Version": "2012-10-17",
          "Statement": [
            {
              "Effect": "Allow",
              "Action": [
                "logs:CreateLogGroup",
                "logs:CreateLogStream",
                "logs:PutLogEvents"
              ],
              "Resource": {
                "Fn::Sub": [
                  "arn:aws:logs:${region}:${account}:log-group:/aws/lambda/${lambda}:log-stream:*",
                  {
                    "region": {
                      "Ref": "AWS::Region"
                    },
                    "account": {
                      "Ref": "AWS::AccountId"
                    },
                    "lambda": {
                      "Ref": "LambdaFunction"
                    }
                  }
                ]
              }
            },
            {
              "Effect": "Allow",
              "Action": "lambda:InvokeFunction",
              "Resource": {
                "Fn::Sub": [
                  "arn:aws:lambda:${region}:${account}:function:addusertotable-${env}",
                  {
                    "region": {
                      "Ref": "AWS::Region"
                    },
                    "account": {
                      "Ref": "AWS::AccountId"
                    },
                    "lambda": {
                      "Ref": "LambdaFunction"
                    },
                    "env": {
                      "Ref": "env"
                    }
                  }
                ]
              }

Actually what I have added is the second object inside the Statement array.

Please note that addusertotable is the name of the custom function.

Related