From 5ecd118938a7dbfef1065f012aeafa0912638ca3 Mon Sep 17 00:00:00 2001 From: Horea Porutiu Date: Fri, 1 Mar 2024 10:56:43 +0100 Subject: [PATCH] Add dynamo db example (#253) --- .../terms-modal-banner-dynamodb/.gitignore | 146 +++++++ examples/terms-modal-banner-dynamodb/LICENSE | 21 + .../terms-modal-banner-dynamodb/README.md | 115 ++++++ .../readApp/app.js | 81 ++++ .../readApp/package.json | 15 + .../terms-modal-banner-dynamodb/template.yaml | 389 ++++++++++++++++++ .../webassets/app.html | 128 ++++++ .../webassets/modal.html | 192 +++++++++ .../webassets/variables.js | 13 + .../writeApp/app.js | 70 ++++ .../writeApp/package.json | 15 + 11 files changed, 1185 insertions(+) create mode 100644 examples/terms-modal-banner-dynamodb/.gitignore create mode 100644 examples/terms-modal-banner-dynamodb/LICENSE create mode 100644 examples/terms-modal-banner-dynamodb/README.md create mode 100644 examples/terms-modal-banner-dynamodb/readApp/app.js create mode 100644 examples/terms-modal-banner-dynamodb/readApp/package.json create mode 100644 examples/terms-modal-banner-dynamodb/template.yaml create mode 100644 examples/terms-modal-banner-dynamodb/webassets/app.html create mode 100644 examples/terms-modal-banner-dynamodb/webassets/modal.html create mode 100644 examples/terms-modal-banner-dynamodb/webassets/variables.js create mode 100644 examples/terms-modal-banner-dynamodb/writeApp/app.js create mode 100644 examples/terms-modal-banner-dynamodb/writeApp/package.json diff --git a/examples/terms-modal-banner-dynamodb/.gitignore b/examples/terms-modal-banner-dynamodb/.gitignore new file mode 100644 index 000000000..d9b5e2934 --- /dev/null +++ b/examples/terms-modal-banner-dynamodb/.gitignore @@ -0,0 +1,146 @@ + +# Created by https://www.gitignore.io/api/osx,node,linux,windows + +### Linux ### +*~ + +# temporary files which can be created if a process still has a handle open of a deleted file +.fuse_hidden* + +# KDE directory preferences +.directory + +# Linux trash folder which might appear on any partition or disk +.Trash-* + +# .nfs files are created when an open file is removed but is still being accessed +.nfs* + +### Node ### +# Logs +logs +*.log +npm-debug.log* +yarn-debug.log* +yarn-error.log* + +# Runtime data +pids +*.pid +*.seed +*.pid.lock + +# Directory for instrumented libs generated by jscoverage/JSCover +lib-cov + +# Coverage directory used by tools like istanbul +coverage + +# nyc test coverage +.nyc_output + +# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) +.grunt + +# Bower dependency directory (https://bower.io/) +bower_components + +# node-waf configuration +.lock-wscript + +# Compiled binary addons (http://nodejs.org/api/addons.html) +build/Release + +# Dependency directories +node_modules/ +jspm_packages/ + +# Typescript v1 declaration files +typings/ + +# Optional npm cache directory +.npm + +# Optional eslint cache +.eslintcache + +# Optional REPL history +.node_repl_history + +# Output of 'npm pack' +*.tgz + +# Yarn Integrity file +.yarn-integrity + +# dotenv environment variables file +.env + + +### OSX ### +*.DS_Store +.AppleDouble +.LSOverride + +# Icon must end with two \r +Icon + +# Thumbnails +._* + +# Files that might appear in the root of a volume +.DocumentRevisions-V100 +.fseventsd +.Spotlight-V100 +.TemporaryItems +.Trashes +.VolumeIcon.icns +.com.apple.timemachine.donotpresent + +# Directories potentially created on remote AFP share +.AppleDB +.AppleDesktop +Network Trash Folder +Temporary Items +.apdisk + +### Windows ### +# Windows thumbnail cache files +Thumbs.db +ehthumbs.db +ehthumbs_vista.db + +# Folder config file +Desktop.ini + +# Recycle Bin used on file shares +$RECYCLE.BIN/ + +# Windows Installer files +*.cab +*.msi +*.msm +*.msp + +# Windows shortcuts +*.lnk + + +# End of https://www.gitignore.io/api/osx,node,linux,windows + +# Editor directories and files +.idea +.vscode +*.suo +*.ntvs* +*.njsproj +*.sln +*.sw? + +#AWS/SAM +.aws-sam +packaged.yaml +samconfig.toml + +#jbesw-specific +testData/ diff --git a/examples/terms-modal-banner-dynamodb/LICENSE b/examples/terms-modal-banner-dynamodb/LICENSE new file mode 100644 index 000000000..caab4f9ff --- /dev/null +++ b/examples/terms-modal-banner-dynamodb/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2024 Miro + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/examples/terms-modal-banner-dynamodb/README.md b/examples/terms-modal-banner-dynamodb/README.md new file mode 100644 index 000000000..c74d3ea6f --- /dev/null +++ b/examples/terms-modal-banner-dynamodb/README.md @@ -0,0 +1,115 @@ +# Miro Terms Modal Banner App (Web-SDK V2 & AWS DynamoDB) + +This app creates a custom modal banner on your Miro boards that you can show to your users/attendees with any desired content and/or call to actions. It is typically used to accept terms and agreements before using a Miro board. + + To understand how to set up the app (including AWS resources needed to run the app) see the +[developer tutorial](https://developers.miro.com/v2.0/docs/terms-modal-banner-aws-dynamodb) on Miro's Developer documentation. + +💸 **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. You are responsible for any AWS costs incurred. No warranty is implied in this example. 💸 + +# 👨🏻‍💻 App Demo + +https://github.com/miroapp/app-examples/assets/10428517/7c97412a-b3ac-4811-965b-af992e7ff7f9 + +# 📒 Table of Contents + +- [Support](#support) +- [Included Features](#features) +- [Tools and Technologies](#tools) +- [Prerequisites](#prerequisites) +- [Associated Developer Tutorial](#tutorial) +- [Run the app locally](#run) +- [Folder Structure](#folder) +- [Contributing](#contributing) +- [License](#license) + +# 🙋🏻 Support + +If you have any questions or need assistance setting up this application, please reach out to your Miro Customer Success Manager or dedicated Miro Solutions Engineer. + +# ⚙️ Included Features + +- [Miro Web SDK](https://developers.miro.com/docs/web-sdk-reference) + - [miro.board.ui.canOpenModal()](https://developers.miro.com/docs/websdk-reference-ui#canopenmodal) + - [miro.board.ui.openModal()](https://developers.miro.com/docs/websdk-reference-ui#openmodal) + - [miro.board.ui.closeModal()](https://developers.miro.com/docs/websdk-reference-ui#closemodal) + - [miro.board.getUserInfo()](https://developers.miro.com/docs/websdk-reference-board#getuserinfo) + +# 🛠️ Tools and Technologies + +- [AWS CLI](https://aws.amazon.com/cli/) +- [AWS SAM CLI](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-install.html) +- [AWS CloudFormation](https://aws.amazon.com/cloudformation/) +- [AWS DynamoDB](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Introduction.html) +- [AWS S3](https://docs.aws.amazon.com/s3) +- [AWS Lambda](https://aws.amazon.com/lambda/) +- [AWS API Gateway](https://aws.amazon.com/api-gateway/) + +# ✅ Prerequisites + +- You have a [Miro account](https://miro.com/signup/). +- You're [signed in to Miro](https://miro.com/login/). +- Your Miro account has a [Developer team](https://developers.miro.com/docs/create-a-developer-team). +- [NodeJS 16.x installed](https://nodejs.org/en/download/) +- [AWS CLI](https://aws.amazon.com/cli/) already configured with Administrator permission +- [AWS SAM CLI installed](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-install.html) - minimum version 0.48. + +# 📖 Associated Developer Tutorial + +Using AWS S3 you can host your html files and serve them as regular web pages so they can load within Miro. In addition, you can also use AWS DynamoDB to add custom functionality to your Miro app to track which users have already accepted the modal, so that the modal does not re-appear again for those users. In this guide we will guide you on how to achieve this functionality using Miro and AWS DynamoDB. + +> See the [developer tutorial](https://developers.miro.com/v2.0/docs/terms-modal-banner-aws-dynamodb) on Miro's Developer documentation. + +# 🏃🏽‍♂️ Run the app using AWS S3 + +Once you have finished all of the steps related to AWS in the [developer tutorial](https://developers.miro.com/v2.0/docs/terms-modal-banner-aws-dynamodb), you can then create the Miro app. + +1. In your new Miro app settings, add in the `App URL`. It should end with `webassets/app.html`. +2. Open the [app manifest editor](https://developers.miro.com/docs/manually-create-an-app#step-2-configure-your-app-in-miro) by clicking **Edit in Manifest**. \ + In the app manifest editor, configure the app as follows ⚠️ Note: you will need to change your sdkUri to be your app.html which is hosted in the `webassets` folder of your S3 bucket. Mine is just shown as an example and then click save: + +```yaml +# See https://developers.miro.com/docs/app-manifest on how to use this +appName: s3-modal-banner +sdkVersion: SDK_V2 +sdkUri: >- + https://s3-miro-terms-banner-12345.s3.amazonaws.com/webassets/app.html +scopes: + - identity:read +``` + +3. Go back to your app home page, and under the `Permissions` section, you will see a blue button that says `Install app and get OAuth token`. Click that button. Then click on `Add` as shown in the video below. In the video we install a different app, but the process is the same regardless of the app. + +> ⚠️ We recommend to install your app on a [developer team](https://developers.miro.com/docs/create-a-developer-team) while you are developing or testing apps.⚠️ + +https://github.com/miroapp/app-examples/assets/10428517/588688ed-eb14-4b64-9dbb-66d1c07eea54 + +4. Go to the team in which you installed the app, and open a board. +5. Once you open the board, the modal should appear within a few seconds. +6. If you click accept, you should see a checkmark and then you should not see the modal again when refreshing the page or opening a new board + on that team. +7. You can also check your AWS DynamoDB database under `Explore Items` tab on the left side and then make sure you select your database which you created as part of this guide and then you should see some Items returned which should be the Miro UserID of the user which has clicked on the "accept" button on the terms. + +🎉 That's it. Great job! 🎉 + +# 🗂️ Folder structure + +``` +. +├── readApp +│ └── app.js // Source code for the serverless backend ("Read" database Lambda function) +├── webassets // HTML and JavaScript files for the Miro app. +│ ├── app.html // The code which uses Miro WebSDK to open the modal for the user. +│ └── modal.html // The code which serves as the UI for the terms which the user will accept. +├── writeApp +│ └── app.js // Source code for the serverless backend ("Write" database Lambda function) +├── template.yaml <-- The yaml code used to generate AWS resources via AWS SAM. +``` + +# 🫱🏻‍🫲🏽 Contributing + +If you want to contribute to this example, or any other Miro Open Source project, please review [Miro's contributing guide](https://github.com/miroapp/app-examples/blob/main/CONTRIBUTING.md). + +# 🪪 License + +[MIT License](https://github.com/miroapp/app-examples/blob/main/LICENSE). diff --git a/examples/terms-modal-banner-dynamodb/readApp/app.js b/examples/terms-modal-banner-dynamodb/readApp/app.js new file mode 100644 index 000000000..5b3bdc510 --- /dev/null +++ b/examples/terms-modal-banner-dynamodb/readApp/app.js @@ -0,0 +1,81 @@ +const AWS = require("aws-sdk"); + +exports.handler = async (event) => { + const dynamoDB = new AWS.DynamoDB.DocumentClient(); + const tableName = process.env.TABLE_NAME; + + const onlyLettersAndNumbers = function (str) { + return /^[A-Za-z0-9]*$/.test(str); + }; + + const responseHeaders = { + "Access-Control-Allow-Headers": "Content-Type,Accept,Cache-Control,Pragma", + "Access-Control-Allow-Origin": "*", // Replace wildcard (*) with your S3 bucket base URL (visible in your AWS SAML CLI Outputs) - See step 2.10 of the PDF guide https://drive.google.com/file/d/13fdsfiTGCBRWSmAv_7BuMBsWfg4_OWlO/view?usp=sharing + "Access-Control-Allow-Methods": "OPTIONS,GET", // Allow only GET request + "Content-Type": "application/json", + }; + + if (event?.queryStringParameters?.u) { + const userId = event.queryStringParameters.u.toString(); + const isValidUserId = onlyLettersAndNumbers(userId); + + if (!isValidUserId) { + /* Returning a 409 error if the value of the URL parameter "u" passed in the GET request contains characters other than letters and numbers */ + return { + statusCode: 409, + headers: responseHeaders, + body: JSON.stringify({ error: "Invalid Data" }), + }; + } + } else { + return { + statusCode: 415, + headers: responseHeaders, + body: JSON.stringify({ error: "Invalid Request" }), + }; + } + + const userId = event.queryStringParameters.u.toString(); + + const params = { + TableName: tableName, + Key: { + id: userId, + }, + }; + + try { + const data = await dynamoDB.get(params).promise(); + + if ( + data && + !!Object.getOwnPropertyDescriptor(data, "Item") && + !!Object.getOwnPropertyDescriptor(data.Item, "id") && + data.Item.id.toString() === userId + ) { + /* Returning a 200 OK if the value of the URL parameter "u" matches an entry in the MiroBannerTermsAccepters DynamoDB table */ + return { + statusCode: 200, + //body: JSON.stringify(data.Item) + headers: responseHeaders, + body: JSON.stringify({ result: "success" }), + }; + } else { + /* Returning a 404 error if the value of the URL parameter "u" does not match any entry in the DynamoDB table */ + return { + statusCode: 404, + headers: responseHeaders, + body: JSON.stringify({ error: "Not Found" }), + }; + } + } catch (error) { + console.error("Error querying DynamoDB:", error); + + /* Returning a 500 error for any other error not catched above */ + return { + statusCode: 500, + headers: responseHeaders, + body: JSON.stringify({ error: "Internal Server Error" }), + }; + } +}; diff --git a/examples/terms-modal-banner-dynamodb/readApp/package.json b/examples/terms-modal-banner-dynamodb/readApp/package.json new file mode 100644 index 000000000..6479c9be9 --- /dev/null +++ b/examples/terms-modal-banner-dynamodb/readApp/package.json @@ -0,0 +1,15 @@ +{ + "name": "MiroBannerTermsAcceptersReadApp", + "version": "1.0.0", + "description": "", + "main": "index.js", + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "keywords": [], + "author": "Luis Colman, Miro Platform Architecture", + "license": "MIT-0", + "devDependencies": { + "aws-sdk": "^2.749.0" + } +} diff --git a/examples/terms-modal-banner-dynamodb/template.yaml b/examples/terms-modal-banner-dynamodb/template.yaml new file mode 100644 index 000000000..56418cc86 --- /dev/null +++ b/examples/terms-modal-banner-dynamodb/template.yaml @@ -0,0 +1,389 @@ +AWSTemplateFormatVersion: "2010-09-09" +Transform: "AWS::Serverless-2016-10-31" +Description: Miro Banner Terms Accepters + +Resources: + ## S3 Bucket + MiroTermsBannerFrontend: + Type: AWS::S3::Bucket + Properties: + BucketName: + !Join [ + "", + [ + "s3-", + !Join [ + "-", + [ + "miro-terms-banner-frontend", + !Select [ + 4, + !Split ["-", !Select [2, !Split ["/", !Ref AWS::StackId]]], + ], + ], + ], + ], + ] + CorsConfiguration: + CorsRules: + - AllowedHeaders: + - "*" + AllowedMethods: + - GET + AllowedOrigins: + - !Join [ + "", + [ + "https://s3-", + !Join [ + "-", + [ + "miro-terms-banner-frontend", + !Select [ + 4, + !Split [ + "-", + !Select [2, !Split ["/", !Ref AWS::StackId]], + ], + ], + ], + ], + ".s3.", + !Ref AWS::Region, + ".amazonaws.com", + ], + ] + - !Join [ + "", + [ + "https://s3-", + !Join [ + "-", + [ + "miro-terms-banner-frontend", + !Select [ + 4, + !Split [ + "-", + !Select [2, !Split ["/", !Ref AWS::StackId]], + ], + ], + ], + ], + ".s3.amazonaws.com", + ], + ] + PublicAccessBlockConfiguration: + BlockPublicAcls: false + BlockPublicPolicy: false + IgnorePublicAcls: false + RestrictPublicBuckets: false + + ## S3 Bucket Policy - This permission will make the contents of the S3 bucket publicly readable + ProductBucketPolicy: + Type: AWS::S3::BucketPolicy + Properties: + Bucket: !Ref MiroTermsBannerFrontend + PolicyDocument: + Id: PublicReadPolicy + Version: "2012-10-17" + Statement: + - Sid: PublicReadForGetBucketObjects + Effect: Allow + Principal: "*" + Action: s3:GetObject + Resource: !Sub "arn:aws:s3:::${MiroTermsBannerFrontend}/*" + Condition: {} + + ## Database where users who have accepted the Miro Banner will be captured. + ## The "id" will be the numeric Miro User ID, stored as a string. You may use a hashed version of the Miro ID in this table instead (if desired) + MiroBannerTermsAcceptersTable: + Type: "AWS::Serverless::SimpleTable" + Properties: + TableName: + !Join [ + "-", + [ + "miro-terms-banner-accepters-database", + !Select [ + 4, + !Split ["-", !Select [2, !Split ["/", !Ref AWS::StackId]]], + ], + ], + ] + PrimaryKey: + Name: id + Type: String + + ## IAM Role for the "Read" Lambda Function to query/read the database + MiroBannerTermsReadFunctionRole: + Type: "AWS::IAM::Role" + Properties: + RoleName: MiroBannerTermsReadFunctionRole + AssumeRolePolicyDocument: + Version: "2012-10-17" + Statement: + - Effect: Allow + Principal: + Service: + - lambda.amazonaws.com + Action: "sts:AssumeRole" + Policies: + - PolicyName: MiroBannerTermsDynamoDBReadPolicy + PolicyDocument: + Version: "2012-10-17" + Statement: + - Effect: Allow + Action: + - "dynamodb:GetItem" + Resource: !GetAtt MiroBannerTermsAcceptersTable.Arn + + ## IAM Role for the "Write" Lambda Function to write on the database + MiroBannerTermsWriteFunctionRole: + Type: "AWS::IAM::Role" + Properties: + RoleName: MiroBannerTermsWriteFunctionRole + AssumeRolePolicyDocument: + Version: "2012-10-17" + Statement: + - Effect: Allow + Principal: + Service: + - lambda.amazonaws.com + Action: "sts:AssumeRole" + Policies: + - PolicyName: MiroBannerTermsDynamoDBWritePolicy + PolicyDocument: + Version: "2012-10-17" + Statement: + - Effect: Allow + Action: + - "dynamodb:UpdateItem" + Resource: !GetAtt MiroBannerTermsAcceptersTable.Arn + + ## Lambda "Read" Function + MiroBannerTermsReadFunction: + Type: "AWS::Serverless::Function" + Properties: + FunctionName: + !Join [ + "-", + [ + "MiroBannerTermsReadFunction", + !Select [ + 4, + !Split ["-", !Select [2, !Split ["/", !Ref AWS::StackId]]], + ], + ], + ] + Description: !Sub 'Lambda function for the "Miro Terms Modal app". It reads data from the DynamoDB table "${MiroBannerTermsAcceptersTable}"' + Handler: app.handler + Runtime: nodejs16.x + CodeUri: readApp/ + Timeout: 10 + Role: !GetAtt MiroBannerTermsReadFunctionRole.Arn + Environment: + Variables: + TABLE_NAME: !Ref MiroBannerTermsAcceptersTable + + ## Lambda "Write" Function + MiroBannerTermsWriteFunction: + Type: "AWS::Serverless::Function" + Properties: + FunctionName: + !Join [ + "-", + [ + "MiroBannerTermsWriteFunction", + !Select [ + 4, + !Split ["-", !Select [2, !Split ["/", !Ref AWS::StackId]]], + ], + ], + ] + Description: !Sub 'Lambda function for the "Miro Terms Modal app". It writes data on the DynamoDB table "${MiroBannerTermsAcceptersTable}"' + Handler: app.handler + Runtime: nodejs16.x + CodeUri: writeApp/ + Timeout: 10 + Role: !GetAtt MiroBannerTermsWriteFunctionRole.Arn + Environment: + Variables: + TABLE_NAME: !Ref MiroBannerTermsAcceptersTable + + ## API Gateway + MiroBannerTermsAPI: + Type: "AWS::Serverless::Api" + Properties: + Name: + !Join [ + "", + [ + "api-", + !Join [ + "-", + [ + !Ref AWS::StackName, + !Select [ + 4, + !Split ["-", !Select [2, !Split ["/", !Ref AWS::StackId]]], + ], + ], + ], + ], + ] + Description: !Sub 'API endpoint for the "Miro Terms Modal app". It handles requests to read/write on the DynamoDB table "${MiroBannerTermsAcceptersTable}"' + StageName: Prod + DefinitionBody: + swagger: "2.0" + info: + title: "MiroBannerTermsAPI" + paths: + /w: + post: + x-amazon-apigateway-integration: + uri: !Sub arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${MiroBannerTermsWriteFunction.Arn}/invocations + passthroughBehavior: "when_no_match" + httpMethod: POST + type: aws_proxy + responses: {} + security: + - sigv4: [] + options: + summary: CORS support + description: | + Enable CORS by returning correct headers + consumes: + - application/json + produces: + - application/json + tags: + - CORS + x-amazon-apigateway-integration: + type: mock + requestTemplates: + application/json: | + { + 'statusCode' : 200 + } + responses: + "default": + statusCode: "200" + responseParameters: + method.response.header.Access-Control-Allow-Headers: "'Content-Type,X-Amz-Date,Authorization,X-Api-Key,Cache-Control,Pragma'" + method.response.header.Access-Control-Allow-Methods: "'OPTIONS,POST'" + method.response.header.Access-Control-Allow-Origin: !Join + - "" + - - "'" + - !If + - IsNotUSEast1 + - Fn::Sub: "https://${MiroTermsBannerFrontend}.s3.${AWS::Region}.amazonaws.com" + - Fn::Sub: "https://${MiroTermsBannerFrontend}.s3.amazonaws.com" + - "'" + responseTemplates: + application/json: | + {} + responses: + "200": + description: Default response for CORS method + headers: + Access-Control-Allow-Headers: + type: "string" + Access-Control-Allow-Methods: + type: "string" + Access-Control-Allow-Origin: + type: "string" + /q: + get: + x-amazon-apigateway-integration: + uri: !Sub arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${MiroBannerTermsReadFunction.Arn}/invocations + passthroughBehavior: "when_no_match" + httpMethod: POST + type: aws_proxy + responses: {} + security: + - sigv4: [] + options: + summary: CORS support + description: | + Enable CORS by returning correct headers + consumes: + - application/json + produces: + - application/json + tags: + - CORS + x-amazon-apigateway-integration: + type: mock + requestTemplates: + application/json: | + { + 'statusCode' : 200 + } + responses: + "default": + statusCode: "200" + responseParameters: + method.response.header.Access-Control-Allow-Headers: "'Content-Type,X-Amz-Date,Authorization,X-Api-Key,Cache-Control,Pragma'" + method.response.header.Access-Control-Allow-Methods: "'OPTIONS,GET'" + method.response.header.Access-Control-Allow-Origin: !Join + - "" + - - "'" + - !If + - IsNotUSEast1 + - Fn::Sub: "https://${MiroTermsBannerFrontend}.s3.${AWS::Region}.amazonaws.com" + - Fn::Sub: "https://${MiroTermsBannerFrontend}.s3.amazonaws.com" + - "'" + responseTemplates: + application/json: | + {} + responses: + "200": + description: Default response for CORS method + headers: + Access-Control-Allow-Headers: + type: "string" + Access-Control-Allow-Methods: + type: "string" + Access-Control-Allow-Origin: + type: "string" + + ## "Read" Lambda Function Invoke Permission + MiroBannerTermsApiInvokePermissionRead: + Type: "AWS::Lambda::Permission" + Properties: + Action: "lambda:InvokeFunction" + FunctionName: !GetAtt MiroBannerTermsReadFunction.Arn + Principal: "apigateway.amazonaws.com" + SourceArn: !Sub "arn:aws:execute-api:${AWS::Region}:${AWS::AccountId}:${MiroBannerTermsAPI}/*/*/*" + + ## "Write" Lambda Function Invoke Permission + MiroBannerTermsApiInvokePermissionWrite: + Type: "AWS::Lambda::Permission" + Properties: + Action: "lambda:InvokeFunction" + FunctionName: !GetAtt MiroBannerTermsWriteFunction.Arn + Principal: "apigateway.amazonaws.com" + SourceArn: !Sub "arn:aws:execute-api:${AWS::Region}:${AWS::AccountId}:${MiroBannerTermsAPI}/*/*/*" + +## Take a note of the outputs for deploying the workflow templates in this sample application +Outputs: + S3BucketBaseUrl: + Description: "Base URL of the S3 bucket where the web assets of the Miro app will be hosted" + Value: !If + - IsNotUSEast1 + - Fn::Sub: "https://${MiroTermsBannerFrontend}.s3.${AWS::Region}.amazonaws.com" + - Fn::Sub: "https://${MiroTermsBannerFrontend}.s3.amazonaws.com" + ApiBaseURL: + Description: "Base URL of HTTP API endpoint to read and write on the MiroBannerTermsAcceptersTable database" + Value: !Sub "https://${MiroBannerTermsAPI}.execute-api.${AWS::Region}.amazonaws.com" + DynamoDBTableName: + Description: "Name of the DynamoDB table that captures users who have accepted the terms banner in Miro" + Value: !Ref MiroBannerTermsAcceptersTable + S3BucketName: + Description: "Name of the S3 bucket where the web assets of the Miro app will be hosted (app.html, modal.html and variables.js)" + Value: !Ref MiroTermsBannerFrontend + +## Condition to adjust URLs based on region (the Default region "us-eat-1" is not added to URLs. For other regions the region is part of the URLs) +Conditions: + IsNotUSEast1: !Not [!Equals [!Ref "AWS::Region", "us-east-1"]] diff --git a/examples/terms-modal-banner-dynamodb/webassets/app.html b/examples/terms-modal-banner-dynamodb/webassets/app.html new file mode 100644 index 000000000..964ffd938 --- /dev/null +++ b/examples/terms-modal-banner-dynamodb/webassets/app.html @@ -0,0 +1,128 @@ + + + + + + + + + + + + diff --git a/examples/terms-modal-banner-dynamodb/webassets/modal.html b/examples/terms-modal-banner-dynamodb/webassets/modal.html new file mode 100644 index 000000000..32028ba7d --- /dev/null +++ b/examples/terms-modal-banner-dynamodb/webassets/modal.html @@ -0,0 +1,192 @@ + + + + + + + + + + +
+
+
+ +
+ To use Company Inc.'s Miro boards, please accept the + Usage Policy.
+ Please reach out to your IT administrator for more information on + the security requirements for using Company Inc.'s Miro boards. +
+
+ + + +
+
+
+
+ + + + diff --git a/examples/terms-modal-banner-dynamodb/webassets/variables.js b/examples/terms-modal-banner-dynamodb/webassets/variables.js new file mode 100644 index 000000000..8367f04cc --- /dev/null +++ b/examples/terms-modal-banner-dynamodb/webassets/variables.js @@ -0,0 +1,13 @@ +/* variables.js */ +/* eslint-disable no-unused-vars */ + +var MODAL_URL = 'replace with your "modal.html" URL from AWS S3'; // keep the single quotes around the value (e.g. 'https://miro-terms-banner-021ba44a2fc7.s3.eu-central-1.amazonaws.com/webassets/modal.html';) + +var API_ENDPOINT_BASE_URL = + 'replace with the value of "ApiBaseURL" from your AWS SAM CLI Output'; // keep the single quotes around the value (e.g. 'https://e4g624kyue.execute-api.eu-central-1.amazonaws.com';) + +var SECONDS_TO_WAIT = 3; // Enter value as number (not string) - Enter value as number (not string) - This is the interval in seconds the app will check if the current user has accepted the terms modal. With the default value (3) the app will check every 3 seconds if the user has accepted the modal until the terms modal has been successfully accepted + +var MODAL_WITH = 590; // Enter value as number (not string) - Width of the modal pop-up in pixels - Adjust as desired + +var MODAL_HEIGHT = 300; // Enter value as number (not string) - Height of the modal pop-up in pixels - Adjusted as desired diff --git a/examples/terms-modal-banner-dynamodb/writeApp/app.js b/examples/terms-modal-banner-dynamodb/writeApp/app.js new file mode 100644 index 000000000..01835d981 --- /dev/null +++ b/examples/terms-modal-banner-dynamodb/writeApp/app.js @@ -0,0 +1,70 @@ +/* Example of expected payload for the POST request: { "id": "Miro_User_ID" } */ + +const AWS = require("aws-sdk"); + +exports.handler = async (event) => { + const dynamoDB = new AWS.DynamoDB.DocumentClient(); + const tableName = process.env.TABLE_NAME; + const apiPayload = JSON.parse(event.body); + + const onlyLettersAndNumbers = function (str) { + return /^[A-Za-z0-9]*$/.test(str); + }; + + const responseHeaders = { + "Access-Control-Allow-Headers": "Content-Type,Accept,Cache-Control,Pragma", + "Access-Control-Allow-Origin": "*", // Replace wildcard (*) with your S3 bucket base URL (visible in your AWS SAML CLI Outputs) - See step 2.13 of the PDF guide https://drive.google.com/file/d/13fdsfiTGCBRWSmAv_7BuMBsWfg4_OWlO/view?usp=sharing + "Access-Control-Allow-Methods": "OPTIONS,POST", // Allow only POST request + "Content-Type": "application/json", + }; + + if (Object.getOwnPropertyDescriptor(apiPayload, "id")) { + const userId = apiPayload.id.toString(); + const isValidUserId = onlyLettersAndNumbers(userId); + + if (!isValidUserId || !userId) { + /* Returning a 409 error if the value of the "id" parameter posted contains characters other than a string with only letters and numbers */ + return { + statusCode: 409, + headers: responseHeaders, + body: JSON.stringify({ error: "Invalid Data" }), + }; + } + + const params = { + TableName: tableName, + Key: { id: userId }, + UpdateExpression: "set hasAcceptedTerms = :hasAcceptedTerms", + ExpressionAttributeValues: { + ":hasAcceptedTerms": "yes", + }, + ReturnValues: "UPDATED_NEW", + }; + + try { + await dynamoDB.update(params).promise(); + return { + statusCode: 200, + //body: JSON.stringify(result.Attributes) + headers: responseHeaders, + body: JSON.stringify({ result: "success" }), + }; + } catch (error) { + console.error("Error updating item:", error); + + /* Returning a 500 error for any other errors */ + return { + statusCode: 500, + headers: responseHeaders, + body: JSON.stringify({ error: "Internal Server Error" }), + }; + } + } else { + /* Returning a 500 error if the "id" parameter was not passed in the posted payload */ + return { + statusCode: 415, + headers: responseHeaders, + body: JSON.stringify({ error: "Invalid Request" }), + }; + } +}; diff --git a/examples/terms-modal-banner-dynamodb/writeApp/package.json b/examples/terms-modal-banner-dynamodb/writeApp/package.json new file mode 100644 index 000000000..77637e6da --- /dev/null +++ b/examples/terms-modal-banner-dynamodb/writeApp/package.json @@ -0,0 +1,15 @@ +{ + "name": "MiroBannerTermsAcceptersWriteApp", + "version": "1.0.0", + "description": "", + "main": "index.js", + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "keywords": [], + "author": "Luis Colman, Miro Platform Architecture", + "license": "MIT-0", + "devDependencies": { + "aws-sdk": "^2.749.0" + } +}