2

当用户注册该方法Auth.signup并且此方法确认通过电子邮件收到的代码时。我想执行确认后触发器并更新通过 schema.graphql 文件上的 @model 方法创建的用户表。

我像这样更新了Auth:

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

然后我做到了amplify push。然后当功能完成后,我像这样更新了这个:

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

然后我做了amplify push,我得到了这个错误:

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]

这是backend-config.json我现在拥有的:

{
    "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"
                    ]
                }
            ]
        }
    }
}

放大 CLI 版本 4.21.3

预期行为 使用 post-confirmation 功能并使用此功能在 User 表上创建或更新内容。

我该如何解决:/?

4

1 回答 1

0

正如相关的 GitHub 票证中所讨论的,我们可以通过调用另一个函数来解决这个问题。

首先,我们假设您使用amplify update auth和添加Cognito Post Confirmation函数将用户添加到组。

此外,您似乎按照本教程制作了一个在确认事件后将用户添加到自定义模型的功能。但是,您不能遵循本教程的最后一步,因为只能将一个函数绑定到Post confirmation触发器。所以让我们绑定我们的第一个函数来Post confirmation触发并保持这个新函数解除绑定。我假设您将这个最近的函数命名为addusertotable.

如果你添加了一个带有 的函数amplify update auth,你将有一个名为 的文件add-to-group.js,修改函数如下:

/* 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);
  }
};

正如这里所讨论的,我们需要在 lambda 策略中添加一个允许我们调用辅助 lambda 函数(即 addusertotable)的段。

然后找到该xyzPostConfirmation-cloudformation-template.json文件,然后PolicyDocument像这样更改其条目:

"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"
                    }
                  }
                ]
              }

实际上我添加的是Statement数组中的第二个对象。

请注意,这addusertotable是自定义函数的名称。

于 2021-01-12T11:03:37.330 回答