【问题标题】:Trying to use model within post-confirmation function尝试在后确认功能中使用模型
【发布时间】:2020-10-11 16:06:15
【问题描述】:

当用户使用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 表上创建或更新内容。

我该如何解决:/?

【问题讨论】:

标签: amazon-web-services aws-amplify aws-amplify-cli


【解决方案1】:

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

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

您似乎也遵循了this tutorial 在确认事件后将用户添加到自定义模型的功能。但是,您不能遵循本教程的最后一步,因为只有一个函数可以绑定到 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);
  }
};

正如here 所讨论的那样,我们需要在 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是自定义函数的名称。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-10
    • 1970-01-01
    • 2020-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多