├── source ├── web_site │ ├── fonts │ │ ├── FontAwesome.otf │ │ ├── fontawesome-webfont.eot │ │ ├── fontawesome-webfont.ttf │ │ ├── fontawesome-webfont.woff │ │ └── fontawesome-webfont.woff2 │ ├── js │ │ ├── dashboard-use.js │ │ ├── bootstrap.min.js │ │ ├── dash.js │ │ └── amazon-cognito-identity.min.js │ ├── help.html │ └── dash.html ├── helper │ ├── package.json │ ├── lib │ │ ├── metrics-helper.js │ │ ├── kinesisapp-helper.js │ │ └── website-helper.js │ └── index.js └── update_ddb_from_stream │ └── update_ddb_from_stream.py ├── .github └── PULL_REQUEST_TEMPLATE.md ├── .gitignore ├── CODE_OF_CONDUCT.md ├── deployment ├── run-unit-tests.sh ├── manifest-generator │ ├── package.json │ ├── package-lock.json │ └── app.js └── build-s3-dist.sh ├── NOTICE.txt ├── CHANGELOG.md ├── README.md ├── CONTRIBUTING.md └── LICENSE.txt /source/web_site/fonts/FontAwesome.otf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aws-solutions/real-time-insights-account-activity/master/source/web_site/fonts/FontAwesome.otf -------------------------------------------------------------------------------- /source/web_site/fonts/fontawesome-webfont.eot: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aws-solutions/real-time-insights-account-activity/master/source/web_site/fonts/fontawesome-webfont.eot -------------------------------------------------------------------------------- /source/web_site/fonts/fontawesome-webfont.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aws-solutions/real-time-insights-account-activity/master/source/web_site/fonts/fontawesome-webfont.ttf -------------------------------------------------------------------------------- /source/web_site/fonts/fontawesome-webfont.woff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aws-solutions/real-time-insights-account-activity/master/source/web_site/fonts/fontawesome-webfont.woff -------------------------------------------------------------------------------- /source/web_site/fonts/fontawesome-webfont.woff2: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aws-solutions/real-time-insights-account-activity/master/source/web_site/fonts/fontawesome-webfont.woff2 -------------------------------------------------------------------------------- /.github/PULL_REQUEST_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | *Issue #, if available:* 2 | 3 | *Description of changes:* 4 | 5 | 6 | By submitting this pull request, I confirm that my contribution is made under the terms of the Apache 2.0 license. 7 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Compiled output 2 | **/dist 3 | **/.zip 4 | **/global-s3-assets 5 | **/regional-s3-assets 6 | **/open-source 7 | 8 | # Dependencies 9 | node_modules/ 10 | package-lock.json 11 | 12 | # Misc 13 | **/.DS_Store -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | ## Code of Conduct 2 | This project has adopted the [Amazon Open Source Code of Conduct](https://aws.github.io/code-of-conduct). 3 | For more information see the [Code of Conduct FAQ](https://aws.github.io/code-of-conduct-faq) or contact 4 | opensource-codeofconduct@amazon.com with any additional questions or comments. -------------------------------------------------------------------------------- /deployment/run-unit-tests.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # This script should be run from the repo's deployment directory 4 | # cd deployment 5 | # ./run-unit-tests.sh 6 | 7 | # Run unit tests 8 | echo "Running unit tests" 9 | echo "cd ../source" 10 | cd ../source 11 | echo "No unit tests to run, so sad ..." 12 | echo "Completed unit tests" 13 | -------------------------------------------------------------------------------- /deployment/manifest-generator/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "manifest-generator", 3 | "version": "0.0.0", 4 | "private": true, 5 | "description": "Helper utility to create data lake site manifest for deployment", 6 | "main": "app.js", 7 | "author": { 8 | "name": "aws-solutions-builder" 9 | }, 10 | "dependencies": { 11 | "minimist": "*" 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /deployment/manifest-generator/package-lock.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "manifest-generator", 3 | "version": "0.0.0", 4 | "lockfileVersion": 1, 5 | "requires": true, 6 | "dependencies": { 7 | "minimist": { 8 | "version": "1.2.5", 9 | "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.5.tgz", 10 | "integrity": "sha512-FM9nNUYrRBAELZQT3xeZQ7fmMOBg6nWNmJKTcgsJeaLstP/UODVpGsr5OhXhhXg6f+qtJ8uiZ+PUxkDWcgIXLw==" 11 | } 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /source/web_site/js/dashboard-use.js: -------------------------------------------------------------------------------- 1 | $(document).ready(function() { 2 | if(_dashboard_usage === 'Yes') { 3 | $.ajax({ 4 | url: 'https://metrics.awssolutionsbuilder.com/page', 5 | type: 'POST', 6 | crossDomain: true, 7 | data: JSON.stringify(_hit_data), 8 | dataType: 'json', 9 | headers: { 10 | 'Content-Type': 'application/json' 11 | }, 12 | success: function(data) { 13 | console.log('Successfully sent page hit to metrics'); 14 | console.log(data); 15 | }, 16 | error: function(xhr, ajaxOptions, thrownError) { 17 | console.log('Error sending page hit to metrics'); 18 | } 19 | }); 20 | } else { 21 | console.log('Dashboard use metrics disabled'); 22 | } 23 | }); 24 | -------------------------------------------------------------------------------- /NOTICE.txt: -------------------------------------------------------------------------------- 1 | Real Time Insights into AWS Account Activity 2 | Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. 3 | 4 | ********************** 5 | THIRD PARTY COMPONENTS 6 | ********************** 7 | This software includes third party software subject to the following copyrights: 8 | 9 | AWS SDK under the Apache License Version 2.0 10 | underscore under the Massachusetts Institute of Technology (MIT) license 11 | moment under the Massachusetts Institute of Technology (MIT) license 12 | password-generator under the Massachusetts Institute of Technology (MIT) license 13 | node-uuid under the Massachusetts Institute of Technology (MIT) license 14 | bootstrap under the Massachusetts Institute of Technology (MIT) license 15 | chart under the Massachusetts Institute of Technology (MIT) license 16 | jquery under the Massachusetts Institute of Technology (MIT) license -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Change Log 2 | 3 | All notable changes to this project will be documented in this file. 4 | 5 | The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), 6 | and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). 7 | 8 | ## [1.1.2] - 2021-05-31 9 | 10 | ### Added 11 | 12 | - Added Encryption support for Kinesis Firehose delivery stream 13 | - Added Point In Time Recovery support for DynamoDB Table 14 | - Added cfn_nag suppress rules for Lambda VPC deployment and Reserved Concurrency 15 | 16 | ### Changed 17 | 18 | - Removed unused dev dependency Grunt 19 | 20 | ## [1.1.1] - 2020-03-30 21 | 22 | ### Changed 23 | 24 | - Updated node runtime to version 12 25 | 26 | ## [1.1] - 2019-08-29 27 | 28 | ### Added 29 | 30 | - CHANGELOG file 31 | - Default encryption to S3 buckets via CloudFormation (instead of custom resources) 32 | 33 | ### Changed 34 | 35 | - Updated node runtime to version 8 36 | - Updated python runtime to version 3 37 | -------------------------------------------------------------------------------- /source/helper/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "custom-resource-helper", 3 | "description": "Solutions Builder custom resource helper Lambda function", 4 | "main": "index.js", 5 | "author": { 6 | "name": "aws-solutions-builder" 7 | }, 8 | "version": "0.0.1", 9 | "private": "true", 10 | "dependencies": { 11 | "moment": "*", 12 | "underscore": "*", 13 | "password-generator": "*", 14 | "node-uuid": "*" 15 | }, 16 | "devDependencies": { 17 | "aws-sdk": "*", 18 | "chai": "*", 19 | "sinon": "*", 20 | "sinon-chai": "*", 21 | "mocha": "*", 22 | "aws-sdk-mock": "*", 23 | "npm-run-all": "*" 24 | }, 25 | "scripts": { 26 | "pretest": "npm install", 27 | "test": "mocha lib/*.spec.js", 28 | "build-init": "rm -rf dist && rm -f archive.zip && mkdir dist && mkdir dist/lib", 29 | "build:copy": "cp index.js dist/ && cp -r lib/*.js dist/lib", 30 | "build:install": "cp package.json dist/ && cd dist && npm install --production", 31 | "build": "npm-run-all -s build-init build:copy build:install", 32 | "zip": "cd dist && zip -rq custom-resource-helper.zip ." 33 | }, 34 | "bundledDependencies": [ 35 | "moment", 36 | "underscore", 37 | "password-generator", 38 | "node-uuid" 39 | ] 40 | } 41 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Note: As of 09/08/2022, Real-Time Insights on AWS Account Activity has been deprecated. The code is no longer being maintained. 2 | 3 | # AWS Real-Time Insights into AWS Account Activity with Kinesis Analytics 4 | 5 | This AWS Solution leverages AWS CloudTrail, AWS Kinesis Analytics, Amazon DynamoDB, AWS Lambda, Amazon S3, Amazon Cognito, and Chart.js to provide real-time insights into AWS account activity. 6 | 7 | ## OS/Python Environment Setup 8 | 9 | ```bash 10 | sudo apt-get update 11 | sudo apt-get install zip sed wget -y 12 | sudo pip install --upgrade pip 13 | sudo pip install --upgrade setuptools 14 | sudo pip install --upgrade virtualenv 15 | ``` 16 | 17 | ## Building Lambda Package 18 | 19 | ```bash 20 | export DIST_OUTPUT_BUCKET=my-bucket-name # bucket where customized code will reside 21 | export VERSION=my-version # version number for the customized code 22 | cd deployment 23 | ./build-s3-dist.sh $DIST_OUTPUT_BUCKET real-time-insights-account-activity $VERSION 24 | ``` 25 | 26 | source-bucket-base-name should be the base name for the S3 bucket location where the template will source the Lambda code from. 27 | The template will append '-[region_name]' to this value. 28 | For example: ./build-s3-dist.sh solutions 29 | The template will then expect the source code to be located in the solutions-[region_name] bucket 30 | 31 | ## CF template and Lambda function 32 | 33 | Located in deployment/dist 34 | 35 | --- 36 | 37 | Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. 38 | 39 | Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at 40 | 41 | http://www.apache.org/licenses/LICENSE-2.0 42 | 43 | or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. 44 | 45 | _This solution collects anonymous operational metrics to help AWS improve the quality of features of the solution.For more information, including how to disable this capability, please see the [implementation guide](https://docs.aws.amazon.com/solutions/latest/real-time-insights-account-activity/appendix-c.html)._ 46 | -------------------------------------------------------------------------------- /source/web_site/help.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | CloudTrail Analytics Dashboard Help 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 |
29 |
30 |
31 | 32 |
33 | 38 | AWS CloudTrail Dashboard 39 |
40 |
41 | 42 | 43 |
44 |
45 |

Overview of the AWS CloudTrail Analytics Dashboard

46 |

This dashboard and its associated solution provide a mechanism for collecting, analyzing, and displaying AWS account activity in real time. The solution logs events for your AWS account using AWS CloudTrail which include actions taken through the AWS Management Console, AWS SDKs, command line tools, and other AWS services. That data is captured and analyzed by Amazon Kinesis to produce important metrics in real time and persist them to DynamoDB. The processed data is visualized using a custom dashboard you see below using a website hosted on Amazon S3. All raw and processed data is archived in Amazon S3.

47 | 48 |

Many events are processed in real time but some events take up to 15 minutes to arrive from AWS CloudTrail. The dashboard loads new data from DynamoDB into line graphs every 10 seconds and bar charts every 1 minute. The past 15 minutes of data are updated every 1 minute to capture events that arrive late from AWS CloudTrail.

49 |

Use of Amazon Cognito

50 |

This solution uses Amazon Cognito for authentication. The solution asks for a user name and email address when it is launched. Durning deployoment, an Amazon Cognito User Pool and user are created for you. The user ID and temporary password are emailed to the provided email address. Additional users can be added to the dashboard by using the Amazon Cognito console and adding additional users. 51 |

Back to dashboard 52 |

53 |
54 |
55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | -------------------------------------------------------------------------------- /source/helper/lib/metrics-helper.js: -------------------------------------------------------------------------------- 1 | /********************************************************************************************************************* 2 | * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * 3 | * * 4 | * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * 5 | * with the License. A copy of the License is located at * 6 | * * 7 | * http://www.apache.org/licenses/LICENSE-2.0 * 8 | * * 9 | * or in the 'license' file accompanying this file. This file is distributed on an 'AS IS' BASIS, WITHOUT WARRANTIES * 10 | * OR CONDITIONS OF ANY KIND, express or implied. See the License for the specific language governing permissions * 11 | * and limitations under the License. * 12 | *********************************************************************************************************************/ 13 | 14 | /** 15 | * @author Solution Builders 16 | */ 17 | 18 | 'use strict'; 19 | 20 | let moment = require('moment'); 21 | let https = require('https'); 22 | 23 | /** 24 | * Helper function to send anonymous data from cfn custom resource. 25 | * 26 | * @class metricsHelper 27 | */ 28 | let metricsHelper = (function() { 29 | 30 | /** 31 | * @class metricsHelper 32 | * @constructor 33 | */ 34 | let metricsHelper = function() {}; 35 | 36 | /** 37 | * Sends opt-in, anonymous metric. 38 | * @param {json} metric - metric to send to opt-in, anonymous collection. 39 | * @param {sendAnonymousMetric~requestCallback} cb - The callback that handles the response. 40 | */ 41 | metricsHelper.prototype.sendAnonymousMetric = function(metric, cb) { 42 | 43 | let _options = { 44 | hostname: 'metrics.awssolutionsbuilder.com', 45 | port: 443, 46 | path: '/generic', 47 | method: 'POST', 48 | headers: { 49 | 'Content-Type': 'application/json' 50 | } 51 | }; 52 | 53 | let request = https.request(_options, function(response) { 54 | // data is streamed in chunks from the server 55 | // so we have to handle the "data" event 56 | let buffer; 57 | let data; 58 | let route; 59 | 60 | response.on('data', function(chunk) { 61 | buffer += chunk; 62 | }); 63 | 64 | response.on('end', function(err) { 65 | data = buffer; 66 | cb(null, data); 67 | }); 68 | }); 69 | 70 | if (metric) { 71 | request.write(JSON.stringify(metric)); 72 | } 73 | 74 | request.end(); 75 | 76 | request.on('error', (e) => { 77 | console.error(e); 78 | cb(['Error occurred when sending metric request.', JSON.stringify(_payload)].join(' '), null); 79 | }); 80 | }; 81 | 82 | return metricsHelper; 83 | 84 | })(); 85 | 86 | module.exports = metricsHelper; 87 | -------------------------------------------------------------------------------- /deployment/manifest-generator/app.js: -------------------------------------------------------------------------------- 1 | /********************************************************************************************************************* 2 | * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * 3 | * * 4 | * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * 5 | * with the License. A copy of the License is located at * 6 | * * 7 | * http://www.apache.org/licenses/LICENSE-2.0 * 8 | * * 9 | * or in the 'license' file accompanying this file. This file is distributed on an 'AS IS' BASIS, WITHOUT WARRANTIES * 10 | * OR CONDITIONS OF ANY KIND, express or implied. See the License for the specific language governing permissions * 11 | * and limitations under the License. * 12 | *********************************************************************************************************************/ 13 | 14 | /** 15 | * @author Solution Builders 16 | */ 17 | 18 | 'use strict'; 19 | 20 | const fs = require('fs'); 21 | const path = require('path'); 22 | const args = require('minimist')(process.argv.slice(2)); 23 | 24 | let getFileList = function(path) { 25 | let fileInfo; 26 | let filesFound; 27 | let fileList = []; 28 | 29 | filesFound = fs.readdirSync(path); 30 | for (let i = 0; i < filesFound.length; i++) { 31 | fileInfo = fs.lstatSync([path, filesFound[i]].join('/')); 32 | if (fileInfo.isFile()) { 33 | fileList.push(filesFound[i]); 34 | } 35 | 36 | if (fileInfo.isDirectory()) { 37 | console.log([path, filesFound[i]].join('/')); 38 | } 39 | } 40 | 41 | return fileList; 42 | }; 43 | 44 | // List all files in a directory in Node.js recursively in a synchronous fashion 45 | let walkSync = function(dir, filelist) { 46 | // let filelist = []; //getFileList('./temp/site'); 47 | let files = fs.readdirSync(dir); 48 | filelist = filelist || []; 49 | files.forEach(function(file) { 50 | if (fs.statSync(path.join(dir, file)).isDirectory()) { 51 | filelist = walkSync(path.join(dir, file), filelist); 52 | } else { 53 | filelist.push(path.join(dir, file)); 54 | } 55 | }); 56 | 57 | return filelist; 58 | }; 59 | 60 | let _filelist = []; 61 | let _manifest = { 62 | files: [] 63 | }; 64 | 65 | if (!args.hasOwnProperty('target')) { 66 | console.log('--target parameter missing. This should be the target directory containing content for the manifest.'); 67 | process.exit(1); 68 | } 69 | 70 | if (!args.hasOwnProperty('output')) { 71 | console.log('--ouput parameter missing. This should be the out directory where the manifest file will be generated.'); 72 | process.exit(1); 73 | } 74 | 75 | console.log(`Generating a manifest file ${args.output} for directory ${args.target}`); 76 | 77 | walkSync(args.target, _filelist); 78 | 79 | for (let i = 0; i < _filelist.length; i++) { 80 | _manifest.files.push(_filelist[i].replace(`${args.target}/`, '')); 81 | }; 82 | 83 | fs.writeFileSync(args.output, JSON.stringify(_manifest, null, 4)); 84 | console.log(`Manifest file ${args.output} generated.`); -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing Guidelines 2 | 3 | Thank you for your interest in contributing to our project. Whether it's a bug report, new feature, correction, or additional 4 | documentation, we greatly value feedback and contributions from our community. 5 | 6 | Please read through this document before submitting any issues or pull requests to ensure we have all the necessary 7 | information to effectively respond to your bug report or contribution. 8 | 9 | 10 | ## Reporting Bugs/Feature Requests 11 | 12 | We welcome you to use the GitHub issue tracker to report bugs or suggest features. 13 | 14 | When filing an issue, please check [existing open](https://github.com/awslabs/real-time-iot-device-monitoring-with-kinesis/issues), or [recently closed](https://github.com/awslabs/real-time-iot-device-monitoring-with-kinesis/issues?utf8=%E2%9C%93&q=is%3Aissue%20is%3Aclosed%20), issues to make sure somebody else hasn't already 15 | reported the issue. Please try to include as much information as you can. Details like these are incredibly useful: 16 | 17 | * A reproducible test case or series of steps 18 | * The version of our code being used 19 | * Any modifications you've made relevant to the bug 20 | * Anything unusual about your environment or deployment 21 | 22 | 23 | ## Contributing via Pull Requests 24 | Contributions via pull requests are much appreciated. Before sending us a pull request, please ensure that: 25 | 26 | 1. You are working against the latest source on the *master* branch. 27 | 2. You check existing open, and recently merged, pull requests to make sure someone else hasn't addressed the problem already. 28 | 3. You open an issue to discuss any significant work - we would hate for your time to be wasted. 29 | 30 | To send us a pull request, please: 31 | 32 | 1. Fork the repository. 33 | 2. Modify the source; please focus on the specific change you are contributing. If you also reformat all the code, it will be hard for us to focus on your change. 34 | 3. Ensure local tests pass. 35 | 4. Commit to your fork using clear commit messages. 36 | 5. Send us a pull request, answering any default questions in the pull request interface. 37 | 6. Pay attention to any automated CI failures reported in the pull request, and stay involved in the conversation. 38 | 39 | GitHub provides additional document on [forking a repository](https://help.github.com/articles/fork-a-repo/) and 40 | [creating a pull request](https://help.github.com/articles/creating-a-pull-request/). 41 | 42 | 43 | ## Finding contributions to work on 44 | Looking at the existing issues is a great way to find something to contribute on. As our projects, by default, use the default GitHub issue labels ((enhancement/bug/duplicate/help wanted/invalid/question/wontfix), looking at any ['help wanted'](https://github.com/awslabs/real-time-iot-device-monitoring-with-kinesis/labels/help%20wanted) issues is a great place to start. 45 | 46 | 47 | ## Code of Conduct 48 | This project has adopted the [Amazon Open Source Code of Conduct](https://aws.github.io/code-of-conduct). 49 | For more information see the [Code of Conduct FAQ](https://aws.github.io/code-of-conduct-faq) or contact 50 | opensource-codeofconduct@amazon.com with any additional questions or comments. 51 | 52 | 53 | ## Security issue notifications 54 | If you discover a potential security issue in this project we ask that you notify AWS/Amazon Security via our [vulnerability reporting page](http://aws.amazon.com/security/vulnerability-reporting/). Please do **not** create a public github issue. 55 | 56 | 57 | ## Licensing 58 | 59 | See the [LICENSE](https://github.com/awslabs/real-time-iot-device-monitoring-with-kinesis/blob/master/LICENSE) file for our project's licensing. We will ask you to confirm the licensing of your contribution. 60 | 61 | We may ask you to sign a [Contributor License Agreement (CLA)](http://en.wikipedia.org/wiki/Contributor_License_Agreement) for larger changes. -------------------------------------------------------------------------------- /deployment/build-s3-dist.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # 3 | # This assumes all of the OS-level configuration has been completed and git repo has already been cloned 4 | # 5 | # This script should be run from the repo's deployment directory 6 | # cd deployment 7 | # ./build-s3-dist.sh source-bucket-base-name trademarked-solution-name version-code 8 | # 9 | # Paramenters: 10 | # - source-bucket-base-name: Name for the S3 bucket location where the template will source the Lambda 11 | # code from. The template will append '-[region_name]' to this bucket name. 12 | # For example: ./build-s3-dist.sh solutions my-solution v1.0.0 13 | # The template will then expect the source code to be located in the solutions-[region_name] bucket 14 | # 15 | # - trademarked-solution-name: name of the solution for consistency 16 | # 17 | # - version-code: version of the package 18 | 19 | # Check to see if input has been provided: 20 | if [ -z "$1" ] || [ -z "$2" ] || [ -z "$3" ]; then 21 | echo "Please provide the base source bucket name (where the lambda code will eventually reside), trademark approved solution name and version." 22 | echo "For example: ./build-s3-dist.sh solutions trademarked-solution-name v1.0.0" 23 | exit 1 24 | fi 25 | 26 | # Get reference for all important folders 27 | template_dir="$PWD" 28 | template_dist_dir="$template_dir/global-s3-assets" 29 | build_dist_dir="$template_dir/regional-s3-assets" 30 | source_dir="$template_dir/../source" 31 | 32 | echo "------------------------------------------------------------------------------" 33 | echo "[Init] Clean old dist, node_modules and bower_components folders" 34 | echo "------------------------------------------------------------------------------" 35 | rm -rf $template_dist_dir 36 | mkdir -p $template_dist_dir 37 | rm -rf $build_dist_dir 38 | mkdir -p $build_dist_dir 39 | 40 | echo "------------------------------------------------------------------------------" 41 | echo "[Packing] Templates" 42 | echo "------------------------------------------------------------------------------" 43 | cp $template_dir/real-time-insights-account-activity.template $template_dist_dir/ 44 | 45 | replace="s/%%BUCKET_NAME%%/$1/g" 46 | sed -i '' -e $replace $template_dist_dir/real-time-insights-account-activity.template 47 | replace="s/%%SOLUTION_NAME%%/$2/g" 48 | sed -i '' -e $replace $template_dist_dir/real-time-insights-account-activity.template 49 | replace="s/%%VERSION%%/$3/g" 50 | sed -i '' -e $replace $template_dist_dir/real-time-insights-account-activity.template 51 | 52 | echo "------------------------------------------------------------------------------" 53 | echo "[Build] Custom resource helper Lambda function" 54 | echo "------------------------------------------------------------------------------" 55 | cd $source_dir/helper 56 | npm install 57 | npm run build 58 | npm run zip 59 | cp ./dist/custom-resource-helper.zip $build_dist_dir/custom-resource-helper.zip 60 | rm -rf dist 61 | rm -rf node_modules 62 | 63 | echo "------------------------------------------------------------------------------" 64 | echo "[Build] Lambda function to update DDB from Kinesis stream" 65 | echo "------------------------------------------------------------------------------" 66 | cd $source_dir/update_ddb_from_stream 67 | rm -rf ./dist && mkdir ./dist 68 | cp update_ddb_from_stream.py ./dist 69 | cd dist 70 | zip -r update_ddb_from_stream.zip . 71 | cp ./update_ddb_from_stream.zip $build_dist_dir/update_ddb_from_stream.zip 72 | 73 | echo "------------------------------------------------------------------------------" 74 | echo "[Build] Copying web site content" 75 | echo "------------------------------------------------------------------------------" 76 | cp -r $source_dir/web_site $build_dist_dir/ 77 | 78 | echo "------------------------------------------------------------------------------" 79 | echo "[Build] Generating web site manifest" 80 | echo "------------------------------------------------------------------------------" 81 | cd "$template_dir/manifest-generator" || exit 82 | npm install 83 | node app.js --target "$build_dist_dir/web_site" --output "$build_dist_dir/web-site-manifest.json" 84 | 85 | echo "------------------------------------------------------------------------------" 86 | echo "S3 Packaging Complete" 87 | echo "------------------------------------------------------------------------------" 88 | -------------------------------------------------------------------------------- /source/helper/lib/kinesisapp-helper.js: -------------------------------------------------------------------------------- 1 | /********************************************************************************************************************* 2 | * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * 3 | * * 4 | * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * 5 | * with the License. A copy of the License is located at * 6 | * * 7 | * http://www.apache.org/licenses/LICENSE-2.0 * 8 | * * 9 | * or in the 'license' file accompanying this file. This file is distributed on an 'AS IS' BASIS, WITHOUT WARRANTIES * 10 | * OR CONDITIONS OF ANY KIND, express or implied. See the License for the specific language governing permissions * 11 | * and limitations under the License. * 12 | *********************************************************************************************************************/ 13 | 14 | /** 15 | * @author Solution Builders 16 | */ 17 | 18 | 'use strict'; 19 | 20 | let AWS = require('aws-sdk'); 21 | let ka = new AWS.KinesisAnalytics(); 22 | 23 | /** 24 | * Helper function to turn on a Kinesis Analytics app cfn custom resource. 25 | * 26 | * @class bucketEncryptionHelper 27 | */ 28 | let kinesisAnalyticsAppHelper = (function() { 29 | 30 | /** 31 | * @class bucketEncryptionHelper 32 | * @constructor 33 | */ 34 | let kinesisAnalyticsAppHelper = function() {}; 35 | 36 | /** 37 | * Starts a Kinesis Data Analytics application. 38 | * @param {string} ApplicationName - Name of the Kinesis Data Analytics application. 39 | * @param {copyWebSiteAssets~requestCallback} cb - The callback that handles the response. 40 | */ 41 | kinesisAnalyticsAppHelper.prototype.startApplication = function(ApplicationName, cb) { 42 | console.log(['Looking up Kinesis Data Analytics application:', ApplicationName].join(' ')); 43 | var params = { 44 | ApplicationName: ApplicationName 45 | }; 46 | ka.describeApplication(params, function(err, app_description) { 47 | if (app_description == null) { 48 | console.log(['Could not find application:', ApplicationName].join(' ')); 49 | return cb(['Kinesis Data Analytics application,', ApplicationName, ', could not be found!'].join(' '), null); 50 | } 51 | console.log('app status: ',app_description.ApplicationDetail.ApplicationStatus); 52 | if (err) { 53 | console.log(['Failed to describe application:', err].join(' ')); 54 | return cb(err, null); 55 | } else { 56 | if (app_description.ApplicationDetail.ApplicationStatus === 'READY') { 57 | //Start App 58 | params = { 59 | ApplicationName: ApplicationName, 60 | InputConfigurations: [ 61 | { 62 | 'Id': '1.1', 63 | 'InputStartingPositionConfiguration': { 64 | 'InputStartingPosition': 'NOW' 65 | } 66 | } 67 | ] 68 | }; 69 | console.log("Starting application"); 70 | ka.startApplication(params, function(err, response) { 71 | if (err) { 72 | console.log(['Failed to start application', item.ApplicationName, ': ', err].join(' ')); 73 | return cb(err, null); 74 | } else { 75 | return cb(null, "SUCCESS"); 76 | } 77 | }); 78 | } else { 79 | return cb(['Kinesis Data Analytics Application was not in READY state (app status === ', app_description.ApplicationDetail.ApplicationStatus,')'].join(''), null); 80 | } 81 | } 82 | }); 83 | }; 84 | 85 | return kinesisAnalyticsAppHelper; 86 | 87 | })(); 88 | 89 | module.exports = kinesisAnalyticsAppHelper; 90 | -------------------------------------------------------------------------------- /source/helper/index.js: -------------------------------------------------------------------------------- 1 | /********************************************************************************************************************* 2 | * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * 3 | * * 4 | * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * 5 | * with the License. A copy of the License is located at * 6 | * * 7 | * http://www.apache.org/licenses/LICENSE-2.0 * 8 | * * 9 | * or in the 'license' file accompanying this file. This file is distributed on an 'AS IS' BASIS, WITHOUT WARRANTIES * 10 | * OR CONDITIONS OF ANY KIND, express or implied. See the License for the specific language governing permissions * 11 | * and limitations under the License. * 12 | *********************************************************************************************************************/ 13 | 14 | /** 15 | * @author Solution Builders 16 | */ 17 | 18 | 'use strict'; 19 | 20 | console.log('Loading function'); 21 | 22 | const AWS = require('aws-sdk'); 23 | const https = require('https'); 24 | const url = require('url'); 25 | const moment = require('moment'); 26 | const WebsiteHelper = require('./lib/website-helper.js'); 27 | const MetricsHelper = require('./lib/metrics-helper.js'); 28 | const KinesisAppHelper = require('./lib/kinesisapp-helper.js'); 29 | const UUID = require('node-uuid'); 30 | 31 | /** 32 | * Request handler. 33 | */ 34 | exports.handler = (event, context, callback) => { 35 | console.log('Received event:', JSON.stringify(event, null, 2)); 36 | 37 | let responseStatus = 'FAILED'; 38 | let responseData = {}; 39 | 40 | if (event.RequestType === 'Delete') { 41 | if (event.ResourceProperties.customAction === 'sendMetric') { 42 | responseStatus = 'SUCCESS'; 43 | 44 | let _metricsHelper = new MetricsHelper(); 45 | 46 | let _metric = { 47 | Solution: event.ResourceProperties.solutionId, 48 | UUID: event.ResourceProperties.UUID, 49 | TimeStamp: moment().utc().format('YYYY-MM-DD HH:mm:ss.S'), 50 | Data: { 51 | Version: event.ResourceProperties.version, 52 | RequestType: event.RequestType 53 | } 54 | }; 55 | 56 | _metricsHelper.sendAnonymousMetric(_metric, function(err, data) { 57 | if (err) { 58 | responseData = { 59 | Error: 'Sending metrics helper delete failed' 60 | }; 61 | console.log([responseData.Error, ':\n', err].join('')); 62 | } 63 | sendResponse(event, callback, context.logStreamName, 'SUCCESS'); 64 | }); 65 | } else { 66 | sendResponse(event, callback, context.logStreamName, 'SUCCESS'); 67 | } 68 | } 69 | 70 | if (event.RequestType === 'Create') { 71 | if (event.ResourceProperties.customAction === 'configureWebsite') { 72 | let _websiteHelper = new WebsiteHelper(); 73 | //BUGFIX removed hardcoded table names:: analyticsTable &\ ipTable 74 | _websiteHelper.copyWebSiteAssets(event.ResourceProperties.sourceS3Bucket, 75 | event.ResourceProperties.sourceS3key, event.ResourceProperties.sourceManifest, event.ResourceProperties.destS3Bucket, 76 | event.ResourceProperties.userPoolId, event.ResourceProperties.userPoolClientId, 77 | event.ResourceProperties.identityPoolId, event.ResourceProperties.region, 78 | event.ResourceProperties.UUID, event.ResourceProperties.anonymousData,event.ResourceProperties.analyticsTable, event.ResourceProperties.ipTable, 79 | function(err, data) { 80 | if (err) { 81 | responseData = { 82 | Error: 'Copy of website assets failed' 83 | }; 84 | console.log([responseData.Error, ':\n', err].join('')); 85 | } else { 86 | responseStatus = 'SUCCESS'; 87 | responseData = {}; 88 | } 89 | 90 | sendResponse(event, callback, context.logStreamName, responseStatus, responseData); 91 | }); 92 | 93 | } else if (event.ResourceProperties.customAction === 'startKinesisApplication') { 94 | let _kinesisAppHelper = new KinesisAppHelper(); 95 | 96 | _kinesisAppHelper.startApplication(event.ResourceProperties.ApplicationName, 97 | function(err, data) { 98 | if (err) { 99 | responseData = { 100 | Error: 'Starting kinesis application failed' 101 | }; 102 | console.log([responseData.Error, ':\n', err].join('')); 103 | } else { 104 | responseStatus = 'SUCCESS'; 105 | responseData = {}; 106 | } 107 | 108 | sendResponse(event, callback, context.logStreamName, responseStatus, responseData); 109 | }); 110 | 111 | } else if (event.ResourceProperties.customAction === 'createUuid') { 112 | responseStatus = 'SUCCESS'; 113 | responseData = { 114 | UUID: UUID.v4() 115 | }; 116 | sendResponse(event, callback, context.logStreamName, responseStatus, responseData); 117 | 118 | } else if (event.ResourceProperties.customAction === 'sendMetric') { 119 | let _metricsHelper = new MetricsHelper(); 120 | 121 | let _metric = { 122 | Solution: event.ResourceProperties.solutionId, 123 | UUID: event.ResourceProperties.UUID, 124 | TimeStamp: moment().utc().format('YYYY-MM-DD HH:mm:ss.S'), 125 | Data: { 126 | Version: event.ResourceProperties.version, 127 | SendAnonymousData: event.ResourceProperties.anonymousData, 128 | RequestType: event.RequestType 129 | } 130 | }; 131 | 132 | _metricsHelper.sendAnonymousMetric(_metric, function(err, data) { 133 | if (err) { 134 | responseData = { 135 | Error: 'Sending anonymous launch metric failed' 136 | }; 137 | console.log([responseData.Error, ':\n', err].join('')); 138 | } else { 139 | responseStatus = 'SUCCESS'; 140 | responseData = {}; 141 | } 142 | }); 143 | sendResponse(event, callback, context.logStreamName, 'SUCCESS'); 144 | } 145 | 146 | } 147 | 148 | }; 149 | 150 | /** 151 | * Sends a response to the pre-signed S3 URL 152 | */ 153 | let sendResponse = function(event, callback, logStreamName, responseStatus, responseData) { 154 | const responseBody = JSON.stringify({ 155 | Status: responseStatus, 156 | Reason: `See the details in CloudWatch Log Stream: ${logStreamName}`, 157 | PhysicalResourceId: logStreamName, 158 | StackId: event.StackId, 159 | RequestId: event.RequestId, 160 | LogicalResourceId: event.LogicalResourceId, 161 | Data: responseData, 162 | }); 163 | 164 | console.log('RESPONSE BODY:\n', responseBody); 165 | const parsedUrl = url.parse(event.ResponseURL); 166 | const options = { 167 | hostname: parsedUrl.hostname, 168 | port: 443, 169 | path: parsedUrl.path, 170 | method: 'PUT', 171 | headers: { 172 | 'Content-Type': '', 173 | 'Content-Length': responseBody.length, 174 | } 175 | }; 176 | 177 | const req = https.request(options, (res) => { 178 | console.log('STATUS:', res.statusCode); 179 | console.log('HEADERS:', JSON.stringify(res.headers)); 180 | callback(null, 'Successfully sent stack response!'); 181 | }); 182 | 183 | req.on('error', (err) => { 184 | console.log('sendResponse Error:\n', err); 185 | callback(err); 186 | }); 187 | 188 | req.write(responseBody); 189 | req.end(); 190 | }; 191 | -------------------------------------------------------------------------------- /source/update_ddb_from_stream/update_ddb_from_stream.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | 4 | # ##################################################################################################################### 5 | # Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. # 6 | # # 7 | # Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance # 8 | # with the License. A copy of the License is located at # 9 | # # 10 | # http://www.apache.org/licenses/LICENSE-2.0 # 11 | # # 12 | # or in the 'license' file accompanying this file. This file is distributed on an 'AS IS' BASIS, WITHOUT WARRANTIES # 13 | # OR CONDITIONS OF ANY KIND, express or implied. See the License for the specific language governing permissions # 14 | # and limitations under the License. # 15 | ####################################################################################################################### 16 | 17 | # @author Solution Builders 18 | 19 | from itertools import groupby 20 | import boto3 21 | import botocore 22 | import base64 23 | import os 24 | import logging 25 | import urllib.request 26 | import urllib.parse 27 | from json import loads,dumps 28 | from collections import OrderedDict 29 | from operator import itemgetter 30 | from random import randint 31 | from sys import maxsize 32 | from time import sleep 33 | 34 | log_level = str(os.environ.get('LOG_LEVEL')).upper() 35 | if log_level not in ['DEBUG', 'INFO','WARNING', 'ERROR','CRITICAL']: 36 | log_level = 'ERROR' 37 | log = logging.getLogger() 38 | log.setLevel(log_level) 39 | 40 | send_anonymous_data = str(os.environ.get('SEND_ANONYMOUS_DATA')).upper() 41 | ip_table_name = os.environ.get('IP_TABLE') 42 | table_name = os.environ.get('TABLE') 43 | calls_per_ip="CallsPerUniqueIp" 44 | successful_calls = "NumberOfSuccessfulCalls" 45 | anomaly_score = "AnomalyScore" 46 | max_retry_attempts = 5 47 | client = boto3.client('dynamodb') 48 | 49 | def update_dynamodb(record_data): 50 | ddb_record = client.get_item(TableName=table_name, 51 | Key={'MetricType': {'S':metric_type}, 52 | 'EventTime':{'S':event_time} }, 53 | ConsistentRead=True) 54 | 55 | ddb_data = loads(ddb_record['Item']['Data']['S']) 56 | concurrency_token = int(ddb_record['Item']['ConcurrencyToken']['N']) 57 | merged_data = { k : record_data.get(k,0) + ddb_data.get(k,0) for k in set(record_data) | set(ddb_data) } 58 | record_data = OrderedDict(sorted(merged_data.items(), key=itemgetter(1), reverse=True)) 59 | put_record(metric_type, event_time, record_data, concurrency_token) 60 | 61 | def put_record_with_retry(metric_type, event_time, record_data, merged_data, concurrency_token, attempt=0): 62 | log.info("Retry: {0} {1} {2}".format(metric_type, event_time, str(attempt))) 63 | if attempt > max_retry_attempts: return 64 | try: 65 | put_record(metric_type, event_time, merged_data, concurrency_token) 66 | except botocore.exceptions.ClientError as e: 67 | if e.response['Error']['Code'] == 'ConditionalCheckFailedException': 68 | sleep(randint(0,5)) 69 | ddb_record = client.get_item(TableName=table_name, 70 | Key={'MetricType': {'S':metric_type}, 71 | 'EventTime':{'S':event_time} }, 72 | ConsistentRead=True) 73 | merged_data = merge_record_with_ddb(record_data, ddb_record) 74 | put_record_with_retry(metric_type, event_time, record_data, merged_data, concurrency_token, attempt+1) 75 | else: raise 76 | 77 | def put_record(metric_type, event_time, data, concurrency_token=None): 78 | item = {'MetricType': {'S':metric_type}, 79 | 'EventTime':{'S':event_time}, 80 | 'Data':{'S':dumps(data)}, 81 | 'ConcurrencyToken':{'N':str(randint(0,maxsize))}} 82 | if concurrency_token: 83 | client.put_item(TableName=table_name, Item=item, 84 | ConditionExpression='ConcurrencyToken = :concurrency_token', 85 | ExpressionAttributeValues={':concurrency_token':{'N':str(concurrency_token)}}) 86 | else: 87 | client.put_item(TableName=table_name, Item=item) 88 | 89 | def merge_record_with_ddb(record_data, ddb_record): 90 | ddb_data = loads(ddb_record['Item']['Data']['S']) 91 | concurrency_token = int(ddb_record['Item']['ConcurrencyToken']['N']) 92 | merged_data = { k : record_data.get(k,0) + ddb_data.get(k,0) for k in set(record_data) | set(ddb_data) } 93 | merged_data = OrderedDict(sorted(merged_data.items(), key=itemgetter(1), reverse=True)) 94 | return merged_data 95 | 96 | def merge_record_values(metric_key, grouped_rows): 97 | if 'AnomalyScore' in metric_key: 98 | return sum(float(key[5]) for key in grouped_rows) 99 | else: 100 | return sum(int(key[5]) for key in grouped_rows) 101 | 102 | #This function sends anonymous usage data, if enabled 103 | def sendAnonymousData(event_time,dataDict): 104 | log.debug("Sending Anonymous Data") 105 | postDict = {} 106 | postDict['Data'] = dataDict 107 | postDict['TimeStamp'] = event_time 108 | postDict['Solution'] = 'SO0037' 109 | postDict['UUID'] = os.environ.get('UUID') 110 | 111 | # API Gateway URL to make HTTP POST call 112 | url = 'https://metrics.awssolutionsbuilder.com/generic' 113 | data = urllib.parse.urlencode(postDict).encode() 114 | log.debug(data) 115 | 116 | headers = {'content-type': 'application/json'} 117 | req = urllib.request.Request(url, data, headers) 118 | rsp = urllib.request.urlopen(req) 119 | rspcode = rsp.getcode() 120 | content = rsp.read() 121 | log.debug("Response from APIGateway: %s, %s", rspcode, content) 122 | 123 | def lambda_handler(event, context): 124 | payload = event['Records'] 125 | output = {} 126 | 127 | data = [base64.b64decode(record['kinesis']['data']).decode().strip().split(',') for record in payload] 128 | data = filter(lambda x: x[2]!="null", data) 129 | log.info(data) 130 | 131 | for metric_key,metric_group in groupby(data, key=lambda x:"{0}|{1}".format(x[0],x[1])): 132 | grouped_metric = list(metric_group) 133 | for category_key,grouped_rows in groupby(grouped_metric, key=lambda x: "{0}|{1}".format(x[2],x[3])): 134 | output.setdefault(metric_key, {})[category_key] = merge_record_values(metric_key, list(grouped_rows)) 135 | 136 | for record_key in output: 137 | event_time,metric_type = record_key.split('|') 138 | record_data = OrderedDict(sorted(output[record_key].items(), key=itemgetter(1), reverse=True)) 139 | 140 | ddb_record = client.get_item(TableName=table_name, 141 | Key={'MetricType': {'S':metric_type}, 142 | 'EventTime':{'S':event_time} }, 143 | ConsistentRead=True) 144 | 145 | if 'Item' not in ddb_record: 146 | put_record(metric_type,event_time, record_data) 147 | else: 148 | merged_data = merge_record_with_ddb(record_data, ddb_record) 149 | put_record_with_retry(metric_type, event_time, record_data, merged_data, int(ddb_record['Item']['ConcurrencyToken']['N'])) 150 | if metric_type == calls_per_ip: 151 | max_ip = next(iter(record_data)) 152 | max_ip_count = record_data[max_ip] 153 | 154 | max_ip = max_ip.split('|')[0] 155 | hour,minute,_ = event_time.split(':') 156 | 157 | ddb_max_ip = client.get_item(TableName=ip_table_name, 158 | Key={'Hour': {'S': hour}, 159 | 'Minute':{'S':minute} }, 160 | ConsistentRead=True) 161 | 162 | if 'Item' not in ddb_max_ip or max_ip_count > int(ddb_max_ip['Item']['MaxCount']['N']): 163 | client.put_item(TableName=ip_table_name, 164 | Item={'Hour': {'S':hour}, 165 | 'Minute':{'S':minute}, 166 | 'IP':{'S':max_ip}, 167 | 'MaxCount':{'N': str(max_ip_count)}} ) 168 | if send_anonymous_data == "YES": 169 | try: 170 | unique_keys = list(set(output)) 171 | for record_key in unique_keys: 172 | event_time,metric_type = record_key.split('|') 173 | if metric_type == successful_calls or metric_type == anomaly_score: 174 | ddb_record = client.get_item(TableName=table_name, 175 | Key={'MetricType': {'S':metric_type}, 176 | 'EventTime':{'S':event_time} }, 177 | ConsistentRead=True) 178 | del ddb_record["Item"]["ConcurrencyToken"] 179 | del ddb_record["Item"]["EventTime"] 180 | metric_data= {} 181 | metric_data['MetricType'] = ddb_record['Item']['MetricType']['S'] 182 | if metric_type == successful_calls: 183 | services, num_calls = ddb_record['Item']['Data']['S'].split(',')[0].split(':') 184 | metric_data['NumberOfSuccessfulCalls'] = num_calls.replace('}','').replace(' ', '') 185 | if metric_type == anomaly_score: 186 | num_calls,anomaly_data = ddb_record['Item']['Data']['S'].split(',')[0].split(':') 187 | metric_data['NumberOfSuccessfulCalls'] = num_calls.replace('{', '').replace('"', '').split('|')[0] 188 | metric_data['AnamonlyScore'] = anomaly_data.replace('}', '') 189 | sendAnonymousData(event_time,metric_data) 190 | except Exception as error: 191 | log.error(error) 192 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2019 - 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. -------------------------------------------------------------------------------- /source/helper/lib/website-helper.js: -------------------------------------------------------------------------------- 1 | /********************************************************************************************************************* 2 | * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * 3 | * * 4 | * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * 5 | * with the License. A copy of the License is located at * 6 | * * 7 | * http://www.apache.org/licenses/LICENSE-2.0 * 8 | * * 9 | * or in the 'license' file accompanying this file. This file is distributed on an 'AS IS' BASIS, WITHOUT WARRANTIES * 10 | * OR CONDITIONS OF ANY KIND, express or implied. See the License for the specific language governing permissions * 11 | * and limitations under the License. * 12 | *********************************************************************************************************************/ 13 | 14 | /** 15 | * @author Solution Builders 16 | */ 17 | 18 | 'use strict'; 19 | 20 | let AWS = require('aws-sdk'); 21 | let s3 = new AWS.S3(); 22 | const fs = require('fs'); 23 | const _downloadLocation = '/tmp/web-site-manifest.json'; 24 | 25 | /** 26 | * Helper function to interact with s3 hosted website for cfn custom resource. 27 | * 28 | * @class websiteHelper 29 | */ 30 | let websiteHelper = (function() { 31 | 32 | /** 33 | * @class websiteHelper 34 | * @constructor 35 | */ 36 | let websiteHelper = function() {}; 37 | 38 | /** 39 | * Provisions the web site UI at deployment. 40 | * @param {string} sourceS3Bucket - Bucket containing the web site files to be copied. 41 | * @param {string} sourceS3prefix - S3 prefix to prepend to the web site manifest file names to be copied. 42 | * @param {string} destS3Bucket - S3 destination bucket to copy website content into 43 | * @param {string} userPoolId - Cognito User Pool Id for web site configuration 44 | * @param {string} userPoolClientId - Cognito User Pool Client Id for web site configuration 45 | * @param {string} identityPoolId - Cognito Identity Pool ID 46 | * @param {string} region - Region of destination S3 bucket 47 | * @param {string} uuid - UUID for this instance of the solution 48 | * @param {string} dashboard_usage - Enable or disable dashaboard use tracking 49 | * @param {copyWebSiteAssets~requestCallback} cb - The callback that handles the response. 50 | */ 51 | websiteHelper.prototype.copyWebSiteAssets = function(sourceS3Bucket, sourceS3prefix, sourceManifest, destS3Bucket, 52 | userPoolId, userPoolClientId, identityPoolId, region, uuid, dashboard_usage,metrics_table,ip_table, cb) { 53 | console.log("Copying UI web site"); 54 | console.log(['source bucket:', sourceS3Bucket].join(' ')); 55 | console.log(['source prefix:', sourceS3prefix].join(' ')); 56 | console.log(['destination bucket:', destS3Bucket].join(' ')); 57 | console.log(['user pool:', userPoolId].join(' ')); 58 | console.log(['user pool client:', userPoolClientId].join(' ')); 59 | console.log(['identity pool:', identityPoolId].join(' ')); 60 | console.log(['region:', region].join(' ')); 61 | 62 | downloadWebisteManifest(sourceS3Bucket, sourceManifest, _downloadLocation, function(err, data) { 63 | if (err) { 64 | console.log(err); 65 | return cb(err, null); 66 | } 67 | 68 | fs.readFile(_downloadLocation, 'utf8', function(err, data) { 69 | if (err) { 70 | console.log(err); 71 | return cb(err, null); 72 | } 73 | 74 | console.log(data); 75 | let _manifest = validateJSON(data); 76 | 77 | if (!_manifest) { 78 | return cb('Unable to validate downloaded manifest file JSON', null); 79 | } else { 80 | uploadFile(_manifest.files, 0, destS3Bucket, [sourceS3Bucket, sourceS3prefix] 81 | .join('/'), 82 | function(err, result) { 83 | if (err) { 84 | return cb(err, null); 85 | } 86 | 87 | console.log(result); 88 | 89 | createAppVariables(userPoolId, userPoolClientId, identityPoolId, region, destS3Bucket, uuid, dashboard_usage, metrics_table, ip_table, 90 | function(err, createResult) { 91 | if (err) { 92 | return cb(err, null); 93 | } 94 | 95 | return cb(null, result); 96 | }); 97 | }); 98 | } 99 | 100 | }); 101 | 102 | }); 103 | 104 | }; 105 | 106 | /** 107 | * Helper function to validate the JSON structure of contents of an import manifest file. 108 | * @param {string} body - JSON object stringify-ed. 109 | * @returns {JSON} - The JSON parsed string or null if string parsing failed 110 | */ 111 | let validateJSON = function(body) { 112 | try { 113 | let data = JSON.parse(body); 114 | console.log(data); 115 | return data; 116 | } catch (e) { 117 | // failed to parse 118 | console.log('Manifest file contains invalid JSON.'); 119 | return null; 120 | } 121 | }; 122 | 123 | let createAppVariables = function(userPoolId, userPoolClientId, identityPoolId, region, destS3Bucket, uuid, dashboard_usage, metrics_table,ip_table, cb) { 124 | console.log("Creating AppVariables"); 125 | console.log(['destination bucket:', destS3Bucket].join(' ')); 126 | console.log(['user pool:', userPoolId].join(' ')); 127 | console.log(['user pool client:', userPoolClientId].join(' ')); 128 | console.log(['identity pool:', identityPoolId].join(' ')); 129 | console.log(['region:', region].join(' ')); 130 | console.log(['destS3Bucket:', destS3Bucket].join(' ')); 131 | console.log(['uuid:', uuid].join(' ')); 132 | console.log(['dashboard_usage:', dashboard_usage].join(' ')); 133 | console.log(['metrics_table:', metrics_table].join(' ')); 134 | console.log(['ip_table:', ip_table].join(' ')); 135 | 136 | var _content = [ 137 | ['localStorage.setItem(\'upid\', \'', userPoolId, '\');'].join(''), 138 | ['localStorage.setItem(\'cid\', \'', userPoolClientId, '\');'].join(''), 139 | ['localStorage.setItem(\'ipid\', \'', identityPoolId, '\');'].join(''), 140 | ['localStorage.setItem(\'r\', \'', region, '\');'].join(''), 141 | ['var _dashboard_usage = \'', dashboard_usage, '\';'].join(''), 142 | ['var metrics_table = \'', metrics_table, '\';'].join(''), 143 | ['var ip_table = \'', ip_table, '\';'].join(''), 144 | ['var _hit_data = {'], 145 | [' \'Solution\': \'SO0037\','], 146 | [' \'UUID\': \'',uuid,'\','].join(''), 147 | [' \'TimeStamp\': moment().utc().format(\'YYYY-MM-DD HH:mm:ss.S\'),'], 148 | [' \'Data\': {'], 149 | [' \'dashboard\': 1,'], 150 | [' \'region\': \'',region,'\''].join(''), 151 | [' }'], 152 | ['};'] 153 | ].join('\n'); 154 | console.log(_content); 155 | let params = { 156 | Bucket: destS3Bucket, 157 | Key: 'js/app-variables.js', 158 | Body: _content 159 | }; 160 | 161 | s3.putObject(params, function(err, data) { 162 | if (err) { 163 | console.log(err); 164 | return cb('error creating js/app-variables.js file for website UI', null); 165 | } 166 | 167 | console.log(data); 168 | return cb(null, data); 169 | }); 170 | 171 | }; 172 | 173 | let uploadFile = function(filelist, index, destS3Bucket, sourceS3prefix, cb) { 174 | if (filelist.length > index) { 175 | let params = { 176 | Bucket: destS3Bucket, 177 | Key: filelist[index], 178 | CopySource: [sourceS3prefix, filelist[index]].join('/'), 179 | }; 180 | if (filelist[index].endsWith('.htm') || filelist[index].endsWith('.html')) { 181 | params.ContentType = "text/html"; 182 | params.MetadataDirective = "REPLACE"; 183 | } else if (filelist[index].endsWith('.css')) { 184 | params.ContentType = "text/css"; 185 | params.MetadataDirective = "REPLACE"; 186 | } else if (filelist[index].endsWith('.js')) { 187 | params.ContentType = "application/javascript"; 188 | params.MetadataDirective = "REPLACE"; 189 | } else if (filelist[index].endsWith('.png')) { 190 | params.ContentType = "image/png"; 191 | params.MetadataDirective = "REPLACE"; 192 | } else if (filelist[index].endsWith('.jpg') || filelist[index].endsWith('.jpeg')) { 193 | params.ContentType = "image/jpeg"; 194 | params.MetadataDirective = "REPLACE"; 195 | } else if (filelist[index].endsWith('.gif')) { 196 | params.ContentType = "image/gif"; 197 | params.MetadataDirective = "REPLACE"; 198 | }; 199 | 200 | s3.copyObject(params, function(err, data) { 201 | if (err) { 202 | return cb(['error copying ', [sourceS3prefix, filelist[index]].join('/'), '\n', err] 203 | .join( 204 | ''), 205 | null); 206 | } 207 | 208 | console.log([ 209 | [sourceS3prefix, filelist[index]].join('/'), 'uploaded successfully' 210 | ].join(' ')); 211 | let _next = index + 1; 212 | uploadFile(filelist, _next, destS3Bucket, sourceS3prefix, function(err, resp) { 213 | if (err) { 214 | return cb(err, null); 215 | } 216 | 217 | cb(null, resp); 218 | }); 219 | }); 220 | } else { 221 | cb(null, [index, 'files copied'].join(' ')); 222 | } 223 | 224 | }; 225 | 226 | /** 227 | * Helper function to download the website manifest to local storage for processing. 228 | * @param {string} s3_bucket - Amazon S3 bucket of the website manifest to download. 229 | * @param {string} s3_key - Amazon S3 key of the website manifest to download. 230 | * @param {string} downloadLocation - Local storage location to download the Amazon S3 object. 231 | * @param {downloadManifest~requestCallback} cb - The callback that handles the response. 232 | */ 233 | let downloadWebisteManifest = function(s3Bucket, sourceManifest, downloadLocation, cb) { 234 | let params = { 235 | Bucket: s3Bucket, 236 | Key: sourceManifest 237 | }; 238 | 239 | console.log(params); 240 | 241 | // check to see if the manifest file exists 242 | s3.headObject(params, function(err, metadata) { 243 | if (err) { 244 | console.log(err); 245 | } 246 | 247 | if (err && err.code === 'NotFound') { 248 | // Handle no object on cloud here 249 | console.log('file doesnt exist'); 250 | return cb('Manifest file was not found.', null); 251 | } else { 252 | console.log('file exists'); 253 | console.log(metadata); 254 | let file = require('fs').createWriteStream(downloadLocation); 255 | 256 | s3.getObject(params). 257 | on('httpData', function(chunk) { 258 | file.write(chunk); 259 | }). 260 | on('httpDone', function() { 261 | file.end(); 262 | console.log('website manifest downloaded for processing...'); 263 | return cb(null, 'success'); 264 | }). 265 | send(); 266 | } 267 | }); 268 | }; 269 | 270 | return websiteHelper; 271 | 272 | })(); 273 | 274 | module.exports = websiteHelper; 275 | -------------------------------------------------------------------------------- /source/web_site/dash.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | CloudTrail Analytics Dashboard 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 |
29 |
30 |
31 | 32 |
33 | 38 | AWS CloudTrail Dashboard 39 |
40 | 41 |
42 |
    43 |
  • 44 | 45 | Configure 46 |
  • 47 |
  • 48 | 49 | Help 50 |
  • 51 |
  • 52 | 53 | Signing In 54 |
  • 55 | 56 |
  • 57 | 58 | Log Out 59 |
  • 60 | 61 |
62 |
63 |
64 | 65 |
66 |
67 | 68 |
69 | 70 |
71 |
72 | 73 |
74 | 75 | 76 |
77 |
78 |

AWS CloudTrail Analytics Dashboard

79 |

Sign in to get started. This dashboard uses Amazon Cognito for authentication. See 80 | help for more information.

81 |
82 |
83 | 84 |
85 |
86 |
87 |
88 | 91 |

Configuration

92 |
93 |
94 |
95 | The Dashboard is not configured correctly. Please ensure these values are set and are accurate. 96 |
97 | 98 |

99 | These values are used by the Dashboard to validate users in your Cognito User Pool. Don't change these values unless you 100 | know what you're doing! 101 |

102 |
103 |
104 |
105 | 106 | 107 |
108 |
109 | 110 | 111 |
112 |
113 | 114 | 115 |
116 |
117 | 118 | 119 |
120 | 121 |
122 |
123 |
124 |
125 | 126 | 127 | 128 |
129 |
130 |
131 |
132 | 133 |
134 |
135 |
136 |
137 | 140 |

Create New Password

141 |
142 |
143 |
144 | The passwords you entered do not match! 145 |
146 |
147 | The password you entered does not meet the following complexity requirements: 148 |
    149 |
  • 8 or more characters
  • 150 |
  • Upper case character
  • 151 |
  • Lower case character
  • 152 |
  • Number
  • 153 |
154 |
155 |
156 |
157 |

158 | Your temporary password must be changed! Please create a new password (8 or more characters, one of which must be 159 | uppercase, lowercase, and a number). 160 |

161 |
162 |
163 |
164 | 165 | 166 |
167 |
168 | 169 | 170 |
171 |
172 |
173 |
174 |
175 | 176 |
177 |
178 |
179 |
180 | 181 | 182 |
183 |
184 |
185 |

Overview of the dashboard

186 |

This dashboard demo and its associated solution provide a mechanism for collecting, analyzing, and displaying 187 | AWS account activity in real time. Amazon Kinesis Data Analytics 188 | is used to compute real-time metrics from AWS CloudTrail 189 | including top IP addresses, services, and API calls by request count. We encourage you to take this Amazon Kinesis 190 | Data Analytics solution and customize it for your own needs. Visit 191 | Real-Time Insights into AWS Account Activity 192 | to learn more about this solution. 193 |

194 |

195 | For more information, including processing and delivery times, please see help. 196 |

197 |
198 |
199 | 200 |
201 |
202 |

Total number of API calls
over the last 10 minutes

203 |
204 |
205 |
206 |
Count: 0
207 |
208 | 209 | Last Updated: 210 |
0
211 |
212 |
213 |
214 |
215 |
216 |
217 |
218 | 219 |
220 |
221 |
222 |

Calls by AWS Service 223 | Over the last hour

224 |
225 |
226 |
227 | 228 |
229 |
230 |
231 |
232 |
233 |
234 |

Anomaly Scores 235 | Over the last hour 236 |

237 |
238 |
239 |
240 |
241 | 242 |
243 |
244 |
245 |
246 | 247 |
248 |
249 | 250 |
251 | 252 |

Top 10 API calls 253 | Over the last minute

254 | 255 | 256 |
257 |
258 |
259 | 260 |
261 |
262 | 263 | 264 |
265 | 266 |
267 |
268 | 269 |

Top 10 IAM user calls 270 | Over the last minute

271 | 272 | 273 |
274 |
275 |
276 | 277 |
278 |
279 |
280 |
281 | 282 |
283 |
284 | 285 |
286 |

Max calls per IP Over last 24 hours

287 |
288 |
289 | 290 |
291 |
292 | 293 |
294 |
295 |

Top Calls By IP Over last 1 hour

296 |
297 |
298 | 299 |
300 |
301 |
302 |
303 |
304 |
305 |

EC2 Calls over the last hour

306 |
307 |
308 | 309 |
310 |
311 |
312 |
313 |
314 |
315 | 316 | 317 | 318 | 319 | 320 | 321 | 322 | 323 | 324 | 325 | 326 | 327 | 328 | 329 | 330 | 331 | 332 | 333 | 334 | 335 | 338 | 339 | 340 | 341 | -------------------------------------------------------------------------------- /source/web_site/js/bootstrap.min.js: -------------------------------------------------------------------------------- 1 | /*! 2 | * Bootstrap v3.3.6 (http://getbootstrap.com) 3 | * Copyright 2011-2015 Twitter, Inc. 4 | * Licensed under the MIT license 5 | */ 6 | if("undefined"==typeof jQuery)throw new Error("Bootstrap's JavaScript requires jQuery");+function(a){"use strict";var b=a.fn.jquery.split(" ")[0].split(".");if(b[0]<2&&b[1]<9||1==b[0]&&9==b[1]&&b[2]<1||b[0]>2)throw new Error("Bootstrap's JavaScript requires jQuery version 1.9.1 or higher, but lower than version 3")}(jQuery),+function(a){"use strict";function b(){var a=document.createElement("bootstrap"),b={WebkitTransition:"webkitTransitionEnd",MozTransition:"transitionend",OTransition:"oTransitionEnd otransitionend",transition:"transitionend"};for(var c in b)if(void 0!==a.style[c])return{end:b[c]};return!1}a.fn.emulateTransitionEnd=function(b){var c=!1,d=this;a(this).one("bsTransitionEnd",function(){c=!0});var e=function(){c||a(d).trigger(a.support.transition.end)};return setTimeout(e,b),this},a(function(){a.support.transition=b(),a.support.transition&&(a.event.special.bsTransitionEnd={bindType:a.support.transition.end,delegateType:a.support.transition.end,handle:function(b){return a(b.target).is(this)?b.handleObj.handler.apply(this,arguments):void 0}})})}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var c=a(this),e=c.data("bs.alert");e||c.data("bs.alert",e=new d(this)),"string"==typeof b&&e[b].call(c)})}var c='[data-dismiss="alert"]',d=function(b){a(b).on("click",c,this.close)};d.VERSION="3.3.6",d.TRANSITION_DURATION=150,d.prototype.close=function(b){function c(){g.detach().trigger("closed.bs.alert").remove()}var e=a(this),f=e.attr("data-target");f||(f=e.attr("href"),f=f&&f.replace(/.*(?=#[^\s]*$)/,""));var g=a(f);b&&b.preventDefault(),g.length||(g=e.closest(".alert")),g.trigger(b=a.Event("close.bs.alert")),b.isDefaultPrevented()||(g.removeClass("in"),a.support.transition&&g.hasClass("fade")?g.one("bsTransitionEnd",c).emulateTransitionEnd(d.TRANSITION_DURATION):c())};var e=a.fn.alert;a.fn.alert=b,a.fn.alert.Constructor=d,a.fn.alert.noConflict=function(){return a.fn.alert=e,this},a(document).on("click.bs.alert.data-api",c,d.prototype.close)}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.button"),f="object"==typeof b&&b;e||d.data("bs.button",e=new c(this,f)),"toggle"==b?e.toggle():b&&e.setState(b)})}var c=function(b,d){this.$element=a(b),this.options=a.extend({},c.DEFAULTS,d),this.isLoading=!1};c.VERSION="3.3.6",c.DEFAULTS={loadingText:"loading..."},c.prototype.setState=function(b){var c="disabled",d=this.$element,e=d.is("input")?"val":"html",f=d.data();b+="Text",null==f.resetText&&d.data("resetText",d[e]()),setTimeout(a.proxy(function(){d[e](null==f[b]?this.options[b]:f[b]),"loadingText"==b?(this.isLoading=!0,d.addClass(c).attr(c,c)):this.isLoading&&(this.isLoading=!1,d.removeClass(c).removeAttr(c))},this),0)},c.prototype.toggle=function(){var a=!0,b=this.$element.closest('[data-toggle="buttons"]');if(b.length){var c=this.$element.find("input");"radio"==c.prop("type")?(c.prop("checked")&&(a=!1),b.find(".active").removeClass("active"),this.$element.addClass("active")):"checkbox"==c.prop("type")&&(c.prop("checked")!==this.$element.hasClass("active")&&(a=!1),this.$element.toggleClass("active")),c.prop("checked",this.$element.hasClass("active")),a&&c.trigger("change")}else this.$element.attr("aria-pressed",!this.$element.hasClass("active")),this.$element.toggleClass("active")};var d=a.fn.button;a.fn.button=b,a.fn.button.Constructor=c,a.fn.button.noConflict=function(){return a.fn.button=d,this},a(document).on("click.bs.button.data-api",'[data-toggle^="button"]',function(c){var d=a(c.target);d.hasClass("btn")||(d=d.closest(".btn")),b.call(d,"toggle"),a(c.target).is('input[type="radio"]')||a(c.target).is('input[type="checkbox"]')||c.preventDefault()}).on("focus.bs.button.data-api blur.bs.button.data-api",'[data-toggle^="button"]',function(b){a(b.target).closest(".btn").toggleClass("focus",/^focus(in)?$/.test(b.type))})}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.carousel"),f=a.extend({},c.DEFAULTS,d.data(),"object"==typeof b&&b),g="string"==typeof b?b:f.slide;e||d.data("bs.carousel",e=new c(this,f)),"number"==typeof b?e.to(b):g?e[g]():f.interval&&e.pause().cycle()})}var c=function(b,c){this.$element=a(b),this.$indicators=this.$element.find(".carousel-indicators"),this.options=c,this.paused=null,this.sliding=null,this.interval=null,this.$active=null,this.$items=null,this.options.keyboard&&this.$element.on("keydown.bs.carousel",a.proxy(this.keydown,this)),"hover"==this.options.pause&&!("ontouchstart"in document.documentElement)&&this.$element.on("mouseenter.bs.carousel",a.proxy(this.pause,this)).on("mouseleave.bs.carousel",a.proxy(this.cycle,this))};c.VERSION="3.3.6",c.TRANSITION_DURATION=600,c.DEFAULTS={interval:5e3,pause:"hover",wrap:!0,keyboard:!0},c.prototype.keydown=function(a){if(!/input|textarea/i.test(a.target.tagName)){switch(a.which){case 37:this.prev();break;case 39:this.next();break;default:return}a.preventDefault()}},c.prototype.cycle=function(b){return b||(this.paused=!1),this.interval&&clearInterval(this.interval),this.options.interval&&!this.paused&&(this.interval=setInterval(a.proxy(this.next,this),this.options.interval)),this},c.prototype.getItemIndex=function(a){return this.$items=a.parent().children(".item"),this.$items.index(a||this.$active)},c.prototype.getItemForDirection=function(a,b){var c=this.getItemIndex(b),d="prev"==a&&0===c||"next"==a&&c==this.$items.length-1;if(d&&!this.options.wrap)return b;var e="prev"==a?-1:1,f=(c+e)%this.$items.length;return this.$items.eq(f)},c.prototype.to=function(a){var b=this,c=this.getItemIndex(this.$active=this.$element.find(".item.active"));return a>this.$items.length-1||0>a?void 0:this.sliding?this.$element.one("slid.bs.carousel",function(){b.to(a)}):c==a?this.pause().cycle():this.slide(a>c?"next":"prev",this.$items.eq(a))},c.prototype.pause=function(b){return b||(this.paused=!0),this.$element.find(".next, .prev").length&&a.support.transition&&(this.$element.trigger(a.support.transition.end),this.cycle(!0)),this.interval=clearInterval(this.interval),this},c.prototype.next=function(){return this.sliding?void 0:this.slide("next")},c.prototype.prev=function(){return this.sliding?void 0:this.slide("prev")},c.prototype.slide=function(b,d){var e=this.$element.find(".item.active"),f=d||this.getItemForDirection(b,e),g=this.interval,h="next"==b?"left":"right",i=this;if(f.hasClass("active"))return this.sliding=!1;var j=f[0],k=a.Event("slide.bs.carousel",{relatedTarget:j,direction:h});if(this.$element.trigger(k),!k.isDefaultPrevented()){if(this.sliding=!0,g&&this.pause(),this.$indicators.length){this.$indicators.find(".active").removeClass("active");var l=a(this.$indicators.children()[this.getItemIndex(f)]);l&&l.addClass("active")}var m=a.Event("slid.bs.carousel",{relatedTarget:j,direction:h});return a.support.transition&&this.$element.hasClass("slide")?(f.addClass(b),f[0].offsetWidth,e.addClass(h),f.addClass(h),e.one("bsTransitionEnd",function(){f.removeClass([b,h].join(" ")).addClass("active"),e.removeClass(["active",h].join(" ")),i.sliding=!1,setTimeout(function(){i.$element.trigger(m)},0)}).emulateTransitionEnd(c.TRANSITION_DURATION)):(e.removeClass("active"),f.addClass("active"),this.sliding=!1,this.$element.trigger(m)),g&&this.cycle(),this}};var d=a.fn.carousel;a.fn.carousel=b,a.fn.carousel.Constructor=c,a.fn.carousel.noConflict=function(){return a.fn.carousel=d,this};var e=function(c){var d,e=a(this),f=a(e.attr("data-target")||(d=e.attr("href"))&&d.replace(/.*(?=#[^\s]+$)/,""));if(f.hasClass("carousel")){var g=a.extend({},f.data(),e.data()),h=e.attr("data-slide-to");h&&(g.interval=!1),b.call(f,g),h&&f.data("bs.carousel").to(h),c.preventDefault()}};a(document).on("click.bs.carousel.data-api","[data-slide]",e).on("click.bs.carousel.data-api","[data-slide-to]",e),a(window).on("load",function(){a('[data-ride="carousel"]').each(function(){var c=a(this);b.call(c,c.data())})})}(jQuery),+function(a){"use strict";function b(b){var c,d=b.attr("data-target")||(c=b.attr("href"))&&c.replace(/.*(?=#[^\s]+$)/,"");return a(d)}function c(b){return this.each(function(){var c=a(this),e=c.data("bs.collapse"),f=a.extend({},d.DEFAULTS,c.data(),"object"==typeof b&&b);!e&&f.toggle&&/show|hide/.test(b)&&(f.toggle=!1),e||c.data("bs.collapse",e=new d(this,f)),"string"==typeof b&&e[b]()})}var d=function(b,c){this.$element=a(b),this.options=a.extend({},d.DEFAULTS,c),this.$trigger=a('[data-toggle="collapse"][href="#'+b.id+'"],[data-toggle="collapse"][data-target="#'+b.id+'"]'),this.transitioning=null,this.options.parent?this.$parent=this.getParent():this.addAriaAndCollapsedClass(this.$element,this.$trigger),this.options.toggle&&this.toggle()};d.VERSION="3.3.6",d.TRANSITION_DURATION=350,d.DEFAULTS={toggle:!0},d.prototype.dimension=function(){var a=this.$element.hasClass("width");return a?"width":"height"},d.prototype.show=function(){if(!this.transitioning&&!this.$element.hasClass("in")){var b,e=this.$parent&&this.$parent.children(".panel").children(".in, .collapsing");if(!(e&&e.length&&(b=e.data("bs.collapse"),b&&b.transitioning))){var f=a.Event("show.bs.collapse");if(this.$element.trigger(f),!f.isDefaultPrevented()){e&&e.length&&(c.call(e,"hide"),b||e.data("bs.collapse",null));var g=this.dimension();this.$element.removeClass("collapse").addClass("collapsing")[g](0).attr("aria-expanded",!0),this.$trigger.removeClass("collapsed").attr("aria-expanded",!0),this.transitioning=1;var h=function(){this.$element.removeClass("collapsing").addClass("collapse in")[g](""),this.transitioning=0,this.$element.trigger("shown.bs.collapse")};if(!a.support.transition)return h.call(this);var i=a.camelCase(["scroll",g].join("-"));this.$element.one("bsTransitionEnd",a.proxy(h,this)).emulateTransitionEnd(d.TRANSITION_DURATION)[g](this.$element[0][i])}}}},d.prototype.hide=function(){if(!this.transitioning&&this.$element.hasClass("in")){var b=a.Event("hide.bs.collapse");if(this.$element.trigger(b),!b.isDefaultPrevented()){var c=this.dimension();this.$element[c](this.$element[c]())[0].offsetHeight,this.$element.addClass("collapsing").removeClass("collapse in").attr("aria-expanded",!1),this.$trigger.addClass("collapsed").attr("aria-expanded",!1),this.transitioning=1;var e=function(){this.transitioning=0,this.$element.removeClass("collapsing").addClass("collapse").trigger("hidden.bs.collapse")};return a.support.transition?void this.$element[c](0).one("bsTransitionEnd",a.proxy(e,this)).emulateTransitionEnd(d.TRANSITION_DURATION):e.call(this)}}},d.prototype.toggle=function(){this[this.$element.hasClass("in")?"hide":"show"]()},d.prototype.getParent=function(){return a(this.options.parent).find('[data-toggle="collapse"][data-parent="'+this.options.parent+'"]').each(a.proxy(function(c,d){var e=a(d);this.addAriaAndCollapsedClass(b(e),e)},this)).end()},d.prototype.addAriaAndCollapsedClass=function(a,b){var c=a.hasClass("in");a.attr("aria-expanded",c),b.toggleClass("collapsed",!c).attr("aria-expanded",c)};var e=a.fn.collapse;a.fn.collapse=c,a.fn.collapse.Constructor=d,a.fn.collapse.noConflict=function(){return a.fn.collapse=e,this},a(document).on("click.bs.collapse.data-api",'[data-toggle="collapse"]',function(d){var e=a(this);e.attr("data-target")||d.preventDefault();var f=b(e),g=f.data("bs.collapse"),h=g?"toggle":e.data();c.call(f,h)})}(jQuery),+function(a){"use strict";function b(b){var c=b.attr("data-target");c||(c=b.attr("href"),c=c&&/#[A-Za-z]/.test(c)&&c.replace(/.*(?=#[^\s]*$)/,""));var d=c&&a(c);return d&&d.length?d:b.parent()}function c(c){c&&3===c.which||(a(e).remove(),a(f).each(function(){var d=a(this),e=b(d),f={relatedTarget:this};e.hasClass("open")&&(c&&"click"==c.type&&/input|textarea/i.test(c.target.tagName)&&a.contains(e[0],c.target)||(e.trigger(c=a.Event("hide.bs.dropdown",f)),c.isDefaultPrevented()||(d.attr("aria-expanded","false"),e.removeClass("open").trigger(a.Event("hidden.bs.dropdown",f)))))}))}function d(b){return this.each(function(){var c=a(this),d=c.data("bs.dropdown");d||c.data("bs.dropdown",d=new g(this)),"string"==typeof b&&d[b].call(c)})}var e=".dropdown-backdrop",f='[data-toggle="dropdown"]',g=function(b){a(b).on("click.bs.dropdown",this.toggle)};g.VERSION="3.3.6",g.prototype.toggle=function(d){var e=a(this);if(!e.is(".disabled, :disabled")){var f=b(e),g=f.hasClass("open");if(c(),!g){"ontouchstart"in document.documentElement&&!f.closest(".navbar-nav").length&&a(document.createElement("div")).addClass("dropdown-backdrop").insertAfter(a(this)).on("click",c);var h={relatedTarget:this};if(f.trigger(d=a.Event("show.bs.dropdown",h)),d.isDefaultPrevented())return;e.trigger("focus").attr("aria-expanded","true"),f.toggleClass("open").trigger(a.Event("shown.bs.dropdown",h))}return!1}},g.prototype.keydown=function(c){if(/(38|40|27|32)/.test(c.which)&&!/input|textarea/i.test(c.target.tagName)){var d=a(this);if(c.preventDefault(),c.stopPropagation(),!d.is(".disabled, :disabled")){var e=b(d),g=e.hasClass("open");if(!g&&27!=c.which||g&&27==c.which)return 27==c.which&&e.find(f).trigger("focus"),d.trigger("click");var h=" li:not(.disabled):visible a",i=e.find(".dropdown-menu"+h);if(i.length){var j=i.index(c.target);38==c.which&&j>0&&j--,40==c.which&&jdocument.documentElement.clientHeight;this.$element.css({paddingLeft:!this.bodyIsOverflowing&&a?this.scrollbarWidth:"",paddingRight:this.bodyIsOverflowing&&!a?this.scrollbarWidth:""})},c.prototype.resetAdjustments=function(){this.$element.css({paddingLeft:"",paddingRight:""})},c.prototype.checkScrollbar=function(){var a=window.innerWidth;if(!a){var b=document.documentElement.getBoundingClientRect();a=b.right-Math.abs(b.left)}this.bodyIsOverflowing=document.body.clientWidth
',trigger:"hover focus",title:"",delay:0,html:!1,container:!1,viewport:{selector:"body",padding:0}},c.prototype.init=function(b,c,d){if(this.enabled=!0,this.type=b,this.$element=a(c),this.options=this.getOptions(d),this.$viewport=this.options.viewport&&a(a.isFunction(this.options.viewport)?this.options.viewport.call(this,this.$element):this.options.viewport.selector||this.options.viewport),this.inState={click:!1,hover:!1,focus:!1},this.$element[0]instanceof document.constructor&&!this.options.selector)throw new Error("`selector` option must be specified when initializing "+this.type+" on the window.document object!");for(var e=this.options.trigger.split(" "),f=e.length;f--;){var g=e[f];if("click"==g)this.$element.on("click."+this.type,this.options.selector,a.proxy(this.toggle,this));else if("manual"!=g){var h="hover"==g?"mouseenter":"focusin",i="hover"==g?"mouseleave":"focusout";this.$element.on(h+"."+this.type,this.options.selector,a.proxy(this.enter,this)),this.$element.on(i+"."+this.type,this.options.selector,a.proxy(this.leave,this))}}this.options.selector?this._options=a.extend({},this.options,{trigger:"manual",selector:""}):this.fixTitle()},c.prototype.getDefaults=function(){return c.DEFAULTS},c.prototype.getOptions=function(b){return b=a.extend({},this.getDefaults(),this.$element.data(),b),b.delay&&"number"==typeof b.delay&&(b.delay={show:b.delay,hide:b.delay}),b},c.prototype.getDelegateOptions=function(){var b={},c=this.getDefaults();return this._options&&a.each(this._options,function(a,d){c[a]!=d&&(b[a]=d)}),b},c.prototype.enter=function(b){var c=b instanceof this.constructor?b:a(b.currentTarget).data("bs."+this.type);return c||(c=new this.constructor(b.currentTarget,this.getDelegateOptions()),a(b.currentTarget).data("bs."+this.type,c)),b instanceof a.Event&&(c.inState["focusin"==b.type?"focus":"hover"]=!0),c.tip().hasClass("in")||"in"==c.hoverState?void(c.hoverState="in"):(clearTimeout(c.timeout),c.hoverState="in",c.options.delay&&c.options.delay.show?void(c.timeout=setTimeout(function(){"in"==c.hoverState&&c.show()},c.options.delay.show)):c.show())},c.prototype.isInStateTrue=function(){for(var a in this.inState)if(this.inState[a])return!0;return!1},c.prototype.leave=function(b){var c=b instanceof this.constructor?b:a(b.currentTarget).data("bs."+this.type);return c||(c=new this.constructor(b.currentTarget,this.getDelegateOptions()),a(b.currentTarget).data("bs."+this.type,c)),b instanceof a.Event&&(c.inState["focusout"==b.type?"focus":"hover"]=!1),c.isInStateTrue()?void 0:(clearTimeout(c.timeout),c.hoverState="out",c.options.delay&&c.options.delay.hide?void(c.timeout=setTimeout(function(){"out"==c.hoverState&&c.hide()},c.options.delay.hide)):c.hide())},c.prototype.show=function(){var b=a.Event("show.bs."+this.type);if(this.hasContent()&&this.enabled){this.$element.trigger(b);var d=a.contains(this.$element[0].ownerDocument.documentElement,this.$element[0]);if(b.isDefaultPrevented()||!d)return;var e=this,f=this.tip(),g=this.getUID(this.type);this.setContent(),f.attr("id",g),this.$element.attr("aria-describedby",g),this.options.animation&&f.addClass("fade");var h="function"==typeof this.options.placement?this.options.placement.call(this,f[0],this.$element[0]):this.options.placement,i=/\s?auto?\s?/i,j=i.test(h);j&&(h=h.replace(i,"")||"top"),f.detach().css({top:0,left:0,display:"block"}).addClass(h).data("bs."+this.type,this),this.options.container?f.appendTo(this.options.container):f.insertAfter(this.$element),this.$element.trigger("inserted.bs."+this.type);var k=this.getPosition(),l=f[0].offsetWidth,m=f[0].offsetHeight;if(j){var n=h,o=this.getPosition(this.$viewport);h="bottom"==h&&k.bottom+m>o.bottom?"top":"top"==h&&k.top-mo.width?"left":"left"==h&&k.left-lg.top+g.height&&(e.top=g.top+g.height-i)}else{var j=b.left-f,k=b.left+f+c;jg.right&&(e.left=g.left+g.width-k)}return e},c.prototype.getTitle=function(){var a,b=this.$element,c=this.options;return a=b.attr("data-original-title")||("function"==typeof c.title?c.title.call(b[0]):c.title)},c.prototype.getUID=function(a){do a+=~~(1e6*Math.random());while(document.getElementById(a));return a},c.prototype.tip=function(){if(!this.$tip&&(this.$tip=a(this.options.template),1!=this.$tip.length))throw new Error(this.type+" `template` option must consist of exactly 1 top-level element!");return this.$tip},c.prototype.arrow=function(){return this.$arrow=this.$arrow||this.tip().find(".tooltip-arrow")},c.prototype.enable=function(){this.enabled=!0},c.prototype.disable=function(){this.enabled=!1},c.prototype.toggleEnabled=function(){this.enabled=!this.enabled},c.prototype.toggle=function(b){var c=this;b&&(c=a(b.currentTarget).data("bs."+this.type),c||(c=new this.constructor(b.currentTarget,this.getDelegateOptions()),a(b.currentTarget).data("bs."+this.type,c))),b?(c.inState.click=!c.inState.click,c.isInStateTrue()?c.enter(c):c.leave(c)):c.tip().hasClass("in")?c.leave(c):c.enter(c)},c.prototype.destroy=function(){var a=this;clearTimeout(this.timeout),this.hide(function(){a.$element.off("."+a.type).removeData("bs."+a.type),a.$tip&&a.$tip.detach(),a.$tip=null,a.$arrow=null,a.$viewport=null})};var d=a.fn.tooltip;a.fn.tooltip=b,a.fn.tooltip.Constructor=c,a.fn.tooltip.noConflict=function(){return a.fn.tooltip=d,this}}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.popover"),f="object"==typeof b&&b;(e||!/destroy|hide/.test(b))&&(e||d.data("bs.popover",e=new c(this,f)),"string"==typeof b&&e[b]())})}var c=function(a,b){this.init("popover",a,b)};if(!a.fn.tooltip)throw new Error("Popover requires tooltip.js");c.VERSION="3.3.6",c.DEFAULTS=a.extend({},a.fn.tooltip.Constructor.DEFAULTS,{placement:"right",trigger:"click",content:"",template:'

'}),c.prototype=a.extend({},a.fn.tooltip.Constructor.prototype),c.prototype.constructor=c,c.prototype.getDefaults=function(){return c.DEFAULTS},c.prototype.setContent=function(){var a=this.tip(),b=this.getTitle(),c=this.getContent();a.find(".popover-title")[this.options.html?"html":"text"](b),a.find(".popover-content").children().detach().end()[this.options.html?"string"==typeof c?"html":"append":"text"](c),a.removeClass("fade top bottom left right in"),a.find(".popover-title").html()||a.find(".popover-title").hide()},c.prototype.hasContent=function(){return this.getTitle()||this.getContent()},c.prototype.getContent=function(){var a=this.$element,b=this.options;return a.attr("data-content")||("function"==typeof b.content?b.content.call(a[0]):b.content)},c.prototype.arrow=function(){return this.$arrow=this.$arrow||this.tip().find(".arrow")};var d=a.fn.popover;a.fn.popover=b,a.fn.popover.Constructor=c,a.fn.popover.noConflict=function(){return a.fn.popover=d,this}}(jQuery),+function(a){"use strict";function b(c,d){this.$body=a(document.body),this.$scrollElement=a(a(c).is(document.body)?window:c),this.options=a.extend({},b.DEFAULTS,d),this.selector=(this.options.target||"")+" .nav li > a",this.offsets=[],this.targets=[],this.activeTarget=null,this.scrollHeight=0,this.$scrollElement.on("scroll.bs.scrollspy",a.proxy(this.process,this)),this.refresh(),this.process()}function c(c){return this.each(function(){var d=a(this),e=d.data("bs.scrollspy"),f="object"==typeof c&&c;e||d.data("bs.scrollspy",e=new b(this,f)),"string"==typeof c&&e[c]()})}b.VERSION="3.3.6",b.DEFAULTS={offset:10},b.prototype.getScrollHeight=function(){return this.$scrollElement[0].scrollHeight||Math.max(this.$body[0].scrollHeight,document.documentElement.scrollHeight)},b.prototype.refresh=function(){var b=this,c="offset",d=0;this.offsets=[],this.targets=[],this.scrollHeight=this.getScrollHeight(),a.isWindow(this.$scrollElement[0])||(c="position",d=this.$scrollElement.scrollTop()),this.$body.find(this.selector).map(function(){var b=a(this),e=b.data("target")||b.attr("href"),f=/^#./.test(e)&&a(e);return f&&f.length&&f.is(":visible")&&[[f[c]().top+d,e]]||null}).sort(function(a,b){return a[0]-b[0]}).each(function(){b.offsets.push(this[0]),b.targets.push(this[1])})},b.prototype.process=function(){var a,b=this.$scrollElement.scrollTop()+this.options.offset,c=this.getScrollHeight(),d=this.options.offset+c-this.$scrollElement.height(),e=this.offsets,f=this.targets,g=this.activeTarget;if(this.scrollHeight!=c&&this.refresh(),b>=d)return g!=(a=f[f.length-1])&&this.activate(a);if(g&&b=e[a]&&(void 0===e[a+1]||b .dropdown-menu > .active").removeClass("active").end().find('[data-toggle="tab"]').attr("aria-expanded",!1),b.addClass("active").find('[data-toggle="tab"]').attr("aria-expanded",!0),h?(b[0].offsetWidth,b.addClass("in")):b.removeClass("fade"),b.parent(".dropdown-menu").length&&b.closest("li.dropdown").addClass("active").end().find('[data-toggle="tab"]').attr("aria-expanded",!0),e&&e()}var g=d.find("> .active"),h=e&&a.support.transition&&(g.length&&g.hasClass("fade")||!!d.find("> .fade").length);g.length&&h?g.one("bsTransitionEnd",f).emulateTransitionEnd(c.TRANSITION_DURATION):f(),g.removeClass("in")};var d=a.fn.tab;a.fn.tab=b,a.fn.tab.Constructor=c,a.fn.tab.noConflict=function(){return a.fn.tab=d,this};var e=function(c){c.preventDefault(),b.call(a(this),"show")};a(document).on("click.bs.tab.data-api",'[data-toggle="tab"]',e).on("click.bs.tab.data-api",'[data-toggle="pill"]',e)}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.affix"),f="object"==typeof b&&b;e||d.data("bs.affix",e=new c(this,f)),"string"==typeof b&&e[b]()})}var c=function(b,d){this.options=a.extend({},c.DEFAULTS,d),this.$target=a(this.options.target).on("scroll.bs.affix.data-api",a.proxy(this.checkPosition,this)).on("click.bs.affix.data-api",a.proxy(this.checkPositionWithEventLoop,this)),this.$element=a(b),this.affixed=null,this.unpin=null,this.pinnedOffset=null,this.checkPosition()};c.VERSION="3.3.6",c.RESET="affix affix-top affix-bottom",c.DEFAULTS={offset:0,target:window},c.prototype.getState=function(a,b,c,d){var e=this.$target.scrollTop(),f=this.$element.offset(),g=this.$target.height();if(null!=c&&"top"==this.affixed)return c>e?"top":!1;if("bottom"==this.affixed)return null!=c?e+this.unpin<=f.top?!1:"bottom":a-d>=e+g?!1:"bottom";var h=null==this.affixed,i=h?e:f.top,j=h?g:b;return null!=c&&c>=e?"top":null!=d&&i+j>=a-d?"bottom":!1},c.prototype.getPinnedOffset=function(){if(this.pinnedOffset)return this.pinnedOffset;this.$element.removeClass(c.RESET).addClass("affix");var a=this.$target.scrollTop(),b=this.$element.offset();return this.pinnedOffset=b.top-a},c.prototype.checkPositionWithEventLoop=function(){setTimeout(a.proxy(this.checkPosition,this),1)},c.prototype.checkPosition=function(){if(this.$element.is(":visible")){var b=this.$element.height(),d=this.options.offset,e=d.top,f=d.bottom,g=Math.max(a(document).height(),a(document.body).height());"object"!=typeof d&&(f=e=d),"function"==typeof e&&(e=d.top(this.$element)),"function"==typeof f&&(f=d.bottom(this.$element));var h=this.getState(g,b,e,f);if(this.affixed!=h){null!=this.unpin&&this.$element.css("top","");var i="affix"+(h?"-"+h:""),j=a.Event(i+".bs.affix");if(this.$element.trigger(j),j.isDefaultPrevented())return;this.affixed=h,this.unpin="bottom"==h?this.getPinnedOffset():null,this.$element.removeClass(c.RESET).addClass(i).trigger(i.replace("affix","affixed")+".bs.affix")}"bottom"==h&&this.$element.offset({top:g-b-f})}};var d=a.fn.affix;a.fn.affix=b,a.fn.affix.Constructor=c,a.fn.affix.noConflict=function(){return a.fn.affix=d,this},a(window).on("load",function(){a('[data-spy="affix"]').each(function(){var c=a(this),d=c.data();d.offset=d.offset||{},null!=d.offsetBottom&&(d.offset.bottom=d.offsetBottom),null!=d.offsetTop&&(d.offset.top=d.offsetTop),b.call(c,d)})})}(jQuery); -------------------------------------------------------------------------------- /source/web_site/js/dash.js: -------------------------------------------------------------------------------- 1 | function init() { 2 | 3 | const clientIdParamName = "cid", 4 | userPoolIdParamName = "upid", 5 | identityPoolIdParamName = "ipid", 6 | cognitoRegionParamName = "r"; 7 | 8 | var streamName, 9 | streamType, 10 | rate, 11 | sendDataHandle, 12 | totalRecordsSent = 0, 13 | cognitoAppClientId = getCongitoConfigParameterByName(clientIdParamName), 14 | cognitoUserPoolId = getCongitoConfigParameterByName(userPoolIdParamName), 15 | cognitoIdentityPoolId = getCongitoConfigParameterByName(identityPoolIdParamName), 16 | cognitoRegion = getCongitoConfigParameterByName(cognitoRegionParamName), 17 | cognitoUser; 18 | 19 | 20 | $("#userPoolId").val(cognitoUserPoolId); 21 | $("#identityPoolId").val(cognitoIdentityPoolId); 22 | $("#clientId").val(cognitoAppClientId); 23 | $("#userPoolRegion").val(cognitoRegion); 24 | 25 | function getCongitoConfigParameterByName(name) { 26 | var data = getQSParameterByName(name); 27 | if(data == null || data == '') { 28 | data = localStorage.getItem(name); 29 | return data; 30 | } 31 | localStorage.setItem(name, data); 32 | return data; 33 | } 34 | function getQSParameterByName(name, url) { 35 | if (!url) { 36 | url = window.location.href; 37 | } 38 | name = name.replace(/[\[\]]/g, "\\$&"); 39 | var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"), 40 | results = regex.exec(url); 41 | if (!results) return null; 42 | if (!results[2]) return ''; 43 | return decodeURIComponent(results[2].replace(/\+/g, " ")); 44 | } 45 | var dateTime = []; 46 | var usersCounter = []; 47 | var androidUsers = []; 48 | var iOSUsers = []; 49 | var windowsUsers = []; 50 | var otherUsers = []; 51 | var quadA = []; 52 | var quadB = []; 53 | var quadC = []; 54 | var quadD = []; 55 | 56 | var osUsageData = []; 57 | var quadrantData = []; 58 | 59 | var colors = ["red", "green", "blue", "orange", "purple", "cyan", "magenta", "lime", "pink", "teal", "lavender", "brown", "beige", "maroon", "mint", "olive", "coral"]; 60 | var dynamicColors = function(i) { 61 | if (i >= 0 && i < colors.length) return colors[i]; 62 | var r = Math.floor(Math.random() * 255); 63 | var g = Math.floor(Math.random() * 255); 64 | var b = Math.floor(Math.random() * 255); 65 | return "rgb(" + r + "," + g + "," + b + ")"; 66 | } 67 | 68 | 69 | var identity = function(arg1) { 70 | return arg1; 71 | }; 72 | 73 | 74 | function addData(chart, label, data) { 75 | chart.data.labels = label; 76 | for (var i=0;i :currentTime", 357 | ExpressionAttributeValues: { ":currentTime": eventTime, ":TrailLog": metricType } 358 | } 359 | }; 360 | var retrieveParamsFromMaxTable = function(metricType, eventTime) { 361 | var date = eventTime.split(' '); 362 | var time = date[1].split(':'); 363 | var hour = date[0]+ " " + time[0]; 364 | var min = time[1]; 365 | return { 366 | //BUGFIX removed hardcoded table names 367 | TableName: ip_table, 368 | ConsistentRead: true, 369 | ScanIndexForward: true, 370 | KeyConditionExpression: "#hour = :hour AND #min > :minute", 371 | ExpressionAttributeNames: {"#hour": "Hour", "#min": "Minute"}, 372 | ExpressionAttributeValues: { ":hour": hour, ":minute": min } 373 | } 374 | } 375 | var updateHorizontalBarChart = function(data, noOfTopItems, chartName, queryTime, labelFunc=identity) { 376 | var items = data.Items; 377 | var ipCountMap = {}; 378 | 379 | // Merge the counts of each DDB item into a single map. 380 | for (var i=0; i 0) { 387 | //console.log(items); 388 | queryTime = items[items.length-1].EventTime; 389 | 390 | var topIps = Object.keys(ipCountMap).sort(function(a,b) { return ipCountMap[b] - ipCountMap[a]}).slice(0,noOfTopItems); 391 | if (topIps.length < noOfTopItems) { 392 | ipCountMap[""] = 0; 393 | for (var i=topIps.length; i i+1); 406 | }; 407 | var range = function(n) { 408 | return Array(n).fill().map((_, i) => i); 409 | }; 410 | var allzeros = function(arr) { 411 | return arr.every(function(x) { return x==0; }); 412 | }; 413 | var normalizeValues = function(labels, times, vals) { 414 | //make existing and new labels/vals as an array of objects, sort it based on label. 415 | //if any value is 0, check if label before and after is less than 10 seconds. if so remove it. 416 | // Constraint: any consecutive non-zero value will be atleast 10 seconds apart. 417 | n=labels.length; 418 | if (n>0) { 419 | var indicesOfLabelsToRemove = range1(n-1).filter(function(key, _) { 420 | return ((times[key-1] + 10000 < times[key]) || (times[key] + 10000 < times[key+1])) && allzeros(vals.map(function(val) {return val[key]; })); 421 | }); 422 | console.log('indices to remove ' + indicesOfLabelsToRemove); 423 | console.log('labels before removing ' + labels); 424 | console.log('times before removing ' + times); 425 | for (i=indicesOfLabelsToRemove.length-1; i>=0; i--) { 426 | x=indicesOfLabelsToRemove[i]; 427 | labels.splice(x,1); 428 | times.splice(x,1); 429 | vals.forEach(function(valArray) { valArray.splice(x,1);}); 430 | }; 431 | 432 | console.log('labels after removing ' + labels); 433 | } 434 | 435 | 436 | var labelsToAdd = range1(n).filter(function(key) { 437 | return (times[key]>=times[key-1]+20000) 438 | }); 439 | //console.log('labels to add ' + labelsToAdd); 440 | for (i=labelsToAdd.length-1; i>=0; i--) { 441 | x=labelsToAdd[i]; 442 | noOfLabelsToInsert = (times[x]-times[x-1])/10000 - 1; 443 | for (j=0;j0) { 457 | labels.splice(0,indexToSlice); 458 | times.splice(0,indexToSlice); 459 | vals.forEach(function(val) { val.slice(indexToSlice); }); 460 | } 461 | }; 462 | 463 | var splitLabel = function(label) { 464 | return [''].concat(label.split(' ')); 465 | } 466 | var sortLabels = function(data) { 467 | data.sort(function(obj1, obj2) {return obj1['time'] - obj2['time']}); 468 | } 469 | 470 | var fastUpdateLineChart = function(data, chartData, chart, queryTime, labelFunc=identity) { 471 | var serviceCallLabels = chartData.labels; 472 | var serviceCallTimes = chartData.times; 473 | var serviceCallMap = chartData.values; 474 | 475 | var items = data.Items; 476 | for (var i=0; i time10sAgo?queryTime: time10sAgo); 513 | } 514 | updateData(chart, serviceCallLabels, Object.values(serviceCallMap), Object.keys(serviceCallMap).map(labelFunc)); 515 | 516 | return queryTime; 517 | } 518 | 519 | var updateLineChart = function(data, chartData, chart, labelFunc=identity) { 520 | var labels = chartData.labels; 521 | var serviceCallTimes = chartData.times; 522 | var serviceCallMap = chartData.values; 523 | 524 | var items = data.Items; 525 | 526 | for (var i=0; i 0) callTime = items[items.length-1].EventTime.split('.')[0]; 613 | else callTime = getTimeSecsAgo(20).split('.')[0]; 614 | totalCallCtx.innerHTML = "

Count: " + totalSuccessfulCalls + "

"; 615 | totalCallTimeCtx.innerHTML = "

Last Updated: " + callTime + " UTC

"; 616 | //totalCallCurrentTime = updateLineChart(data, labels, {"Total no of calls" : totalCalls}, quadChart, totalCallCurrentTime); 617 | } 618 | }); 619 | docClient.query(ipParams, function(err, data) { 620 | if (err) console.log(err); 621 | else { 622 | ipQueryTime = updateHorizontalBarChart(data, 5, osChart, ipQueryTime, splitFunc); 623 | } 624 | }); 625 | docClient.query(userParams, function(err, data) { 626 | if (err) console.log(err); 627 | else { 628 | userQueryTime = updateHorizontalBarChart(data, 5, userCallChart, userQueryTime, splitFunc); 629 | } 630 | }); 631 | 632 | while(isInFastUpdate); 633 | isInSlowUpdate = true; 634 | docClient.query(serviceTypeParams, function(err, data) { 635 | if (err) console.log(err); 636 | else { 637 | 638 | serviceCallChartData = updateLineChart(data, serviceCallChartData, serviceCallChart, splitFunc) ; 639 | } 640 | 641 | }); 642 | 643 | ec2CallQueryTime = getTimeSecsAgo(15*60); 644 | docClient.query(ec2Params, function(err, data) { 645 | if (err) console.log(err); 646 | else { 647 | ec2CallChartData = updateLineChart(data, ec2CallChartData, ec2CallChart, function(label) { result = label.split('|')[1]; if (result == "null") return "SuccessfulCalls"; else return "Failure calls: " + result;}) ; 648 | 649 | } 650 | }); 651 | isInSlowUpdate = false; 652 | 653 | docClient.query(apiParams, function(err, data) { 654 | if (err) console.log(err); 655 | else { 656 | apiQueryTime = updateHorizontalBarChart(data, 10, apiCallChart, apiQueryTime); 657 | } 658 | }); 659 | docClient.query(maxIpParams, function(err, data) { 660 | if (err) console.log(err); 661 | else { 662 | var items = data.Items; 663 | for (var i=0; i0) { 668 | maxIpQueryTime = items[items.length-1].Hour+":"+items[items.length-1].Minute+":00.000"; 669 | updateData(maxIpChart, maxIpCallLabels, Object.values(maxIpCallMap), Object.keys(maxIpCallMap)); 670 | } 671 | else { 672 | var defaultTime = getTimeSecsAgo(30); 673 | if (maxIpQueryTime < defaultTime) maxIpQueryTime = defaultTime; 674 | } 675 | } 676 | }); 677 | 678 | 679 | setTimeout( function() { 680 | updateDashboard(); 681 | }, 60000); 682 | } 683 | 684 | var fastUpdate = function() { 685 | var docClient = new AWS.DynamoDB.DocumentClient(); 686 | 687 | var serviceTypeParams = retrieveParams("CallsPerServiceType", serviceCallQueryTime); 688 | 689 | while(isInSlowUpdate); 690 | isInFastUpdate = true; 691 | docClient.query(serviceTypeParams, function(err, data) { 692 | if (err) console.log(err); 693 | else { 694 | serviceCallQueryTime = fastUpdateLineChart(data, serviceCallChartData, serviceCallChart, serviceCallQueryTime, splitFunc) ; 695 | } 696 | 697 | }); 698 | 699 | 700 | var ec2Params = retrieveParams("EC2Calls", ec2CallQueryTime); 701 | docClient.query(ec2Params, function(err, data) { 702 | if (err) console.log(err); 703 | else { 704 | //console.log(ec2CallChartData); 705 | 706 | ec2CallQueryTime = fastUpdateLineChart(data, ec2CallChartData, ec2CallChart, ec2CallQueryTime, function(label) { result = label.split('|')[1]; if (result == "null") return "SuccessfulCalls"; else return "Failure calls: " + result;}) ; 707 | } 708 | }); 709 | isInFastUpdate = false; 710 | var anomalyParams = retrieveParams("AnomalyScore", anomalyScoreCurrentTime); 711 | 712 | docClient.query(anomalyParams, function(err, data) { 713 | if (err) console.log(err); 714 | else { 715 | var items = data.Items; 716 | for (var i=0; i0) { 724 | anomalyScoreCurrentTime = items[items.length-1].EventTime; 725 | updateData(anomalyChart, anomalyCallLabels, Object.values(anomalyCallMap), Object.keys(anomalyCallMap), true); 726 | } 727 | } 728 | }); 729 | setTimeout( function() { 730 | fastUpdate(); 731 | }, 10000); 732 | 733 | } 734 | var cognitoAuth = function() { 735 | 736 | $("#logoutLink").click( function() { 737 | cognitoUser.signOut(); 738 | 739 | $("#password").val(""); 740 | $("#loginForm").removeClass("hidden"); 741 | $("#logoutLink").addClass("hidden"); 742 | $("#unauthMessage").removeClass("hidden"); 743 | $("#dashboard_content").addClass("hidden"); 744 | }); 745 | $("#btnSaveConfiguration").click(function (e) { 746 | 747 | var clientId = $("#clientId").val(), 748 | userPoolId = $("#userPoolId").val(), 749 | identityPoolId = $("#identityPoolId").val(), 750 | userPoolRegion = $("#userPoolRegion").val(); 751 | 752 | if(clientId && userPoolId && identityPoolId && userPoolRegion){ 753 | $("#configErr").addClass("hidden"); 754 | localStorage.setItem(clientIdParamName, clientId); 755 | localStorage.setItem(userPoolIdParamName, userPoolId); 756 | localStorage.setItem(identityPoolIdParamName, identityPoolId); 757 | localStorage.setItem(cognitoRegionParamName, userPoolRegion); 758 | $("#cognitoModal").modal("hide"); 759 | 760 | } 761 | else { 762 | $("#configErr").removeClass("hidden"); 763 | } 764 | 765 | }); 766 | function refreshAuthentication(userPool, userData) { 767 | var cognitoUser = new AmazonCognitoIdentity.CognitoUser(userData); 768 | cognitoUser.authenticateUser( authDetails, { 769 | onSuccess: function(result) { 770 | var logins = {}; 771 | logins["cognito-idp." + cognitoRegion + ".amazonaws.com/" + cognitoUserPoolId] = result.getIdToken().getJwtToken(); 772 | var params = { 773 | IdentityPoolId: cognitoIdentityPoolId, 774 | Logins: logins 775 | }; 776 | 777 | AWS.config.region = cognitoRegion; 778 | AWSCognito.config.region = cognitoRegion; 779 | 780 | AWS.config.credentials = new AWS.CognitoIdentityCredentials(params); 781 | 782 | AWS.config.credentials.get(function(refreshErr) { 783 | if(refreshErr) { 784 | console.error(refreshErr); 785 | } 786 | else { 787 | setTimeout( function() { 788 | refreshAuthentication(userPool, userData); 789 | }, 3600*1000); 790 | 791 | } 792 | }); 793 | 794 | }, 795 | onFailure: function(err) { 796 | alert(err); 797 | } 798 | 799 | }); 800 | } 801 | 802 | $("#btnSavePassword").click(function (e) { 803 | var newPassword = $("#newPassword").val(); 804 | 805 | if(newPassword.length >= 8 && newPassword.match(/[a-z]/) && newPassword.match(/[A-Z]/) && newPassword.match(/[0-9]/) && newPassword == $("#newPassword2").val()) { 806 | $("#newPasswordModal").modal("hide"); 807 | $("#newPasswordErr").addClass("hidden"); 808 | $("#newPasswordMatchErr").addClass("hidden"); 809 | $("#newPasswordComplexityErr").addClass("hidden"); 810 | $("#btnLogin").trigger("click"); 811 | } else { 812 | $("#newPasswordErr").removeClass("hidden"); 813 | if(newPassword != $("#newPassword2").val()) { 814 | $("#newPasswordMatchErr").removeClass("hidden"); 815 | } else { 816 | $("#newPasswordMatchErr").addClass("hidden"); 817 | } 818 | if(newPassword.length < 8 || !newPassword.match(/[a-z]/) || !newPassword.match(/[A-Z]/) || !newPassword.match(/[0-9]/)) { 819 | $("#newPasswordComplexityErr").removeClass("hidden"); 820 | if(newPassword.length < 8 ) { 821 | $("#newPasswordLengthErr").removeClass("hidden"); 822 | } else { 823 | $("#newPasswordLengthErr").addClass("hidden"); 824 | } 825 | if(!newPassword.match(/[a-z]/)) { 826 | $("#newPasswordLowerErr").removeClass("hidden"); 827 | } else { 828 | $("#newPasswordLowerErr").addClass("hidden"); 829 | } 830 | if(!newPassword.match(/[A-Z]/)) { 831 | $("#newPasswordUpperErr").removeClass("hidden"); 832 | } else { 833 | $("#newPasswordUpperErr").addClass("hidden"); 834 | } 835 | if(!newPassword.match(/[0-9]/)) { 836 | $("#newPasswordNumberErr").removeClass("hidden"); 837 | } else { 838 | $("#newPasswordNumberErr").addClass("hidden"); 839 | } 840 | } else { 841 | $("#newPasswordComplexityErr").addClass("hidden"); 842 | } 843 | } 844 | }); 845 | 846 | $("#btnLogin").click(function() { 847 | //validate that the Cognito configuration parameters have been set 848 | if(!cognitoAppClientId || !cognitoUserPoolId || !cognitoIdentityPoolId || !cognitoRegion) { 849 | 850 | $("#configErr").removeClass("hidden"); 851 | $("#configureLink").trigger("click"); 852 | return; 853 | } 854 | 855 | //update ui 856 | $("#loginForm").addClass("hidden"); 857 | $("#signInSpinner").removeClass("hidden"); 858 | 859 | var userName = $("#userName").val(); 860 | var password = $("#password").val(); 861 | var newPassword = $("#newPassword").val(); 862 | 863 | var authData = { 864 | UserName: userName, 865 | Password: password 866 | }; 867 | 868 | var authDetails = new AmazonCognitoIdentity.AuthenticationDetails(authData); 869 | 870 | var poolData = { 871 | UserPoolId: cognitoUserPoolId, 872 | ClientId: cognitoAppClientId 873 | }; 874 | 875 | var userPool = new AmazonCognitoIdentity.CognitoUserPool(poolData); 876 | var userData = { 877 | Username: userName, 878 | Pool: userPool 879 | }; 880 | 881 | cognitoUser = new AmazonCognitoIdentity.CognitoUser(userData); 882 | cognitoUser.authenticateUser( authDetails, { 883 | onSuccess: function(result) { 884 | 885 | var logins = {}; 886 | logins["cognito-idp." + cognitoRegion + ".amazonaws.com/" + cognitoUserPoolId] = result.getIdToken().getJwtToken(); 887 | var params = { 888 | IdentityPoolId: cognitoIdentityPoolId, 889 | Logins: logins 890 | }; 891 | 892 | AWS.config.region = cognitoRegion; 893 | AWSCognito.config.region = cognitoRegion; 894 | 895 | AWS.config.credentials = new AWS.CognitoIdentityCredentials(params); 896 | 897 | AWS.config.credentials.get(function(refreshErr) { 898 | if(refreshErr) { 899 | console.error(refreshErr); 900 | } 901 | else { 902 | $("#unauthMessage").addClass("hidden"); 903 | $("#logoutLink").removeClass("hidden"); 904 | $("#dashboard_content").removeClass("hidden"); 905 | $("#signInSpinner").addClass("hidden"); 906 | updateDashboard(); 907 | setTimeout( function() { 908 | fastUpdate(); 909 | }, 10000); 910 | setTimeout( function() { 911 | refreshAuthentication(userPool, userData); 912 | }, 3600*1000); 913 | 914 | } 915 | }); 916 | 917 | }, 918 | onFailure: function(err) { 919 | $("#logoutLink").addClass("hidden"); 920 | $("#loginForm").removeClass("hidden"); 921 | $("#signInSpinner").addClass("hidden"); 922 | 923 | alert(err); 924 | }, 925 | newPasswordRequired: function(userAttributes, requiredAttributes) { 926 | // User was signed up by an admin and must provide new 927 | // password and required attributes, if any, to complete 928 | // authentication. 929 | console.log("New Password Required"); 930 | 931 | var attributesData = {}; 932 | if (newPassword.length >= 8 && newPassword.match(/[a-z]/) && newPassword.match(/[A-Z]/) && newPassword.match(/[0-9]/) && newPassword == $("#newPassword2").val()) { 933 | cognitoUser.completeNewPasswordChallenge(newPassword, attributesData, this) 934 | } else { 935 | $("#newPasswordModal").modal("show"); 936 | } 937 | } 938 | }); 939 | }); 940 | } 941 | 942 | cognitoAuth(); 943 | 944 | function timeNow() { 945 | var d = new Date(), 946 | h = (d.getHours()<10?'0':'') + d.getHours(), 947 | m = (d.getMinutes()<10?'0':'') + d.getMinutes(), 948 | s = (d.getSeconds()<10?'0':'') + d.getSeconds(); 949 | 950 | return h + ':' + m + ':' + s; 951 | } 952 | 953 | } 954 | -------------------------------------------------------------------------------- /source/web_site/js/amazon-cognito-identity.min.js: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2016 Amazon.com, 3 | * Inc. or its affiliates. All Rights Reserved. 4 | * 5 | * Licensed under the Amazon Software License (the "License"). 6 | * You may not use this file except in compliance with the 7 | * License. A copy of the License is located at 8 | * 9 | * http://aws.amazon.com/asl/ 10 | * 11 | * or in the "license" file accompanying this file. This file is 12 | * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR 13 | * CONDITIONS OF ANY KIND, express or implied. See the License 14 | * for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | !function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t(require("aws-sdk/global"),require("aws-sdk/clients/cognitoidentityserviceprovider")):"function"==typeof define&&define.amd?define(["aws-sdk/global","aws-sdk/clients/cognitoidentityserviceprovider"],t):"object"==typeof exports?exports.AmazonCognitoIdentity=t(require("aws-sdk/global"),require("aws-sdk/clients/cognitoidentityserviceprovider")):e.AmazonCognitoIdentity=t(e.AWSCognito,e.AWSCognito.CognitoIdentityServiceProvider)}(this,function(e,t){return function(e){function t(i){if(n[i])return n[i].exports;var s=n[i]={exports:{},id:i,loaded:!1};return e[i].call(s.exports,s,s.exports,t),s.loaded=!0,s.exports}var n={};return t.m=e,t.c=n,t.p="",t(0)}([function(e,t,n){"use strict";function i(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return t.default=e,t}function s(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var r=n(15);Object.keys(r).forEach(function(e){"default"!==e&&"__esModule"!==e&&Object.defineProperty(t,e,{enumerable:!0,get:function(){return r[e]}})});var o=n(12),a=s(o),u=i(r);Object.keys(u).forEach(function(e){a.default[e]=u[e]}),"undefined"!=typeof window&&!window.crypto&&window.msCrypto&&(window.crypto=window.msCrypto)},function(t,n){t.exports=e},function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{default:e}}function s(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(t,"__esModule",{value:!0});var r=function(){function e(e,t){for(var n=0;n=0;){var o=t*this[e++]+n[i]+s;s=Math.floor(o/67108864),n[i++]=67108863&o}return s}function r(e){return J.charAt(e)}function o(e,t){var n=G[e.charCodeAt(t)];return null==n?-1:n}function a(e){for(var t=this.t-1;t>=0;--t)e[t]=this[t];e.t=this.t,e.s=this.s}function u(e){this.t=1,this.s=e<0?-1:0,e>0?this[0]=e:e<-1?this[0]=e+this.DV:this.t=0}function l(e){var t=i();return t.fromInt(e),t}function c(e,t){var i;if(16==t)i=4;else if(8==t)i=3;else if(2==t)i=1;else if(32==t)i=5;else{if(4!=t)throw new Error("Only radix 2, 4, 8, 16, 32 are supported");i=2}this.t=0,this.s=0;for(var s=e.length,r=!1,a=0;--s>=0;){var u=o(e,s);u<0?"-"==e.charAt(s)&&(r=!0):(r=!1,0==a?this[this.t++]=u:a+i>this.DB?(this[this.t-1]|=(u&(1<>this.DB-a):this[this.t-1]|=u<=this.DB&&(a-=this.DB))}this.clamp(),r&&n.ZERO.subTo(this,this)}function h(){for(var e=this.s&this.DM;this.t>0&&this[this.t-1]==e;)--this.t}function f(e){if(this.s<0)return"-"+this.negate().toString();var t;if(16==e)t=4;else if(8==e)t=3;else if(2==e)t=1;else if(32==e)t=5;else{if(4!=e)throw new Error("Only radix 2, 4, 8, 16, 32 are supported");t=2}var n,i=(1<0)for(u>u)>0&&(s=!0,o=r(n));a>=0;)u>(u+=this.DB-t)):(n=this[a]>>(u-=t)&i,u<=0&&(u+=this.DB,--a)),n>0&&(s=!0),s&&(o+=r(n));return s?o:"0"}function d(){var e=i();return n.ZERO.subTo(this,e),e}function v(){return this.s<0?this.negate():this}function g(e){var t=this.s-e.s;if(0!=t)return t;var n=this.t;if(t=n-e.t,0!=t)return this.s<0?-t:t;for(;--n>=0;)if(0!=(t=this[n]-e[n]))return t;return 0}function m(e){var t,n=1;return 0!=(t=e>>>16)&&(e=t,n+=16),0!=(t=e>>8)&&(e=t,n+=8),0!=(t=e>>4)&&(e=t,n+=4),0!=(t=e>>2)&&(e=t,n+=2),0!=(t=e>>1)&&(e=t,n+=1),n}function p(){return this.t<=0?0:this.DB*(this.t-1)+m(this[this.t-1]^this.s&this.DM)}function y(e,t){var n;for(n=this.t-1;n>=0;--n)t[n+e]=this[n];for(n=e-1;n>=0;--n)t[n]=0;t.t=this.t+e,t.s=this.s}function S(e,t){for(var n=e;n=0;--n)t[n+o+1]=this[n]>>s|a,a=(this[n]&r)<=0;--n)t[n]=0;t[o]=a,t.t=this.t+o+1,t.s=this.s,t.clamp()}function w(e,t){t.s=this.s;var n=Math.floor(e/this.DB);if(n>=this.t)return void(t.t=0);var i=e%this.DB,s=this.DB-i,r=(1<>i;for(var o=n+1;o>i;i>0&&(t[this.t-n-1]|=(this.s&r)<>=this.DB;if(e.t>=this.DB;i+=this.s}else{for(i+=this.s;n>=this.DB;i-=e.s}t.s=i<0?-1:0,i<-1?t[n++]=this.DV+i:i>0&&(t[n++]=i),t.t=n,t.clamp()}function A(e,t){var i=this.abs(),s=e.abs(),r=i.t;for(t.t=r+s.t;--r>=0;)t[r]=0;for(r=0;r=0;)e[n]=0;for(n=0;n=t.DV&&(e[n+t.t]-=t.DV,e[n+t.t+1]=1)}e.t>0&&(e[e.t-1]+=t.am(n,t[n],e,2*n,0,1)),e.s=0,e.clamp()}function U(e,t,s){var r=e.abs();if(!(r.t<=0)){var o=this.abs();if(o.t0?(r.lShiftTo(c,a),o.lShiftTo(c,s)):(r.copyTo(a),o.copyTo(s));var h=a.t,f=a[h-1];if(0!=f){var d=f*(1<1?a[h-2]>>this.F2:0),v=this.FV/d,g=(1<=0&&(s[s.t++]=1,s.subTo(C,s)),n.ONE.dlShiftTo(h,C),C.subTo(a,a);a.t=0;){var w=s[--y]==f?this.DM:Math.floor(s[y]*v+(s[y-1]+p)*g);if((s[y]+=a.am(0,w,s,S,0,h))0&&s.rShiftTo(c,s),u<0&&n.ZERO.subTo(s,s)}}}function E(e){var t=i();return this.abs().divRemTo(e,null,t),this.s<0&&t.compareTo(n.ZERO)>0&&e.subTo(t,t),t}function D(){if(this.t<1)return 0;var e=this[0];if(0==(1&e))return 0;var t=3&e;return t=t*(2-(15&e)*t)&15,t=t*(2-(255&e)*t)&255,t=t*(2-((65535&e)*t&65535))&65535,t=t*(2-e*t%this.DV)%this.DV,t>0?this.DV-t:-t}function I(e){return 0==this.compareTo(e)}function b(e,t){for(var n=0,i=0,s=Math.min(e.t,this.t);n>=this.DB;if(e.t>=this.DB;i+=this.s}else{for(i+=this.s;n>=this.DB;i+=e.s}t.s=i<0?-1:0,i>0?t[n++]=i:i<-1&&(t[n++]=this.DV+i),t.t=n,t.clamp()}function P(e){var t=i();return this.addTo(e,t),t}function R(e){var t=i();return this.subTo(e,t),t}function F(e){var t=i();return this.multiplyTo(e,t),t}function _(e){var t=i();return this.divRemTo(e,t,null),t}function B(e){this.m=e,this.mp=e.invDigit(),this.mpl=32767&this.mp,this.mph=this.mp>>15,this.um=(1<0&&this.m.subTo(t,t),t}function M(e){var t=i();return e.copyTo(t),this.reduce(t),t}function N(e){for(;e.t<=this.mt2;)e[e.t++]=0;for(var t=0;t>15)*this.mpl&this.um)<<15)&e.DM;for(n=t+this.m.t,e[n]+=this.m.am(0,i,e,t,0,this.m.t);e[n]>=e.DV;)e[n]-=e.DV,e[++n]++}e.clamp(),e.drShiftTo(this.m.t,e),e.compareTo(this.m)>=0&&e.subTo(this.m,e)}function V(e,t){e.squareTo(t),this.reduce(t)}function K(e,t,n){e.multiplyTo(t,n),this.reduce(n)}function q(e,t){var n,s=e.bitLength(),r=l(1),o=new B(t);if(s<=0)return r;n=s<18?1:s<48?3:s<144?4:s<768?5:6;var a=new Array,u=3,c=n-1,h=(1<1){var f=i();for(o.sqrTo(a[1],f);u<=h;)a[u]=i(),o.mulTo(f,a[u-2],a[u]),u+=2}var d,v,g=e.t-1,p=!0,y=i();for(s=m(e[g])-1;g>=0;){for(s>=c?d=e[g]>>s-c&h:(d=(e[g]&(1<0&&(d|=e[g-1]>>this.DB+s-c)),u=n;0==(1&d);)d>>=1,--u;if((s-=u)<0&&(s+=this.DB,--g),p)a[d].copyTo(r),p=!1;else{for(;u>1;)o.sqrTo(r,y),o.sqrTo(y,r),u-=2;u>0?o.sqrTo(r,y):(v=r,r=y,y=v),o.mulTo(y,a[d],r)}for(;g>=0&&0==(e[g]&1<0&&void 0!==arguments[0]?arguments[0]:{},n=t.AccessToken;i(this,e),this.jwtToken=n||""}return s(e,[{key:"getJwtToken",value:function(){return this.jwtToken}},{key:"getExpiration",value:function(){var e=this.jwtToken.split(".")[1],t=JSON.parse(r.util.base64.decode(e).toString("utf8"));return t.exp}}]),e}();t.default=o},function(e,t,n){"use strict";function i(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(t,"__esModule",{value:!0});var s=function(){function e(e,t){for(var n=0;n0&&void 0!==arguments[0]?arguments[0]:{},n=t.IdToken;i(this,e),this.jwtToken=n||""}return s(e,[{key:"getJwtToken",value:function(){return this.jwtToken}},{key:"getExpiration",value:function(){var e=this.jwtToken.split(".")[1],t=JSON.parse(r.util.base64.decode(e).toString("utf8"));return t.exp}}]),e}();t.default=o},function(e,t){"use strict";function n(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(t,"__esModule",{value:!0});var i=function(){function e(e,t){for(var n=0;n0&&void 0!==arguments[0]?arguments[0]:{},i=t.RefreshToken;n(this,e),this.token=i||""}return i(e,[{key:"getToken",value:function(){return this.token}}]),e}();t.default=s},function(e,t,n){"use strict";function i(e){return e&&e.__esModule?e:{default:e}}function s(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(t,"__esModule",{value:!0});var r=function(){function e(e,t){for(var n=0;n0&&void 0!==arguments[0]?arguments[0]:{},i=t.Name,s=t.Value;n(this,e),this.Name=i||"",this.Value=s||""}return i(e,[{key:"getValue",value:function(){return this.Value}},{key:"setValue",value:function(e){return this.Value=e,this}},{key:"getName",value:function(){return this.Name}},{key:"setName",value:function(e){return this.Name=e,this}},{key:"toString",value:function(){return JSON.stringify(this)}},{key:"toJSON",value:function(){return{Name:this.Name,Value:this.Value}}}]),e}();t.default=s},function(e,t){"use strict";function n(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(t,"__esModule",{value:!0});var i=function(){function e(e,t){for(var n=0;n0&&void 0!==arguments[0]?arguments[0]:{},i=t.IdToken,s=t.RefreshToken,r=t.AccessToken;if(n(this,e),null==r||null==i)throw new Error("Id token and Access Token must be present.");this.idToken=i,this.refreshToken=s,this.accessToken=r}return i(e,[{key:"getIdToken",value:function(){return this.idToken}},{key:"getRefreshToken",value:function(){return this.refreshToken}},{key:"getAccessToken",value:function(){return this.accessToken}},{key:"isValid",value:function(){var e=Math.floor(new Date/1e3);return e