├── .gitignore ├── LICENSE ├── README.md ├── app ├── app.js ├── controllers │ ├── confirm.js │ ├── loggedIn.js │ ├── register.js │ └── signIn.js ├── factories │ └── utils.js ├── services │ └── AuthService.js └── views │ ├── confirm.html │ ├── loggedIn.html │ ├── register.html │ └── signIn.html ├── bower.json ├── img └── arch_diagram.png ├── index.html └── lib ├── aws-variables.js ├── cognito ├── amazon-cognito-identity.min.js ├── amazon-cognito-identity.min.js.map ├── aws-cognito-sdk.min.js └── aws-cognito-sdk.min.js.map ├── jsbn ├── LICENSE ├── jsbn.js └── jsbn2.js └── sjcl ├── LICENSE.txt └── sjcl.js /.gitignore: -------------------------------------------------------------------------------- 1 | # See http://help.github.com/ignore-files/ for more about ignoring files. 2 | 3 | # dependencies 4 | /bower_components 5 | 6 | # IDEs and editors 7 | /.idea 8 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 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 | Copyright 2016 Amazon Web Services 177 | 178 | Licensed under the Apache License, Version 2.0 (the "License"); 179 | you may not use this file except in compliance with the License. 180 | You may obtain a copy of the License at 181 | 182 | http://www.apache.org/licenses/LICENSE-2.0 183 | 184 | Unless required by applicable law or agreed to in writing, software 185 | distributed under the License is distributed on an "AS IS" BASIS, 186 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 187 | See the License for the specific language governing permissions and 188 | limitations under the License. 189 | 190 | Note: Other license terms may apply to certain, identified software files 191 | contained within or distributed with the accompanying software if such terms 192 | are included in the directory containing the accompanying software. 193 | Such other license terms will then apply in lieu of the terms 194 | of the software license above. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Building fine-grained authorization using Amazon Cognito User Pools groups 2 | 3 | **This Angular.js application** is a reference web app that allows users to explore the use of groups in Amazon Cognito User Pools, together with Amazon Cognito Federated Identities identity pools, to obtain temporary IAM credentials in your web app. 4 | The IAM credentials map to privileges that a user obtains after successfully authenticating with a user pool. Those privileges are determined by the role that is mapped to the user pool group that the user belongs to. 5 | User pools provide flexibility. You can use them to implement granular authorization architectures for authenticated users. 6 | The project code is released under the Apache 2.0 license. 7 | Please feel free to make use of the code in this project, and spread the word. 8 | We hope you enjoy it, and we certainly welcome all feedback, pull requests and other contributions! 9 | 10 | 11 | ## Architecture diagram 12 |  13 | 14 | ## AWS services used 15 | 16 | This sample is built using the following AWS services: 17 | 18 | * [AWS Cognito](https://aws.amazon.com/cognito/) - Amazon Cognito lets you easily add user sign-up and sign-in to your mobile and web apps. With Amazon Cognito, you also have the options to authenticate users through social identity providers such as Facebook, Twitter, or Amazon, with SAML identity solutions, or by using your own identity system. Furthermore, AWS Cognito supports User Groups that let to create collections of users to manage their permissions or to represent different types of users. 19 | * [Amazon DynamoDB](https://aws.amazon.com/dynamodb/) - Amazon DynamoDB is a fast and flexible NoSQL database service for all applications that need consistent, single-digit millisecond latency at any scale. It is a fully managed cloud database and supports both document and key-value store models. 20 | 21 | ## Get started 22 | 23 | #### Instructions to install dependencies and populate constants 24 | 25 | * Run `bower install` from the root of your directory once you clone this project. 26 | * Navigate to `lib/aws-variables.js` and populate your own details. More detailed instructions can be found in the [Building fine-grained authorization using Amazon Cognito User Pools groups](https://aws.amazon.com/blogs/mobile/building-fine-grained-authorization-using-amazon-cognito-user-pools-groups/) blog. 27 | -------------------------------------------------------------------------------- /app/app.js: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2017 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 with the License. A copy of the License is located at 5 | 6 | http://aws.amazon.com/apache2.0/ 7 | 8 | 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. 9 | */ 10 | 11 | angular.module('cognitoBlog', ['ngRoute','cognitoBlog.authService','cognitoBlog.login','cognitoBlog.register', 'cognitoBlog.confirm', 'cognitoBlog.loggedIn']) 12 | 13 | .config(function($routeProvider) { 14 | $routeProvider 15 | .when("/", { 16 | templateUrl : "app/views/signIn.html", 17 | controller:"signInController" 18 | }) 19 | .when("/register", { 20 | templateUrl : "app/views/register.html", 21 | controller:"registerController" 22 | }) 23 | .when("/confirm", { 24 | templateUrl : "app/views/confirm.html", 25 | controller:"confirmController" 26 | }) 27 | .when("/loggedIn", { 28 | templateUrl : "app/views/loggedIn.html", 29 | controller:"loggedInController" 30 | }) 31 | }); -------------------------------------------------------------------------------- /app/controllers/confirm.js: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2017 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 with the License. A copy of the License is located at 5 | 6 | http://aws.amazon.com/apache2.0/ 7 | 8 | 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. 9 | */ 10 | angular.module('cognitoBlog.confirm', ['cognitoBlog.authService']) 11 | .controller('confirmController', function($scope, $location, authService) { 12 | 13 | //calling the confirm method from AuthService in order to confirm the user 14 | $scope.confirmAccount = function(newuser, isValid) { 15 | console.log(newuser); 16 | if (isValid) { 17 | newuser.username = newuser.email.replace("@", "_").replace(".", "_"); 18 | console.log("Confirmation code " + newuser.confirmCode); 19 | 20 | authService.confirm(newuser).then(function(){ 21 | $location.path('/'); 22 | }, function(msg) { 23 | $scope.errormessage = "An unexpected error has occurred. Please try again."; 24 | $scope.$apply(); 25 | return; 26 | }); 27 | 28 | } else { 29 | $scope.errormessage = "There are still invalid fields."; 30 | $scope.$apply(); 31 | } 32 | }; 33 | }); -------------------------------------------------------------------------------- /app/controllers/loggedIn.js: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2017 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 with the License. A copy of the License is located at 5 | 6 | http://aws.amazon.com/apache2.0/ 7 | 8 | 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. 9 | */ 10 | angular.module('cognitoBlog.loggedIn', ['cognitoBlog.authService']) 11 | .controller('loggedInController', function($scope, $location, authService) { 12 | 13 | 14 | //calling the isAuthenticated method from AuthService in order to add the user to DynamoDB table if not exists already 15 | if (true) { 16 | authService.isAuthenticated().then(function(result) { 17 | console.log(result); 18 | 19 | }, function(msg) { 20 | console.log(msg); 21 | $scope.errormessage = "Unable to access DynamoDB"; 22 | 23 | if ($scope.$$phase != '$digest') { 24 | $scope.$apply(); 25 | } 26 | return; 27 | }); 28 | } else { 29 | $scope.errormessage = "Some error happened"; 30 | 31 | }; 32 | 33 | 34 | $scope.status=""; 35 | 36 | //calling the updateItemDynamo method from AuthService in order to update the Status attribute for a given user 37 | $scope.replaceDynamoDBItem = function(isValid, status) { 38 | 39 | if (isValid) { 40 | authService.updateItemDynamo(status).then(function(result) { 41 | console.log(result); 42 | }, function(msg) { 43 | console.log(msg); 44 | $scope.errormessage = "Unable to access DynamoDB"; 45 | 46 | if ($scope.$$phase != '$digest') { 47 | $scope.$apply(); 48 | } 49 | return; 50 | }); 51 | } else { 52 | $scope.errormessage = "Some error happened"; 53 | 54 | } 55 | }; 56 | 57 | //calling the scanDynamoDB method from the AuthService in order to scan the Dynamo DB items 58 | $scope.scanDynamoDBItems = function(isValid) { 59 | 60 | if (isValid) { 61 | 62 | authService.scanDynamoDB().then(function(result) { 63 | console.log(result); 64 | 65 | }, function(msg) { 66 | console.log(msg); 67 | $scope.errormessage = "Unable to access DynamoDB"; 68 | 69 | if ($scope.$$phase != '$digest') { 70 | $scope.$apply(); 71 | } 72 | return; 73 | }); 74 | } else { 75 | $scope.errormessage = "Some error happened"; 76 | 77 | } 78 | }; 79 | 80 | $scope.logout = function() { 81 | authService.logOut(); 82 | $location.path('/'); 83 | } 84 | 85 | 86 | }); 87 | 88 | 89 | -------------------------------------------------------------------------------- /app/controllers/register.js: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2017 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 with the License. A copy of the License is located at 5 | 6 | http://aws.amazon.com/apache2.0/ 7 | 8 | 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. 9 | */ 10 | angular.module('cognitoBlog.register', ['cognitoBlog.authService']) 11 | .controller('registerController', function($scope, $location, authService) { 12 | 13 | $scope.errormessage=""; 14 | 15 | 16 | //calling the signup method from AuthService to register a user 17 | $scope.register = function(newuser, isValid) { 18 | console.log(newuser); 19 | 20 | if (isValid) { 21 | 22 | authService.signup(newuser).then(function() { 23 | 24 | $location.path('/confirm'); 25 | }, function(msg) { 26 | $scope.errormessage = "An unexpected error has occurred. Please try again."; 27 | 28 | $scope.$apply(); 29 | return; 30 | }); 31 | 32 | } else { 33 | $scope.errormessage = "There are still invalid fields."; 34 | 35 | $scope.$apply(); 36 | } 37 | } 38 | 39 | }); 40 | 41 | 42 | -------------------------------------------------------------------------------- /app/controllers/signIn.js: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2017 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 with the License. A copy of the License is located at 5 | 6 | http://aws.amazon.com/apache2.0/ 7 | 8 | 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. 9 | */ 10 | 11 | angular.module('cognitoBlog.login', ['cognitoBlog.authService']) 12 | .controller('signInController', function($scope, $location, authService) { 13 | 14 | $scope.changeView = function(view){ 15 | $location.path(view); // path not hash 16 | }; 17 | 18 | //calling the signin method from AuthService to sign in the user to the application 19 | $scope.login = function(user, isValid) { 20 | 21 | if (isValid) { 22 | authService.signin(user).then(function(result) { 23 | console.log('Id Token: ' + result.getIdToken().getJwtToken()); 24 | $location.path('/loggedIn'); 25 | }, function(msg) { 26 | console.log(msg); 27 | if ($scope.$$phase != '$digest') { 28 | $scope.$apply(); 29 | } 30 | return; 31 | }); 32 | } else { 33 | console.log("Probably you have provided invalid login fields"); 34 | 35 | } 36 | }; 37 | 38 | 39 | }); 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | -------------------------------------------------------------------------------- /app/factories/utils.js: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2017 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 with the License. A copy of the License is located at 5 | 6 | http://aws.amazon.com/apache2.0/ 7 | 8 | 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. 9 | */ 10 | 11 | angular.module('cognitoBlog.utils', []) 12 | 13 | .factory('$_', function() { 14 | return window._; // assumes underscore has already been loaded on the page 15 | }) 16 | 17 | .factory('$localstorage', ['$window', function($window) { 18 | return { 19 | set: function(key, value) { 20 | $window.localStorage[key] = value; 21 | }, 22 | get: function(key, defaultValue) { 23 | return $window.localStorage[key] || defaultValue; 24 | }, 25 | setObject: function(key, value) { 26 | $window.localStorage[key] = JSON.stringify(value); 27 | }, 28 | getObject: function(key) { 29 | return JSON.parse($window.localStorage[key] || '{}'); 30 | } 31 | } 32 | }]); 33 | -------------------------------------------------------------------------------- /app/services/AuthService.js: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. 4 | 5 | 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 6 | 7 | http://aws.amazon.com/apache2.0/ 8 | 9 | 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. 10 | */ 11 | 12 | angular.module('cognitoBlog.authService', ['cognitoBlog.utils']) 13 | .service('authService', function($q, $_, $localstorage) { 14 | 15 | this.signup = function(newuser) { 16 | var deferred = $q.defer(); 17 | 18 | newuser.username = newuser.email.replace("@", "_").replace(".", "_"); 19 | 20 | var poolData = { 21 | UserPoolId: YOUR_USER_POOL_ID, 22 | ClientId: YOUR_USER_POOL_CLIENT_ID, 23 | Paranoia: 8 24 | }; 25 | var userPool = new AWSCognito.CognitoIdentityServiceProvider.CognitoUserPool(poolData); 26 | 27 | var attributeList = []; 28 | 29 | var dataEmail = { 30 | Name: 'email', 31 | Value: newuser.email 32 | }; 33 | 34 | var dataName = { 35 | Name: 'name', 36 | Value: newuser.name 37 | }; 38 | 39 | var attributeEmail = new AWSCognito.CognitoIdentityServiceProvider.CognitoUserAttribute(dataEmail); 40 | var attributeName = new AWSCognito.CognitoIdentityServiceProvider.CognitoUserAttribute(dataName); 41 | 42 | attributeList.push(attributeEmail); 43 | attributeList.push(attributeName); 44 | 45 | console.log("Submitting " + newuser.name); 46 | userPool.signUp(newuser.username, newuser.password, attributeList, null, function(err, result) { 47 | if (err) { 48 | console.log(err); 49 | deferred.reject(err.message); 50 | } else { 51 | deferred.resolve(result.user); 52 | } 53 | }); 54 | 55 | return deferred.promise; 56 | 57 | }; 58 | 59 | this.confirm = function(newuser) { 60 | var deferred = $q.defer(); 61 | 62 | var poolData = { 63 | UserPoolId: YOUR_USER_POOL_ID, 64 | ClientId: YOUR_USER_POOL_CLIENT_ID, 65 | Paranoia: 8 66 | }; 67 | 68 | var userPool = new AWSCognito.CognitoIdentityServiceProvider.CognitoUserPool(poolData); 69 | var userData = { 70 | Username: newuser.username, 71 | Pool: userPool 72 | }; 73 | 74 | var cognitoUser = new AWSCognito.CognitoIdentityServiceProvider.CognitoUser(userData); 75 | cognitoUser.confirmRegistration(newuser.confirmCode, true, function(err, result) { 76 | if (err) { 77 | console.log(err); 78 | deferred.reject(err); 79 | } 80 | deferred.resolve(); 81 | }); 82 | 83 | return deferred.promise; 84 | }; 85 | 86 | this.signin = function(user) { 87 | var deferred = $q.defer(); 88 | 89 | var authenticationData = { 90 | Username: user.email, 91 | Password: user.password 92 | }; 93 | 94 | var authenticationDetails = new AWSCognito.CognitoIdentityServiceProvider.AuthenticationDetails( 95 | authenticationData); 96 | var poolData = { 97 | UserPoolId: YOUR_USER_POOL_ID, 98 | ClientId: YOUR_USER_POOL_CLIENT_ID, 99 | Paranoia: 8 100 | }; 101 | 102 | var userPool = new AWSCognito.CognitoIdentityServiceProvider.CognitoUserPool(poolData); 103 | var userData = { 104 | Username: user.email, 105 | Pool: userPool 106 | }; 107 | 108 | var cognitoUser = new AWSCognito.CognitoIdentityServiceProvider.CognitoUser(userData); 109 | 110 | try { 111 | cognitoUser.authenticateUser(authenticationDetails, { 112 | onSuccess: function(result) { 113 | console.log(cognitoUser) 114 | //console.log('access token + ' + result.getIdToken().getJwtToken()); 115 | $localstorage.set('username', cognitoUser.getUsername()); 116 | deferred.resolve(result); 117 | }, 118 | 119 | onFailure: function(err) { 120 | deferred.reject(err); 121 | } 122 | 123 | }); 124 | } catch (e) { 125 | console.log(e); 126 | deferred.reject(e); 127 | } 128 | 129 | return deferred.promise; 130 | 131 | }; 132 | 133 | this.isAuthenticated = function() { 134 | var deferred = $q.defer(); 135 | var data = { 136 | UserPoolId: YOUR_USER_POOL_ID, 137 | ClientId: YOUR_USER_POOL_CLIENT_ID, 138 | Paranoia: 8 139 | }; 140 | var userPool = new AWSCognito.CognitoIdentityServiceProvider.CognitoUserPool(data); 141 | var cognitoUser = userPool.getCurrentUser(); 142 | 143 | try { 144 | if (cognitoUser != null) { 145 | cognitoUser.getSession(function(err, session) { 146 | if (err) { 147 | deferred.resolve(false); 148 | } 149 | 150 | deferred.resolve(true); 151 | 152 | console.log('session validity: ' + session.isValid()); 153 | 154 | console.log('session token: ' + session.getIdToken().getJwtToken()); 155 | 156 | var paramsCredentials = { 157 | IdentityPoolId : IDENTITY_POOL_ID, 158 | Logins : {} 159 | }; 160 | 161 | //passing dynamically the user pool id along with some constants 162 | paramsCredentials.Logins[YOUR_USER_POOL_ID_IDP] = session.getIdToken().getJwtToken(); 163 | 164 | AWS.config.region = 'eu-west-1'; 165 | AWS.config.credentials = new AWS.CognitoIdentityCredentials(paramsCredentials); 166 | 167 | AWS.config.credentials.clearCachedId(); 168 | AWS.config.credentials.get(function(err){ 169 | if (!err) { 170 | var id = AWS.config.credentials.identityId; 171 | console.log('Cognito Identity ID '+ id); 172 | 173 | // Instantiate aws sdk service objects now that the credentials have been updated 174 | var docClient = new AWS.DynamoDB.DocumentClient({ region: 'eu-west-1' }); 175 | 176 | var params = { 177 | TableName: ddbTable, 178 | Item:{userid: id} 179 | }; 180 | 181 | var paramsQuery = { 182 | TableName : ddbTable, 183 | KeyConditionExpression: "userid = :id", 184 | ExpressionAttributeValues: { 185 | ":id":id 186 | } 187 | }; 188 | 189 | //Query the table to identify if the user is in the table already. If the user is not in the table add his Cognito id as the hash key 190 | docClient.query(paramsQuery, function(err, data) { 191 | if (err) { 192 | console.error("Unable to query. Error:", JSON.stringify(err, null, 2)); 193 | } else { 194 | console.log("Query succeeded."); 195 | if( data.Items.length == 0) { 196 | console.log("User first time sign in - adding to table."); 197 | docClient.put(params, function (err, data) { 198 | if (err) console.log(err); 199 | else console.log(data); 200 | }); 201 | }else{ 202 | console.log("User exists in the table already."); 203 | } 204 | 205 | } 206 | }); 207 | 208 | 209 | 210 | } 211 | }); 212 | }); 213 | } else { 214 | deferred.resolve(false); 215 | } 216 | } catch (e) { 217 | console.log(e); 218 | deferred.resolve(false); 219 | } 220 | 221 | return deferred.promise; 222 | 223 | }; 224 | 225 | this.updateItemDynamo = function(status) { 226 | var deferred = $q.defer(); 227 | var data = { 228 | UserPoolId: YOUR_USER_POOL_ID, 229 | ClientId: YOUR_USER_POOL_CLIENT_ID, 230 | Paranoia: 8 231 | }; 232 | 233 | var userPool = new AWSCognito.CognitoIdentityServiceProvider.CognitoUserPool(data); 234 | var cognitoUser = userPool.getCurrentUser(); 235 | 236 | 237 | try { 238 | if (cognitoUser != null) { 239 | cognitoUser.getSession(function(err, session) { 240 | if (err) { 241 | deferred.resolve(false); 242 | } 243 | 244 | deferred.resolve(true); 245 | 246 | console.log('session validity: ' + session.isValid()); 247 | 248 | console.log('session token: ' + session.getIdToken().getJwtToken()); 249 | 250 | var paramsCredentials = { 251 | IdentityPoolId : IDENTITY_POOL_ID, 252 | Logins : {} 253 | }; 254 | 255 | //passing dynamically the user pool id along with some constants 256 | paramsCredentials.Logins[YOUR_USER_POOL_ID_IDP] = session.getIdToken().getJwtToken(); 257 | 258 | AWS.config.region = 'eu-west-1'; 259 | AWS.config.credentials = new AWS.CognitoIdentityCredentials(paramsCredentials); 260 | 261 | 262 | AWS.config.credentials.get(function(err){ 263 | 264 | if (!err) { 265 | var id = AWS.config.credentials.identityId; 266 | console.log('Cognito Identity ID '+ id); 267 | 268 | // Instantiate aws sdk service objects now that the credentials have been updated 269 | var docClient = new AWS.DynamoDB.DocumentClient({ region: 'eu-west-1' }); 270 | //var ddbTable = 'CognitoBlog'; 271 | 272 | var params = { 273 | TableName: ddbTable, 274 | Item:{userid:id, status:status} 275 | }; 276 | 277 | docClient.put(params, function(err, data) { 278 | if (err) console.log(err); 279 | else console.log(data); 280 | }); 281 | } 282 | }); 283 | }); 284 | } else { 285 | deferred.resolve(false); 286 | } 287 | } catch (e) { 288 | console.log(e); 289 | deferred.resolve(false); 290 | } 291 | 292 | return deferred.promise; 293 | 294 | }; 295 | 296 | 297 | this.scanDynamoDB = function() { 298 | var deferred = $q.defer(); 299 | var data = { 300 | UserPoolId: YOUR_USER_POOL_ID, 301 | ClientId: YOUR_USER_POOL_CLIENT_ID, 302 | Paranoia: 8 303 | }; 304 | var userPool = new AWSCognito.CognitoIdentityServiceProvider.CognitoUserPool(data); 305 | var cognitoUser = userPool.getCurrentUser(); 306 | 307 | try { 308 | if (cognitoUser != null) { 309 | cognitoUser.getSession(function(err, session) { 310 | if (err) { 311 | deferred.resolve(false); 312 | } 313 | 314 | deferred.resolve(true); 315 | 316 | console.log('session validity: ' + session.isValid()); 317 | 318 | console.log('session token: ' + session.getIdToken().getJwtToken()); 319 | 320 | var paramsCredentials = { 321 | IdentityPoolId : IDENTITY_POOL_ID, 322 | Logins : {} 323 | }; 324 | 325 | //passing dynamically the user pool id along with some constants 326 | paramsCredentials.Logins[YOUR_USER_POOL_ID_IDP] = session.getIdToken().getJwtToken(); 327 | 328 | AWS.config.region = 'eu-west-1'; 329 | AWS.config.credentials = new AWS.CognitoIdentityCredentials(paramsCredentials); 330 | 331 | AWS.config.credentials.get(function(err){ 332 | if (!err) { 333 | 334 | // Instantiate aws sdk service objects now that the credentials have been updated 335 | var docClient = new AWS.DynamoDB.DocumentClient({ region: 'eu-west-1' }); 336 | 337 | var params = { 338 | TableName: ddbTable 339 | }; 340 | 341 | docClient.scan(params, function(err, data) { 342 | if (err) console.log(err); 343 | else console.log(data); 344 | }); 345 | 346 | } 347 | }); 348 | 349 | 350 | 351 | 352 | }); 353 | } else { 354 | deferred.resolve(false); 355 | } 356 | } catch (e) { 357 | console.log(e); 358 | deferred.resolve(false); 359 | } 360 | 361 | return deferred.promise; 362 | 363 | }; 364 | 365 | this.logOut = function() { 366 | 367 | try { 368 | var data = { 369 | UserPoolId: YOUR_USER_POOL_ID, 370 | ClientId: YOUR_USER_POOL_CLIENT_ID, 371 | Paranoia: 8 372 | }; 373 | var userPool = new AWSCognito.CognitoIdentityServiceProvider.CognitoUserPool(data); 374 | var cognitoUser = userPool.getCurrentUser(); 375 | 376 | if (cognitoUser != null) { 377 | cognitoUser.signOut(); 378 | return true; 379 | } else { 380 | return false; 381 | } 382 | } catch (e) { 383 | console.log(e); 384 | return false; 385 | } 386 | 387 | }; 388 | 389 | this.getUserAccessToken = function() { 390 | var deferred = $q.defer(); 391 | 392 | var data = { 393 | UserPoolId: YOUR_USER_POOL_ID, 394 | ClientId: YOUR_USER_POOL_CLIENT_ID, 395 | Paranoia: 8 396 | }; 397 | 398 | var userPool = new AWSCognito.CognitoIdentityServiceProvider.CognitoUserPool(data); 399 | var cognitoUser = userPool.getCurrentUser(); 400 | 401 | if (cognitoUser != null) { 402 | 403 | cognitoUser.getSession(function(err, session) { 404 | if (err) { 405 | console.log(err); 406 | deferred.reject(err); 407 | } 408 | deferred.resolve(session.idToken); 409 | }); 410 | 411 | } else { 412 | deferred.reject(); 413 | } 414 | 415 | return deferred.promise; 416 | }; 417 | 418 | this.getUserAccessTokenWithUsername = function() { 419 | var deferred = $q.defer(); 420 | 421 | var data = { 422 | UserPoolId: YOUR_USER_POOL_ID, 423 | ClientId: YOUR_USER_POOL_CLIENT_ID, 424 | Paranoia: 8 425 | }; 426 | 427 | var userPool = new AWSCognito.CognitoIdentityServiceProvider.CognitoUserPool(data); 428 | var cognitoUser = userPool.getCurrentUser(); 429 | 430 | if (cognitoUser != null) { 431 | 432 | cognitoUser.getSession(function(err, session) { 433 | if (err) { 434 | console.log(err); 435 | deferred.reject(err); 436 | } 437 | deferred.resolve({ 438 | token: session.idToken, 439 | username: cognitoUser.username 440 | }); 441 | }); 442 | 443 | } else { 444 | deferred.reject(); 445 | } 446 | 447 | return deferred.promise; 448 | }; 449 | 450 | this.getUserInfo = function() { 451 | var deferred = $q.defer(); 452 | 453 | var userinfo = { 454 | email: "", 455 | name: "", 456 | username: "" 457 | }; 458 | var data = { 459 | UserPoolId: YOUR_USER_POOL_ID, 460 | ClientId: YOUR_USER_POOL_CLIENT_ID, 461 | Paranoia: 8 462 | }; 463 | 464 | var userPool = new AWSCognito.CognitoIdentityServiceProvider.CognitoUserPool(data); 465 | var cognitoUser = userPool.getCurrentUser(); 466 | 467 | if (cognitoUser != null) { 468 | 469 | cognitoUser.getSession(function(err, session) { 470 | if (err) { 471 | console.log(err); 472 | deferred.reject(err); 473 | } 474 | 475 | cognitoUser.getUserAttributes(function(err, result) { 476 | if (err) { 477 | console.log(err); 478 | deferred.reject(err); 479 | } 480 | 481 | var nm = $_.where(result, { 482 | Name: "name" 483 | }); 484 | if (nm.length > 0) { 485 | userinfo.name = nm[0].Value; 486 | } 487 | 488 | var em = $_.where(result, { 489 | Name: "email" 490 | }); 491 | if (em.length > 0) { 492 | userinfo.email = em[0].Value; 493 | } 494 | 495 | userinfo.username = cognitoUser.getUsername(); 496 | 497 | deferred.resolve(userinfo); 498 | 499 | }); 500 | }); 501 | } else { 502 | deferred.reject(); 503 | } 504 | 505 | return deferred.promise; 506 | 507 | } 508 | }); 509 | 510 | -------------------------------------------------------------------------------- /app/views/confirm.html: -------------------------------------------------------------------------------- 1 | 2 | 11 | 12 | 13 | 14 |
>(p+=this.DB-k);
191 | }
192 | else {
193 | d = (this[i]>>(p-=k))&km;
194 | if(p <= 0) { p += this.DB; --i; }
195 | }
196 | if(d > 0) m = true;
197 | if(m) r += int2char(d);
198 | }
199 | }
200 | return m?r:"0";
201 | }
202 |
203 | // (public) -this
204 | function bnNegate() { var r = nbi(); BigInteger.ZERO.subTo(this,r); return r; }
205 |
206 | // (public) |this|
207 | function bnAbs() { return (this.s<0)?this.negate():this; }
208 |
209 | // (public) return + if this > a, - if this < a, 0 if equal
210 | function bnCompareTo(a) {
211 | var r = this.s-a.s;
212 | if(r != 0) return r;
213 | var i = this.t;
214 | r = i-a.t;
215 | if(r != 0) return (this.s<0)?-r:r;
216 | while(--i >= 0) if((r=this[i]-a[i]) != 0) return r;
217 | return 0;
218 | }
219 |
220 | // returns bit length of the integer x
221 | function nbits(x) {
222 | var r = 1, t;
223 | if((t=x>>>16) != 0) { x = t; r += 16; }
224 | if((t=x>>8) != 0) { x = t; r += 8; }
225 | if((t=x>>4) != 0) { x = t; r += 4; }
226 | if((t=x>>2) != 0) { x = t; r += 2; }
227 | if((t=x>>1) != 0) { x = t; r += 1; }
228 | return r;
229 | }
230 |
231 | // (public) return the number of bits in "this"
232 | function bnBitLength() {
233 | if(this.t <= 0) return 0;
234 | return this.DB*(this.t-1)+nbits(this[this.t-1]^(this.s&this.DM));
235 | }
236 |
237 | // (protected) r = this << n*DB
238 | function bnpDLShiftTo(n,r) {
239 | var i;
240 | for(i = this.t-1; i >= 0; --i) r[i+n] = this[i];
241 | for(i = n-1; i >= 0; --i) r[i] = 0;
242 | r.t = this.t+n;
243 | r.s = this.s;
244 | }
245 |
246 | // (protected) r = this >> n*DB
247 | function bnpDRShiftTo(n,r) {
248 | for(var i = n; i < this.t; ++i) r[i-n] = this[i];
249 | r.t = Math.max(this.t-n,0);
250 | r.s = this.s;
251 | }
252 |
253 | // (protected) r = this << n
254 | function bnpLShiftTo(n,r) {
255 | var bs = n%this.DB;
256 | var cbs = this.DB-bs;
257 | var bm = (1< >(p+=this.DB-8);
121 | }
122 | else {
123 | d = (this[i]>>(p-=8))&0xff;
124 | if(p <= 0) { p += this.DB; --i; }
125 | }
126 | if((d&0x80) != 0) d |= -256;
127 | if(k == 0 && (this.s&0x80) != (d&0x80)) ++k;
128 | if(k > 0 || d != this.s) r[k++] = d;
129 | }
130 | }
131 | return r;
132 | }
133 |
134 | function bnEquals(a) { return(this.compareTo(a)==0); }
135 | function bnMin(a) { return(this.compareTo(a)<0)?this:a; }
136 | function bnMax(a) { return(this.compareTo(a)>0)?this:a; }
137 |
138 | // (protected) r = this op a (bitwise)
139 | function bnpBitwiseTo(a,op,r) {
140 | var i, f, m = Math.min(a.t,this.t);
141 | for(i = 0; i < m; ++i) r[i] = op(this[i],a[i]);
142 | if(a.t < this.t) {
143 | f = a.s&this.DM;
144 | for(i = m; i < this.t; ++i) r[i] = op(this[i],f);
145 | r.t = this.t;
146 | }
147 | else {
148 | f = this.s&this.DM;
149 | for(i = m; i < a.t; ++i) r[i] = op(f,a[i]);
150 | r.t = a.t;
151 | }
152 | r.s = op(this.s,a.s);
153 | r.clamp();
154 | }
155 |
156 | // (public) this & a
157 | function op_and(x,y) { return x&y; }
158 | function bnAnd(a) { var r = nbi(); this.bitwiseTo(a,op_and,r); return r; }
159 |
160 | // (public) this | a
161 | function op_or(x,y) { return x|y; }
162 | function bnOr(a) { var r = nbi(); this.bitwiseTo(a,op_or,r); return r; }
163 |
164 | // (public) this ^ a
165 | function op_xor(x,y) { return x^y; }
166 | function bnXor(a) { var r = nbi(); this.bitwiseTo(a,op_xor,r); return r; }
167 |
168 | // (public) this & ~a
169 | function op_andnot(x,y) { return x&~y; }
170 | function bnAndNot(a) { var r = nbi(); this.bitwiseTo(a,op_andnot,r); return r; }
171 |
172 | // (public) ~this
173 | function bnNot() {
174 | var r = nbi();
175 | for(var i = 0; i < this.t; ++i) r[i] = this.DM&~this[i];
176 | r.t = this.t;
177 | r.s = ~this.s;
178 | return r;
179 | }
180 |
181 | // (public) this << n
182 | function bnShiftLeft(n) {
183 | var r = nbi();
184 | if(n < 0) this.rShiftTo(-n,r); else this.lShiftTo(n,r);
185 | return r;
186 | }
187 |
188 | // (public) this >> n
189 | function bnShiftRight(n) {
190 | var r = nbi();
191 | if(n < 0) this.lShiftTo(-n,r); else this.rShiftTo(n,r);
192 | return r;
193 | }
194 |
195 | // return index of lowest 1-bit in x, x < 2^31
196 | function lbit(x) {
197 | if(x == 0) return -1;
198 | var r = 0;
199 | if((x&0xffff) == 0) { x >>= 16; r += 16; }
200 | if((x&0xff) == 0) { x >>= 8; r += 8; }
201 | if((x&0xf) == 0) { x >>= 4; r += 4; }
202 | if((x&3) == 0) { x >>= 2; r += 2; }
203 | if((x&1) == 0) ++r;
204 | return r;
205 | }
206 |
207 | // (public) returns index of lowest 1-bit (or -1 if none)
208 | function bnGetLowestSetBit() {
209 | for(var i = 0; i < this.t; ++i)
210 | if(this[i] != 0) return i*this.DB+lbit(this[i]);
211 | if(this.s < 0) return this.t*this.DB;
212 | return -1;
213 | }
214 |
215 | // return number of 1 bits in x
216 | function cbit(x) {
217 | var r = 0;
218 | while(x != 0) { x &= x-1; ++r; }
219 | return r;
220 | }
221 |
222 | // (public) return number of set bits
223 | function bnBitCount() {
224 | var r = 0, x = this.s&this.DM;
225 | for(var i = 0; i < this.t; ++i) r += cbit(this[i]^x);
226 | return r;
227 | }
228 |
229 | // (public) true iff nth bit is set
230 | function bnTestBit(n) {
231 | var j = Math.floor(n/this.DB);
232 | if(j >= this.t) return(this.s!=0);
233 | return((this[j]&(1<<(n%this.DB)))!=0);
234 | }
235 |
236 | // (protected) this op (1<