├── .gitignore ├── README.md ├── license.txt ├── submitFormFunction ├── .npmignore ├── app.js ├── dynamodb.js ├── package.json ├── ses.js └── testHarness.js └── template.yaml /.gitignore: -------------------------------------------------------------------------------- 1 | 2 | # Created by https://www.gitignore.io/api/osx,node,linux,windows 3 | 4 | ### Linux ### 5 | *~ 6 | 7 | # temporary files which can be created if a process still has a handle open of a deleted file 8 | .fuse_hidden* 9 | 10 | # KDE directory preferences 11 | .directory 12 | 13 | # Linux trash folder which might appear on any partition or disk 14 | .Trash-* 15 | 16 | # .nfs files are created when an open file is removed but is still being accessed 17 | .nfs* 18 | 19 | ### Node ### 20 | # Logs 21 | logs 22 | *.log 23 | npm-debug.log* 24 | yarn-debug.log* 25 | yarn-error.log* 26 | 27 | # Runtime data 28 | pids 29 | *.pid 30 | *.seed 31 | *.pid.lock 32 | 33 | # Directory for instrumented libs generated by jscoverage/JSCover 34 | lib-cov 35 | 36 | # Coverage directory used by tools like istanbul 37 | coverage 38 | 39 | # nyc test coverage 40 | .nyc_output 41 | 42 | # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) 43 | .grunt 44 | 45 | # Bower dependency directory (https://bower.io/) 46 | bower_components 47 | 48 | # node-waf configuration 49 | .lock-wscript 50 | 51 | # Compiled binary addons (http://nodejs.org/api/addons.html) 52 | build/Release 53 | 54 | # Dependency directories 55 | node_modules/ 56 | jspm_packages/ 57 | 58 | # Typescript v1 declaration files 59 | typings/ 60 | 61 | # Optional npm cache directory 62 | .npm 63 | 64 | # Optional eslint cache 65 | .eslintcache 66 | 67 | # Optional REPL history 68 | .node_repl_history 69 | 70 | # Output of 'npm pack' 71 | *.tgz 72 | 73 | # Yarn Integrity file 74 | .yarn-integrity 75 | 76 | # dotenv environment variables file 77 | .env 78 | 79 | 80 | ### OSX ### 81 | *.DS_Store 82 | .AppleDouble 83 | .LSOverride 84 | 85 | # Icon must end with two \r 86 | Icon 87 | 88 | # Thumbnails 89 | ._* 90 | 91 | # Files that might appear in the root of a volume 92 | .DocumentRevisions-V100 93 | .fseventsd 94 | .Spotlight-V100 95 | .TemporaryItems 96 | .Trashes 97 | .VolumeIcon.icns 98 | .com.apple.timemachine.donotpresent 99 | 100 | # Directories potentially created on remote AFP share 101 | .AppleDB 102 | .AppleDesktop 103 | Network Trash Folder 104 | Temporary Items 105 | .apdisk 106 | 107 | ### Windows ### 108 | # Windows thumbnail cache files 109 | Thumbs.db 110 | ehthumbs.db 111 | ehthumbs_vista.db 112 | 113 | # Folder config file 114 | Desktop.ini 115 | 116 | # Recycle Bin used on file shares 117 | $RECYCLE.BIN/ 118 | 119 | # Windows Installer files 120 | *.cab 121 | *.msi 122 | *.msm 123 | *.msp 124 | 125 | # Windows shortcuts 126 | *.lnk 127 | samconfig.toml 128 | .aws-sam 129 | 130 | # End of https://www.gitignore.io/api/osx,node,linux,windows -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Serverless Form Handler 2 | 3 | The Serverless Form Handler accepts a form submission from a webpage, saving the data to a DynamoDB table and sending an email via SES. 4 | 5 | Important: this application uses various AWS services and there are costs associated with these services after the Free Tier usage - please see the [AWS pricing page](https://aws.amazon.com/pricing/) for details. 6 | 7 | ```bash 8 | . 9 | ├── README.MD <-- This instructions file 10 | ├── submitFormFunction <-- Source code for the main lambda function 11 | │ └── app.js <-- Main Lambda handler 12 | │ └── dynamodb.js <-- DynamoDB helper function 13 | │ └── ses.js <-- Wrapper for Amazon SES 14 | │ └── testHarness.js <-- For testing code locally 15 | │ └── package.json <-- NodeJS dependencies and scripts 16 | ├── template.yaml <-- SAM template 17 | ``` 18 | 19 | ## Requirements 20 | 21 | * AWS CLI already configured with Administrator permission 22 | * [NodeJS 12.x installed](https://nodejs.org/en/download/) 23 | 24 | ## Installation Instructions 25 | 26 | 1. [Create an AWS account](https://portal.aws.amazon.com/gp/aws/developer/registration/index.html) if you do not already have one and login. 27 | 1. Go to the app's page on the [Serverless Application Repository](https://serverlessrepo.aws.amazon.com/applications/) and click "Deploy" 28 | 1. Provide the required app parameters (see parameter details below) and click "Deploy" 29 | 30 | ## Parameter Details 31 | 32 | * Validated email: provided an email address that has been validated in the Amazon SES service in the same region when you are deploying this application. For instructions on how to validate an email in SES, see [this page](https://docs.aws.amazon.com/ses/latest/DeveloperGuide/verify-email-addresses-procedure.html). 33 | 34 | ## Using this Application 35 | 36 | * This application creates an API Gateway endpoint where browser-based forms can send text-based form data. The application will store the response in a DynamoDB table and email the form data to the Validated Email. 37 | * This application is for educational purposes and does not provide any throttling on the API Gateway endpoint. For production usage, you should [apply throttling to your API resources](https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-request-throttling.html). 38 | 39 | ## How it works 40 | 41 | * Deploy this serverless application and take a note of the API endpoint. 42 | * Create a form in a webpage and use the Javascript handling functon as shown in [this Gist](https://gist.github.com/jbesw/b75a2409521e2ff632dce7c8e07d6d2a) for an example. Use the API endpoint in the AJAX request to process the form data. 43 | 44 | ============================================== 45 | 46 | Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. 47 | 48 | SPDX-License-Identifier: MIT-0 -------------------------------------------------------------------------------- /license.txt: -------------------------------------------------------------------------------- 1 | MIT No Attribution 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy of this 4 | software and associated documentation files (the "Software"), to deal in the Software 5 | without restriction, including without limitation the rights to use, copy, modify, 6 | merge, publish, distribute, sublicense, and/or sell copies of the Software, and to 7 | permit persons to whom the Software is furnished to do so. 8 | 9 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, 10 | INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 11 | PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT 12 | HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 13 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE 14 | SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -------------------------------------------------------------------------------- /submitFormFunction/.npmignore: -------------------------------------------------------------------------------- 1 | tests/* 2 | -------------------------------------------------------------------------------- /submitFormFunction/app.js: -------------------------------------------------------------------------------- 1 | /*! Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | * SPDX-License-Identifier: MIT-0 3 | */ 4 | 5 | 'use strict' 6 | 7 | /** 8 | * 9 | * Event doc: https://docs.aws.amazon.com/apigateway/latest/developerguide/set-up-lambda-proxy-integrations.html#api-gateway-simple-proxy-for-lambda-input-format 10 | * @param {Object} event - API Gateway Lambda Proxy Input Format 11 | * 12 | */ 13 | 14 | const { saveFormData } = require('./dynamodb') 15 | const { sendEmail } = require('./ses') 16 | 17 | const headers = { 18 | 'Content-Type': 'application/json', 19 | 'Access-Control-Allow-Origin': '*', 20 | 'Access-Control-Allow-Headers': "Content-Type", 21 | "Access-Control-Allow-Methods": "OPTIONS,POST" 22 | } 23 | 24 | // Main Lambda entry point 25 | exports.handler = async (event) => { 26 | 27 | console.log(`Started with: ${event.body}`) 28 | const formData = JSON.parse(event.body) 29 | 30 | try { 31 | // Send email and save to DynamoDB in parallel using Promise.all 32 | await Promise.all([sendEmail(formData), saveFormData(formData)]) 33 | 34 | return { 35 | statusCode: 200, 36 | body: 'OK!', 37 | headers 38 | } 39 | } catch(err) { 40 | console.error('handler error: ', err) 41 | 42 | return { 43 | statusCode: 500, 44 | body: 'Error', 45 | headers 46 | } 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /submitFormFunction/dynamodb.js: -------------------------------------------------------------------------------- 1 | /*! Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | * SPDX-License-Identifier: MIT-0 3 | */ 4 | 5 | 'use strict' 6 | 7 | const AWS = require('aws-sdk') 8 | AWS.config.update({ region: process.env.AWS_REGION || 'us-east-1' }) 9 | const documentClient = new AWS.DynamoDB.DocumentClient() 10 | 11 | // DynamoDB functions. 12 | 13 | const saveFormData = async (formData) => { 14 | return new Promise((resolve, reject) => { 15 | const params = { 16 | TableName: process.env.FormDataTable, 17 | Item: { 18 | formId: Math.floor(Math.random() * Math.floor(10000000)).toString(), 19 | formData: JSON.stringify(formData), //stringify to store against empty responses in form 20 | created: Math.floor(Date.now() / 1000) 21 | } 22 | } 23 | console.log(params) 24 | documentClient.put(params, function(err, data) { 25 | if (err) { 26 | console.error(err) 27 | reject(err) 28 | } 29 | else resolve(data) 30 | }) 31 | }) 32 | } 33 | 34 | module.exports = { saveFormData } 35 | -------------------------------------------------------------------------------- /submitFormFunction/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "form-handler", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "app.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1" 8 | }, 9 | "keywords": [], 10 | "author": "James Beswick, Amazon Web Services", 11 | "license": "MIT", 12 | "dependencies": { 13 | "aws-sdk": "^2.1440.0" 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /submitFormFunction/ses.js: -------------------------------------------------------------------------------- 1 | /*! Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | * SPDX-License-Identifier: MIT-0 3 | */ 4 | 'use strict' 5 | 6 | const AWS = require('aws-sdk') 7 | AWS.config.update({ region: process.env.AWS_REGION || 'us-east-1' }) 8 | const SES = new AWS.SES() 9 | 10 | const sendEmail = async function (formData) { 11 | 12 | const getContent = (formData) => { 13 | let retval = '' 14 | for (var attribName in formData){ 15 | retval += attribName + ': ' + formData[attribName] + '\n\n' 16 | } 17 | return retval 18 | } 19 | 20 | return new Promise(async (resolve, reject) => { 21 | 22 | // Build params for SES 23 | const emailParams = { 24 | Source: process.env.ValidatedEmail, // SES SENDING EMAIL 25 | ReplyToAddresses: [process.env.ValidatedEmail], 26 | Destination: { 27 | ToAddresses: [process.env.ValidatedEmail], // SES RECEIVING EMAIL 28 | }, 29 | Message: { 30 | Body: { 31 | Text: { 32 | Charset: 'UTF-8', 33 | Data: getContent(formData) 34 | }, 35 | }, 36 | Subject: { 37 | Charset: 'UTF-8', 38 | Data: 'New Form Submission' 39 | }, 40 | }, 41 | } 42 | // Send the email 43 | try { 44 | const result = await SES.sendEmail(emailParams).promise() 45 | console.log('sendEmail result: ', result) 46 | resolve() 47 | } catch (err) { 48 | console.error('sendEmail error: ', err) 49 | reject() 50 | } 51 | }) 52 | } 53 | 54 | module.exports = { sendEmail } -------------------------------------------------------------------------------- /submitFormFunction/testHarness.js: -------------------------------------------------------------------------------- 1 | /*! Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | * SPDX-License-Identifier: MIT-0 3 | */ 4 | 5 | const { handler } = require('./app') 6 | 7 | // Mock event 8 | const event = { 9 | "body": "{\"name\": \"Sender Name\",\"reply_to\": \"sender@email.com\",\"message\": \"A test message\"}" 10 | } 11 | 12 | const main = async () => { 13 | await handler(event) 14 | } 15 | 16 | main() 17 | -------------------------------------------------------------------------------- /template.yaml: -------------------------------------------------------------------------------- 1 | AWSTemplateFormatVersion: '2010-09-09' 2 | Transform: AWS::Serverless-2016-10-31 3 | Description: > 4 | Serverless Form Handler - accepts a form submission from a webpage, saving the data to a DynamoDB table and sending an email via SES. 5 | 6 | Parameters: 7 | ValidatedEmail: 8 | Type: String 9 | Description: (Required) A validated SES email address for receiving new submissions. 10 | MaxLength: 70 11 | Default: validated@email.com 12 | MinLength: 4 13 | ConstraintDescription: Required. Must be a SES verified email address. 14 | 15 | # More info about Globals: https://github.com/awslabs/serverless-application-model/blob/master/docs/globals.rst 16 | Globals: 17 | Function: 18 | Timeout: 10 19 | Api: 20 | EndpointConfiguration: EDGE 21 | Cors: 22 | AllowMethods: "'OPTIONS,POST'" 23 | AllowHeaders: "'Content-Type'" 24 | AllowOrigin: "'*'" 25 | 26 | Resources: 27 | FormDataTable: 28 | Type: AWS::DynamoDB::Table 29 | Properties: 30 | AttributeDefinitions: 31 | - AttributeName: formId 32 | AttributeType: S 33 | KeySchema: 34 | - AttributeName: formId 35 | KeyType: HASH 36 | BillingMode: PAY_PER_REQUEST 37 | SubmitFormFunction: 38 | Type: AWS::Serverless::Function # More info about Function Resource: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction 39 | Properties: 40 | CodeUri: submitFormFunction/ 41 | Handler: app.handler 42 | Runtime: nodejs16.x 43 | MemorySize: 128 44 | Environment: 45 | Variables: 46 | ValidatedEmail: !Ref ValidatedEmail 47 | FormDataTable: !Ref FormDataTable 48 | Policies: 49 | - DynamoDBCrudPolicy: 50 | TableName: !Ref FormDataTable 51 | - SESCrudPolicy: 52 | IdentityName: !Ref ValidatedEmail 53 | Events: 54 | HttpPost: 55 | Type: Api 56 | Properties: 57 | Path: '/submitForm' 58 | Method: post 59 | 60 | Outputs: 61 | SubmitFormFunction: 62 | Description: "Lambda Function ARN" 63 | Value: !GetAtt SubmitFormFunction.Arn 64 | SubmitFormFunctionIamRole: 65 | Description: "Implicit IAM Role created for function" 66 | Value: !GetAtt SubmitFormFunctionRole.Arn 67 | FormDataTable: 68 | Description: DynamoDB Table 69 | Value: !Ref FormDataTable 70 | --------------------------------------------------------------------------------