尝试在确认后功能中使用模型 [英] Trying to use model within post-confirmation function

查看:20
本文介绍了尝试在确认后功能中使用模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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]

这是我现在拥有的 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 表上创建或更新内容.

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

我该如何解决:/?

推荐答案

在相关的 GitHub 票证中已经讨论过,我们可以通过调用另一个函数来解决这个问题.

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

首先,我们假设您使用了 amplify update auth 并添加了 Cognito Post Confirmation 功能以将用户添加到组中.

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

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

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.

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

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

正如在此处讨论的那样,我们需要添加lambda 策略的一个段,允许我们调用辅助 lambda 函数(即 addusertotable).

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).

然后找到xyzPostConfirmation-cloudformation-template.json文件,然后像这样修改它的PolicyDocument条目:

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

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

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

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

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

这篇关于尝试在确认后功能中使用模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆