Skip to content

Commit

Permalink
[feat] Added Chapter6. Cognito&S3 Trigger
Browse files Browse the repository at this point in the history
- 인증 및 S3에 대한 람다 트리거 추가
- Cognito 트리거의 경우, lambdatriggerc602322aPostConfirmation-cloudformation-template 수정 필요
  - Cognito 접근을 위해 Policy에 cogniot-idp 관련 권한 추가
  - aws-amplify/amplify-js#1565 참고
- 각 트리거 테스트를 위한 클라이언트 추가
  - React Router를 사용하여 각 테스트에 대한 컴포넌트 구현
  • Loading branch information
yoonjeong-choi-dev committed Nov 15, 2021
1 parent 823bb36 commit e3f62ad
Show file tree
Hide file tree
Showing 50 changed files with 2,869 additions and 0 deletions.
45 changes: 45 additions & 0 deletions ComputerScience/Web/FullStackServerless/lambda-trigger/.gitignore
@@ -0,0 +1,45 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.

# dependencies
/node_modules
/.pnp
.pnp.js

# testing
/coverage

# production
/build

# misc
.DS_Store
.env.local
.env.development.local
.env.test.local
.env.production.local

npm-debug.log*
yarn-debug.log*
yarn-error.log*

#amplify-do-not-edit-begin
amplify/\#current-cloud-backend
amplify/.config/local-*
amplify/logs
amplify/mock-data
amplify/backend/amplify-meta.json
amplify/backend/awscloudformation
amplify/backend/.temp
build/
dist/
node_modules/
aws-exports.js
awsconfiguration.json
amplifyconfiguration.json
amplifyconfiguration.dart
amplify-build-config.json
amplify-gradle-config.json
amplifytools.xcconfig
.secret-*
**.sample
#amplify-do-not-edit-end
70 changes: 70 additions & 0 deletions ComputerScience/Web/FullStackServerless/lambda-trigger/README.md
@@ -0,0 +1,70 @@
# Getting Started with Create React App

This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).

## Available Scripts

In the project directory, you can run:

### `npm start`

Runs the app in the development mode.\
Open [http://localhost:3000](http://localhost:3000) to view it in the browser.

The page will reload if you make edits.\
You will also see any lint errors in the console.

### `npm test`

Launches the test runner in the interactive watch mode.\
See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.

### `npm run build`

Builds the app for production to the `build` folder.\
It correctly bundles React in production mode and optimizes the build for the best performance.

The build is minified and the filenames include the hashes.\
Your app is ready to be deployed!

See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.

### `npm run eject`

**Note: this is a one-way operation. Once you `eject`, you can’t go back!**

If you aren’t satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project.

Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own.

You don’t have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it.

## Learn More

You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started).

To learn React, check out the [React documentation](https://reactjs.org/).

### Code Splitting

This section has moved here: [https://facebook.github.io/create-react-app/docs/code-splitting](https://facebook.github.io/create-react-app/docs/code-splitting)

### Analyzing the Bundle Size

This section has moved here: [https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size](https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size)

### Making a Progressive Web App

This section has moved here: [https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app](https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app)

### Advanced Configuration

This section has moved here: [https://facebook.github.io/create-react-app/docs/advanced-configuration](https://facebook.github.io/create-react-app/docs/advanced-configuration)

### Deployment

This section has moved here: [https://facebook.github.io/create-react-app/docs/deployment](https://facebook.github.io/create-react-app/docs/deployment)

### `npm run build` fails to minify

This section has moved here: [https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify](https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify)
@@ -0,0 +1,17 @@
{
"projectName": "lambdatrigger",
"version": "3.1",
"frontend": "javascript",
"javascript": {
"framework": "react",
"config": {
"SourceDir": "src",
"DistributionDir": "build",
"BuildCommand": "npm run-script build",
"StartCommand": "npm run-script start"
}
},
"providers": [
"awscloudformation"
]
}
@@ -0,0 +1,8 @@
# Getting Started with Amplify CLI
This directory was generated by [Amplify CLI](https://docs.amplify.aws/cli).

Helpful resources:
- Amplify documentation: https://docs.amplify.aws
- Amplify CLI documentation: https://docs.amplify.aws/cli
- More details on this folder & generated files: https://docs.amplify.aws/cli/reference/files
- Join Amplify's community: https://amplify.aws/community/
@@ -0,0 +1,148 @@
{
"Description": "Custom Resource stack for Auth Trigger created using Amplify CLI",
"AWSTemplateFormatVersion": "2010-09-09",
"Parameters": {
"env": {
"Type": "String"
},
"userpoolId": {
"Type": "String"
},
"userpoolArn": {
"Type": "String"
},
"functionlambdatriggerc602322aPostConfirmationName": {
"Type": "String"
},
"functionlambdatriggerc602322aPostConfirmationArn": {
"Type": "String"
}
},
"Conditions": {
"ShouldNotCreateEnvResources": {
"Fn::Equals": [
{
"Ref": "env"
},
"NONE"
]
}
},
"Resources": {
"UserPoolPostConfirmationLambdaInvokePermission": {
"Type": "AWS::Lambda::Permission",
"Properties": {
"Action": "lambda:InvokeFunction",
"FunctionName": {
"Ref": "functionlambdatriggerc602322aPostConfirmationName"
},
"Principal": "cognito-idp.amazonaws.com",
"SourceArn": {
"Ref": "userpoolArn"
}
}
},
"authTriggerFnServiceRole08093B67": {
"Type": "AWS::IAM::Role",
"Properties": {
"AssumeRolePolicyDocument": {
"Statement": [
{
"Action": "sts:AssumeRole",
"Effect": "Allow",
"Principal": {
"Service": "lambda.amazonaws.com"
}
}
],
"Version": "2012-10-17"
},
"ManagedPolicyArns": [
{
"Fn::Join": [
"",
[
"arn:",
{
"Ref": "AWS::Partition"
},
":iam::aws:policy/service-role/AWSLambdaBasicExecutionRole"
]
]
}
]
}
},
"authTriggerFnServiceRoleDefaultPolicyEC9285A8": {
"Type": "AWS::IAM::Policy",
"Properties": {
"PolicyDocument": {
"Statement": [
{
"Action": [
"cognito-idp:DescribeUserPool",
"cognito-idp:DescribeUserPoolClient",
"cognito-idp:UpdateUserPool",
"iam:PassRole"
],
"Effect": "Allow",
"Resource": "*"
}
],
"Version": "2012-10-17"
},
"PolicyName": "authTriggerFnServiceRoleDefaultPolicyEC9285A8",
"Roles": [
{
"Ref": "authTriggerFnServiceRole08093B67"
}
]
}
},
"authTriggerFn7FCFA449": {
"Type": "AWS::Lambda::Function",
"Properties": {
"Code": {
"ZipFile": "const response = require('cfn-response');\nconst aws = require('aws-sdk');\n\nexports.handler = async function (event, context) {\n try {\n const userPoolId = event.ResourceProperties.userpoolId;\n const lambdaConfig = event.ResourceProperties.lambdaConfig;\n const config = {};\n const cognitoClient = new aws.CognitoIdentityServiceProvider();\n const userPoolConfig = await cognitoClient.describeUserPool({ UserPoolId: userPoolId }).promise();\n const userPoolParams = userPoolConfig.UserPool;\n // update userPool params\n\n const updateUserPoolConfig = {\n UserPoolId: userPoolParams.Id,\n Policies: userPoolParams.Policies,\n SmsVerificationMessage: userPoolParams.SmsVerificationMessage,\n AccountRecoverySetting: userPoolParams.AccountRecoverySetting,\n AdminCreateUserConfig: userPoolParams.AdminCreateUserConfig,\n AutoVerifiedAttributes: userPoolParams.AutoVerifiedAttributes,\n EmailConfiguration: userPoolParams.EmailConfiguration,\n EmailVerificationMessage: userPoolParams.EmailVerificationMessage,\n EmailVerificationSubject: userPoolParams.EmailVerificationSubject,\n VerificationMessageTemplate: userPoolParams.VerificationMessageTemplate,\n SmsAuthenticationMessage: userPoolParams.SmsAuthenticationMessage,\n MfaConfiguration: userPoolParams.MfaConfiguration,\n DeviceConfiguration: userPoolParams.DeviceConfiguration,\n SmsConfiguration: userPoolParams.SmsConfiguration,\n UserPoolTags: userPoolParams.UserPoolTags,\n UserPoolAddOns: userPoolParams.UserPoolAddOns,\n };\n\n // removing undefined keys\n Object.keys(updateUserPoolConfig).forEach(key => updateUserPoolConfig[key] === undefined && delete updateUserPoolConfig[key]);\n\n /*removing UnusedAccountValidityDays as deprecated\n InvalidParameterException: Please use TemporaryPasswordValidityDays in PasswordPolicy instead of UnusedAccountValidityDays\n */\n if (updateUserPoolConfig.AdminCreateUserConfig && updateUserPoolConfig.AdminCreateUserConfig.UnusedAccountValidityDays) {\n delete updateUserPoolConfig.AdminCreateUserConfig.UnusedAccountValidityDays;\n }\n\n lambdaConfig.forEach(lambda => (config[`${lambda.triggerType}`] = lambda.lambdaFunctionArn));\n if (event.RequestType == 'Delete') {\n try {\n updateUserPoolConfig.LambdaConfig = {};\n const result = await cognitoClient.updateUserPool(updateUserPoolConfig).promise();\n console.log('delete response data ' + JSON.stringify(result));\n await response.send(event, context, response.SUCCESS, {});\n } catch (err) {\n console.log(err.stack);\n await response.send(event, context, response.FAILED, { err });\n }\n }\n if (event.RequestType == 'Update' || event.RequestType == 'Create') {\n updateUserPoolConfig.LambdaConfig = config;\n console.log(updateUserPoolConfig);\n try {\n const result = await cognitoClient.updateUserPool(updateUserPoolConfig).promise();\n console.log('createOrUpdate response data ' + JSON.stringify(result));\n await response.send(event, context, response.SUCCESS, { result });\n } catch (err) {\n console.log(err.stack);\n await response.send(event, context, response.FAILED, { err });\n }\n }\n } catch (err) {\n console.log(err.stack);\n await response.send(event, context, response.FAILED, { err });\n }\n};\n"
},
"Role": {
"Fn::GetAtt": [
"authTriggerFnServiceRole08093B67",
"Arn"
]
},
"Handler": "index.handler",
"Runtime": "nodejs12.x"
},
"DependsOn": [
"authTriggerFnServiceRoleDefaultPolicyEC9285A8",
"authTriggerFnServiceRole08093B67"
]
},
"CustomAuthTriggerResource": {
"Type": "Custom::CustomAuthTriggerResourceOutputs",
"Properties": {
"ServiceToken": {
"Fn::GetAtt": [
"authTriggerFn7FCFA449",
"Arn"
]
},
"userpoolId": {
"Ref": "userpoolId"
},
"lambdaConfig": [
{
"triggerType": "PostConfirmation",
"lambdaFunctionName": "lambdatriggerc602322aPostConfirmation",
"lambdaFunctionArn": {
"Ref": "functionlambdatriggerc602322aPostConfirmationArn"
}
}
]
},
"UpdateReplacePolicy": "Delete",
"DeletionPolicy": "Delete"
}
}
}

0 comments on commit e3f62ad

Please sign in to comment.