├── .gitattributes ├── .gitignore ├── .npmignore ├── LICENSE ├── LICENSE.AMAZON ├── LICENSE.APACHE ├── NOTICE ├── README.md ├── android ├── build.gradle └── src │ └── main │ ├── AndroidManifest.xml │ └── java │ └── com │ └── airlabsinc │ ├── RNAWSCognitoModule.java │ └── RNAWSCognitoPackage.java ├── example ├── .babelrc ├── .buckconfig ├── .flowconfig ├── .gitattributes ├── .gitignore ├── .watchmanconfig ├── android │ ├── app │ │ ├── BUCK │ │ ├── build.gradle │ │ ├── proguard-rules.pro │ │ └── src │ │ │ └── main │ │ │ ├── AndroidManifest.xml │ │ │ ├── java │ │ │ └── com │ │ │ │ └── example │ │ │ │ ├── MainActivity.java │ │ │ │ └── MainApplication.java │ │ │ └── res │ │ │ ├── mipmap-hdpi │ │ │ └── ic_launcher.png │ │ │ ├── mipmap-mdpi │ │ │ └── ic_launcher.png │ │ │ ├── mipmap-xhdpi │ │ │ └── ic_launcher.png │ │ │ ├── mipmap-xxhdpi │ │ │ └── ic_launcher.png │ │ │ └── values │ │ │ ├── strings.xml │ │ │ └── styles.xml │ ├── build.gradle │ ├── gradle.properties │ ├── gradle │ │ └── wrapper │ │ │ ├── gradle-wrapper.jar │ │ │ └── gradle-wrapper.properties │ ├── gradlew │ ├── gradlew.bat │ ├── keystores │ │ ├── BUCK │ │ └── debug.keystore.properties │ └── settings.gradle ├── app.js ├── app.json ├── index.android.js ├── index.ios.js ├── ios │ ├── example-tvOS │ │ └── Info.plist │ ├── example-tvOSTests │ │ └── Info.plist │ ├── example.xcodeproj │ │ ├── project.pbxproj │ │ └── xcshareddata │ │ │ └── xcschemes │ │ │ ├── example-tvOS.xcscheme │ │ │ └── example.xcscheme │ ├── example │ │ ├── AppDelegate.h │ │ ├── AppDelegate.m │ │ ├── Base.lproj │ │ │ └── LaunchScreen.xib │ │ ├── Images.xcassets │ │ │ └── AppIcon.appiconset │ │ │ │ └── Contents.json │ │ ├── Info.plist │ │ └── main.m │ └── exampleTests │ │ ├── Info.plist │ │ └── exampleTests.m ├── package.json └── yarn.lock ├── index.js ├── ios ├── JKBigInteger │ ├── JKBigDecimal.h │ ├── JKBigDecimal.m │ ├── JKBigInteger.h │ ├── JKBigInteger.m │ └── LibTomMath │ │ ├── tommath.c │ │ ├── tommath.h │ │ ├── tommath_class.h │ │ └── tommath_superclass.h ├── RNAWSCognito.h ├── RNAWSCognito.m └── RNAWSCognito.xcodeproj │ └── project.pbxproj ├── package.json ├── react-native-aws-cognito-js.podspec ├── src ├── AuthenticationDetails.js ├── AuthenticationHelper.js ├── BigInteger.js ├── CognitoAccessToken.js ├── CognitoIdToken.js ├── CognitoRefreshToken.js ├── CognitoUser.js ├── CognitoUserAttribute.js ├── CognitoUserPool.js ├── CognitoUserSession.js ├── DateHelper.js ├── StorageHelper.js └── index.js └── yarn.lock /.gitattributes: -------------------------------------------------------------------------------- 1 | *.pbxproj -text -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # OSX 2 | # 3 | .DS_Store 4 | 5 | # node.js 6 | # 7 | node_modules/ 8 | npm-debug.log 9 | yarn-error.log 10 | 11 | 12 | # Xcode 13 | # 14 | build/ 15 | *.pbxuser 16 | !default.pbxuser 17 | *.mode1v3 18 | !default.mode1v3 19 | *.mode2v3 20 | !default.mode2v3 21 | *.perspectivev3 22 | !default.perspectivev3 23 | xcuserdata 24 | *.xccheckout 25 | *.moved-aside 26 | DerivedData 27 | *.hmap 28 | *.ipa 29 | *.xcuserstate 30 | project.xcworkspace 31 | 32 | 33 | # Android/IntelliJ 34 | # 35 | build/ 36 | .idea 37 | .gradle 38 | local.properties 39 | *.iml 40 | 41 | # BUCK 42 | buck-out/ 43 | \.buckd/ 44 | *.keystore 45 | -------------------------------------------------------------------------------- /.npmignore: -------------------------------------------------------------------------------- 1 | /example -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The AWS SDK for JavaScript is licensed under the Apache 2.0 License, with the Amazon Cognito Identity Provider SDK for JavaScript components being licensed under the Amazon Software License. 2 | -------------------------------------------------------------------------------- /LICENSE.AMAZON: -------------------------------------------------------------------------------- 1 | Amazon Software License 2 | This Amazon Software License (“License”) governs your use, reproduction, and distribution of the accompanying software as specified below. 3 | 1. Definitions 4 | “Licensor” means any person or entity that distributes its Work. 5 | 6 | “Software” means the original work of authorship made available under this License. 7 | 8 | “Work” means the Software and any additions to or derivative works of the Software that are made available under this License. 9 | 10 | The terms “reproduce,” “reproduction,” “derivative works,” and “distribution” have the meaning as provided under U.S. copyright law; provided, however, that for the purposes of this License, derivative works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work. 11 | 12 | Works, including the Software, are “made available” under this License by including in or with the Work either (a) a copyright notice referencing the applicability of this License to the Work, or (b) a copy of this License. 13 | 2. License Grants 14 | 2.1 Copyright Grant. Subject to the terms and conditions of this License, each Licensor grants to you a perpetual, worldwide, non-exclusive, royalty-free, copyright license to reproduce, prepare derivative works of, publicly display, publicly perform, sublicense and distribute its Work and any resulting derivative works in any form. 15 | 2.2 Patent Grant. Subject to the terms and conditions of this License, each Licensor grants to you a perpetual, worldwide, non-exclusive, royalty-free patent license to make, have made, use, sell, offer for sale, import, and otherwise transfer its Work, in whole or in part. The foregoing license applies only to the patent claims licensable by Licensor that would be infringed by Licensor’s Work (or portion thereof) individually and excluding any combinations with any other materials or technology. 16 | 3. Limitations 17 | 3.1 Redistribution. You may reproduce or distribute the Work only if (a) you do so under this License, (b) you include a complete copy of this License with your distribution, and (c) you retain without modification any copyright, patent, trademark, or attribution notices that are present in the Work. 18 | 3.2 Derivative Works. You may specify that additional or different terms apply to the use, reproduction, and distribution of your derivative works of the Work (“Your Terms”) only if (a) Your Terms provide that the use limitation in Section 3.3 applies to your derivative works, and (b) you identify the specific derivative works that are subject to Your Terms. Notwithstanding Your Terms, this License (including the redistribution requirements in Section 3.1) will continue to apply to the Work itself. 19 | 3.3 Use Limitation. The Work and any derivative works thereof only may be used or intended for use with the web services, computing platforms or applications provided by Amazon.com, Inc. or its affiliates, including Amazon Web Services, Inc. 20 | 3.4 Patent Claims. If you bring or threaten to bring a patent claim against any Licensor (including any claim, cross-claim or counterclaim in a lawsuit) to enforce any patents that you allege are infringed by any Work, then your rights under this License from such Licensor (including the grants in Sections 2.1 and 2.2) will terminate immediately. 21 | 3.5 Trademarks. This License does not grant any rights to use any Licensor’s or its affiliates’ names, logos, or trademarks, except as necessary to reproduce the notices described in this License. 22 | 3.6 Termination. If you violate any term of this License, then your rights under this License (including the grants in Sections 2.1 and 2.2) will terminate immediately. 23 | 4. Disclaimer of Warranty. 24 | THE WORK IS PROVIDED “AS IS” WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WARRANTIES OR CONDITIONS OF M ERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE OR NON-INFRINGEMENT. YOU BEAR THE RISK OF UNDERTAKING ANY ACTIVITIES UNDER THIS LICENSE. SOME STATES’ CONSUMER LAWS DO NOT ALLOW EXCLUSION OF AN IMPLIED WARRANTY, SO THIS DISCLAIMER MAY NOT APPLY TO YOU. 25 | 5. Limitation of Liability. 26 | EXCEPT AS PROHIBITED BY APPLICABLE LAW, IN NO EVENT AND UNDER NO LEGAL THEORY, WHETHER IN TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE SHALL ANY LICENSOR BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF OR RELATED TO THIS LICENSE, THE USE OR INABILITY TO USE THE WORK (INCLUDING BUT NOT LIMITED TO LOSS OF GOODWILL, BUSINESS INTERRUPTION, LOST PROFITS OR DATA, COMPUTER FAILURE OR MALFUNCTION, OR ANY OTHER COMM ERCIAL DAMAGES OR LOSSES), EVEN IF THE LICENSOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 27 | Effective Date – April 18, 2008 © 2008 Amazon.com, Inc. or its affiliates. All rights reserved. -------------------------------------------------------------------------------- /LICENSE.APACHE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright 2012-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. -------------------------------------------------------------------------------- /NOTICE: -------------------------------------------------------------------------------- 1 | react-native-aws-cognito-js 2 | Copyright 2017 Air Labs, Inc. or its affiliates. All Rights Reserved. 3 | 4 | This product includes software developed by Amazon Technologies, Inc (http://www.amazon.com/). 5 | 6 | Licensed under the Amazon Software License included in LICENSE.txt. 7 | 8 | ***************************** 9 | AMAZON PROPRIETARY COMPONENTS 10 | ***************************** 11 | 12 | The following components are distributed under a proprietary license by Amazon Technologies, Inc 13 | 14 | - Amazon Cognito Identity Provider SDK for JavaScript 15 | Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. 16 | https://github.com/aws/amazon-cognito-identity-js 17 | 18 | 19 | - AWS SDK for JavaScript 20 | Copyright 2012-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. 21 | This product includes software developed at 22 | Amazon Web Services, Inc. (http://aws.amazon.com/). 23 | https://github.com/aws/aws-sdk-js 24 | 25 | See the License for the specific language governing permissions and limitations under the License. 26 | 27 | ********************** 28 | THIRD PARTY COMPONENTS 29 | ********************** 30 | 31 | This software includes third party software subject to the following copyrights: 32 | 33 | - JKBigInteger – Copyright (c) 2015 Midfar Sun. All rights reserved. – MIT License 34 | https://github.com/kirsteins/JKBigInteger/ 35 | 36 | - Basic JavaScript BN library - Copyright (c) 2005 Tom Wu. All Rights Reserved. 37 | http://www-cs-students.stanford.edu/%7Etjw/jsbn/jsbn.js 38 | 39 | ==================== 40 | 41 | JKBigInteger – Copyright (c) 2015 Midfar Sun. All rights reserved. 42 | 43 | Copyright (C) 2013 Jānis Kiršteins 44 | 45 | Permission is hereby granted, free of charge, to any person obtaining a copy of 46 | this software and associated documentation files (the "Software"), to deal in 47 | the Software without restriction, including without limitation the rights to 48 | use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of 49 | the Software, and to permit persons to whom the Software is furnished to do so, 50 | subject to the following conditions: 51 | 52 | The above copyright notice and this permission notice shall be included in all 53 | copies or substantial portions of the Software. 54 | 55 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 56 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS 57 | FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR 58 | COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER 59 | IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 60 | CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 61 | 62 | ==================== 63 | 64 | Licensing 65 | --------- 66 | 67 | This software is covered under the following copyright: 68 | 69 | /* 70 | * Copyright (c) 2003-2005 Tom Wu 71 | * All Rights Reserved. 72 | * 73 | * Permission is hereby granted, free of charge, to any person obtaining 74 | * a copy of this software and associated documentation files (the 75 | * "Software"), to deal in the Software without restriction, including 76 | * without limitation the rights to use, copy, modify, merge, publish, 77 | * distribute, sublicense, and/or sell copies of the Software, and to 78 | * permit persons to whom the Software is furnished to do so, subject to 79 | * the following conditions: 80 | * 81 | * The above copyright notice and this permission notice shall be 82 | * included in all copies or substantial portions of the Software. 83 | * 84 | * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, 85 | * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY 86 | * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. 87 | * 88 | * IN NO EVENT SHALL TOM WU BE LIABLE FOR ANY SPECIAL, INCIDENTAL, 89 | * INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, OR ANY DAMAGES WHATSOEVER 90 | * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER OR NOT ADVISED OF 91 | * THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF LIABILITY, ARISING OUT 92 | * OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. 93 | * 94 | * In addition, the following condition applies: 95 | * 96 | * All redistributions must retain an intact copy of this copyright notice 97 | * and disclaimer. 98 | */ 99 | 100 | Address all questions regarding this license to: 101 | 102 | Tom Wu 103 | tjw@cs.Stanford.EDU 104 | 105 | ==================== 106 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | This library is deprecated. It was merged into aws cognito identity js and finally into: 2 | 3 | https://github.com/aws-amplify/amplify-js. 4 | 5 | The amplify library will have the most up to date versions of everything and is maintained by AWS. 6 | 7 | ## react-native-aws-cognito-js [![npm version](https://badge.fury.io/js/react-native-aws-cognito-js.svg)](http://badge.fury.io/js/react-native-aws-cognito-js) 8 | 9 | This is an adaptation of [Amazon Cognito Identity SDK for JavaScript](https://github.com/aws/amazon-cognito-identity-js) in combination with [AWS SDK for JavaScript](https://github.com/aws/aws-sdk-js/tree/react-native) for [React Native](https://github.com/facebook/react-native/). 10 | 11 | This project uses Native Modules to handle intensive math operations on the device using the React Native bridge. 12 | 13 | ## Installation 14 | 15 | Install in your application directory: 16 | 17 | ```bash 18 | npm install --save react-native-aws-cognito-js 19 | ``` 20 | 21 | or 22 | 23 | ```bash 24 | yarn add react-native-aws-cognito-js 25 | ``` 26 | 27 | Link project: 28 | 29 | ```bash 30 | react-native link react-native-aws-cognito-js 31 | ``` 32 | 33 | ## MemoryStorage 34 | 35 | The local MemoryStorage can handle everything on the authentication side, but the data is lost when the app is reopened. The storage sync method will grab only the MemoryStorage data from AsyncStorage and update the local MemoryStage with the values. 36 | 37 | The new sync method can be used from either the userPool or cognitoUser: 38 | 39 | ```js 40 | userPool.storage.sync((err, result) => { 41 | // MemoryStorage is now updated with AsyncStorage values 42 | }); 43 | ``` 44 | 45 | or 46 | 47 | ```js 48 | cognitoUser.storage.sync((err, result) => { 49 | // MemoryStorage is now updated with AsyncStorage values 50 | }); 51 | ``` 52 | 53 | ## Usage 54 | 55 | Refer to the Amazon Cognito Identity SDK for JavaScript usage [examples](https://github.com/aws/amazon-cognito-identity-js#usage). 56 | 57 | ## Example 58 | 59 | This is a user authentication sample: 60 | 61 | ```js 62 | //imports 63 | import { 64 | Config, 65 | CognitoIdentityCredentials 66 | } from 'aws-sdk/dist/aws-sdk-react-native'; 67 | 68 | import { 69 | AuthenticationDetails, 70 | CognitoUser, 71 | CognitoUserPool, 72 | CognitoUserAttribute 73 | } from 'react-native-aws-cognito-js'; 74 | 75 | const appConfig = { 76 | region: '', 77 | IdentityPoolId: '', 78 | UserPoolId: '', 79 | ClientId: '', 80 | } 81 | 82 | //setting config 83 | Config.region = appConfig.region; 84 | 85 | //component: 86 | state = { 87 | username: '', 88 | password: '', 89 | } 90 | 91 | login = () => { 92 | const { username, password } = this.state; 93 | const authenticationData = { 94 | Username: username, 95 | Password: password, 96 | }; 97 | const authenticationDetails = new AuthenticationDetails(authenticationData); 98 | const poolData = { 99 | UserPoolId: appConfig.UserPoolId, 100 | ClientId: appConfig.ClientId 101 | }; 102 | const userPool = new CognitoUserPool(poolData); 103 | const userData = { 104 | Username: username, 105 | Pool: userPool 106 | }; 107 | const cognitoUser = new CognitoUser(userData); 108 | cognitoUser.authenticateUser(authenticationDetails, { 109 | onSuccess: (result) => { 110 | console.log('access token + ' + result.getAccessToken().getJwtToken()); 111 | Config.credentials = new CognitoIdentityCredentials({ 112 | IdentityPoolId: appConfig.IdentityPoolId, 113 | Logins: { 114 | [`cognito-idp.${appConfig.region}.amazonaws.com/${appConfig.UserPoolId}`]: result.getIdToken().getJwtToken() 115 | } 116 | }); 117 | alert('Success'); 118 | console.log(Config.credentials); 119 | }, 120 | onFailure: (err) => { 121 | alert(err); 122 | }, 123 | }); 124 | } 125 | ``` 126 | 127 | ## Advanced Example 128 | 129 | ```js 130 | //- AWS.js 131 | //create AWS with userPool using dotenv to hold environment variables 132 | import AWS, { CognitoIdentityServiceProvider } from 'aws-sdk/dist/aws-sdk-react-native'; 133 | import * as enhancements from 'react-native-aws-cognito-js'; 134 | import { AWS_REGION, AWS_POOL_ID, AWS_POOL_CLIENT_ID } from 'react-native-dotenv'; 135 | 136 | Object.keys(enhancements).forEach(key => (CognitoIdentityServiceProvider[key] = enhancements[key])); 137 | 138 | AWS.config.update({ region: AWS_REGION }); 139 | 140 | export const poolData = { 141 | UserPoolId: AWS_POOL_ID, 142 | ClientId: AWS_POOL_CLIENT_ID, 143 | }; 144 | 145 | export const userPool = new AWS.CognitoIdentityServiceProvider.CognitoUserPool(poolData); 146 | 147 | export default AWS; 148 | ``` 149 | 150 | ```js 151 | //import AWS and userPool 152 | import AWS, { userPool } from './AWS'; 153 | 154 | //component: 155 | state = { 156 | username: '', 157 | password: '', 158 | } 159 | 160 | login = () => { 161 | const { username, password } = this.state; 162 | const authenticationData = { Username: username, Password: password }; 163 | const authenticationDetails = new AWS.CognitoIdentityServiceProvider.AuthenticationDetails(authenticationData); 164 | const userData = { Username: username, Pool: userPool }; 165 | const cognitoUser = new AWS.CognitoIdentityServiceProvider.CognitoUser(userData); 166 | cognitoUser.authenticateUser(authenticationDetails, { 167 | onSuccess: (result) => { 168 | console.log('result', result); 169 | console.log('access token:', result.getAccessToken().getJwtToken()); 170 | }, 171 | onFailure: (error) => { 172 | Alert.alert(error.code, error.message); 173 | }, 174 | }); 175 | } 176 | ``` 177 | -------------------------------------------------------------------------------- /android/build.gradle: -------------------------------------------------------------------------------- 1 | buildscript { 2 | repositories { 3 | jcenter() 4 | } 5 | 6 | dependencies { 7 | classpath 'com.android.tools.build:gradle:1.3.1' 8 | } 9 | } 10 | 11 | apply plugin: 'com.android.library' 12 | 13 | android { 14 | compileSdkVersion 23 15 | buildToolsVersion "23.0.1" 16 | 17 | defaultConfig { 18 | minSdkVersion 16 19 | targetSdkVersion 22 20 | versionCode 1 21 | versionName "1.0" 22 | } 23 | lintOptions { 24 | abortOnError false 25 | } 26 | } 27 | 28 | repositories { 29 | mavenCentral() 30 | } 31 | 32 | dependencies { 33 | compile 'com.facebook.react:react-native:+' 34 | } 35 | -------------------------------------------------------------------------------- /android/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /android/src/main/java/com/airlabsinc/RNAWSCognitoModule.java: -------------------------------------------------------------------------------- 1 | package com.airlabsinc; 2 | 3 | import com.facebook.react.bridge.ReactApplicationContext; 4 | import com.facebook.react.bridge.ReactContextBaseJavaModule; 5 | import com.facebook.react.bridge.ReactMethod; 6 | import com.facebook.react.bridge.ReadableMap; 7 | import com.facebook.react.bridge.Callback; 8 | import java.math.BigInteger; 9 | 10 | public class RNAWSCognitoModule extends ReactContextBaseJavaModule { 11 | 12 | private final ReactApplicationContext reactContext; 13 | 14 | private static final String HEX_N = "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1" 15 | + "29024E088A67CC74020BBEA63B139B22514A08798E3404DD" 16 | + "EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245" 17 | + "E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED" 18 | + "EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D" 19 | + "C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F" 20 | + "83655D23DCA3AD961C62F356208552BB9ED529077096966D" 21 | + "670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B" 22 | + "E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9" 23 | + "DE2BCBF6955817183995497CEA956AE515D2261898FA0510" 24 | + "15728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64" 25 | + "ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7" 26 | + "ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6B" 27 | + "F12FFA06D98A0864D87602733EC86A64521F2B18177B200C" 28 | + "BBE117577A615D6C770988C0BAD946E208E24FA074E5AB31" 29 | + "43DB5BFCE0FD108E4B82D120A93AD2CAFFFFFFFFFFFFFFFF"; 30 | 31 | private static final BigInteger N = new BigInteger(HEX_N, 16); 32 | 33 | public RNAWSCognitoModule(ReactApplicationContext reactContext) { 34 | super(reactContext); 35 | this.reactContext = reactContext; 36 | } 37 | 38 | @Override 39 | public String getName() { 40 | return "RNAWSCognito"; 41 | } 42 | 43 | @ReactMethod 44 | public void computeModPow(final ReadableMap values, final Callback callback) { 45 | try { 46 | final BigInteger target = new BigInteger(values.getString("target"), 16); 47 | final BigInteger value = new BigInteger(values.getString("value"), 16); 48 | final BigInteger result = target.modPow(value, N); 49 | callback.invoke(null, result.toString(16)); 50 | } catch (Exception e) { 51 | callback.invoke(e.getMessage(), null); 52 | } 53 | } 54 | 55 | @ReactMethod 56 | public void computeS(final ReadableMap values, final Callback callback) { 57 | try { 58 | final BigInteger g = new BigInteger(values.getString("g"), 16); 59 | final BigInteger x = new BigInteger(values.getString("x"), 16); 60 | final BigInteger k = new BigInteger(values.getString("k"), 16); 61 | final BigInteger a = new BigInteger(values.getString("a"), 16); 62 | final BigInteger b = new BigInteger(values.getString("b"), 16); 63 | final BigInteger u = new BigInteger(values.getString("u"), 16); 64 | final BigInteger exp = a.add(u.multiply(x)); 65 | final BigInteger base = b.subtract(k.multiply(g.modPow(x, N))); 66 | final BigInteger result = base.modPow(exp, N).mod(N); 67 | callback.invoke(null, result.toString(16)); 68 | } catch (Exception e) { 69 | callback.invoke(e.getMessage(), null); 70 | } 71 | } 72 | } -------------------------------------------------------------------------------- /android/src/main/java/com/airlabsinc/RNAWSCognitoPackage.java: -------------------------------------------------------------------------------- 1 | package com.airlabsinc; 2 | 3 | import java.util.Arrays; 4 | import java.util.Collections; 5 | import java.util.List; 6 | 7 | import com.facebook.react.ReactPackage; 8 | import com.facebook.react.bridge.NativeModule; 9 | import com.facebook.react.bridge.ReactApplicationContext; 10 | import com.facebook.react.uimanager.ViewManager; 11 | import com.facebook.react.bridge.JavaScriptModule; 12 | public class RNAWSCognitoPackage implements ReactPackage { 13 | @Override 14 | public List createNativeModules(ReactApplicationContext reactContext) { 15 | return Arrays.asList(new RNAWSCognitoModule(reactContext)); 16 | } 17 | 18 | public List> createJSModules() { 19 | return Collections.emptyList(); 20 | } 21 | 22 | @Override 23 | public List createViewManagers(ReactApplicationContext reactContext) { 24 | return Collections.emptyList(); 25 | } 26 | } -------------------------------------------------------------------------------- /example/.babelrc: -------------------------------------------------------------------------------- 1 | { 2 | "presets": ["react-native"] 3 | } -------------------------------------------------------------------------------- /example/.buckconfig: -------------------------------------------------------------------------------- 1 | 2 | [android] 3 | target = Google Inc.:Google APIs:23 4 | 5 | [maven_repositories] 6 | central = https://repo1.maven.org/maven2 7 | -------------------------------------------------------------------------------- /example/.flowconfig: -------------------------------------------------------------------------------- 1 | [ignore] 2 | ; We fork some components by platform 3 | .*/*[.]android.js 4 | 5 | ; Ignore "BUCK" generated dirs 6 | /\.buckd/ 7 | 8 | ; Ignore unexpected extra "@providesModule" 9 | .*/node_modules/.*/node_modules/fbjs/.* 10 | 11 | ; Ignore duplicate module providers 12 | ; For RN Apps installed via npm, "Libraries" folder is inside 13 | ; "node_modules/react-native" but in the source repo it is in the root 14 | .*/Libraries/react-native/React.js 15 | .*/Libraries/react-native/ReactNative.js 16 | 17 | [include] 18 | 19 | [libs] 20 | node_modules/react-native/Libraries/react-native/react-native-interface.js 21 | node_modules/react-native/flow 22 | flow/ 23 | 24 | [options] 25 | emoji=true 26 | 27 | module.system=haste 28 | 29 | experimental.strict_type_args=true 30 | 31 | munge_underscores=true 32 | 33 | module.name_mapper='^[./a-zA-Z0-9$_-]+\.\(bmp\|gif\|jpg\|jpeg\|png\|psd\|svg\|webp\|m4v\|mov\|mp4\|mpeg\|mpg\|webm\|aac\|aiff\|caf\|m4a\|mp3\|wav\|html\|pdf\)$' -> 'RelativeImageStub' 34 | 35 | suppress_type=$FlowIssue 36 | suppress_type=$FlowFixMe 37 | suppress_type=$FixMe 38 | 39 | suppress_comment=\\(.\\|\n\\)*\\$FlowFixMe\\($\\|[^(]\\|(\\(>=0\\.\\(4[0-0]\\|[1-3][0-9]\\|[0-9]\\).[0-9]\\)? *\\(site=[a-z,_]*react_native[a-z,_]*\\)?)\\) 40 | suppress_comment=\\(.\\|\n\\)*\\$FlowIssue\\((\\(>=0\\.\\(4[0-0]\\|[1-3][0-9]\\|[0-9]\\).[0-9]\\)? *\\(site=[a-z,_]*react_native[a-z,_]*\\)?)\\)?:? #[0-9]+ 41 | suppress_comment=\\(.\\|\n\\)*\\$FlowFixedInNextDeploy 42 | suppress_comment=\\(.\\|\n\\)*\\$FlowExpectedError 43 | 44 | unsafe.enable_getters_and_setters=true 45 | 46 | [version] 47 | ^0.40.0 48 | -------------------------------------------------------------------------------- /example/.gitattributes: -------------------------------------------------------------------------------- 1 | *.pbxproj -text 2 | -------------------------------------------------------------------------------- /example/.gitignore: -------------------------------------------------------------------------------- 1 | # OSX 2 | # 3 | .DS_Store 4 | 5 | # Xcode 6 | # 7 | build/ 8 | *.pbxuser 9 | !default.pbxuser 10 | *.mode1v3 11 | !default.mode1v3 12 | *.mode2v3 13 | !default.mode2v3 14 | *.perspectivev3 15 | !default.perspectivev3 16 | xcuserdata 17 | *.xccheckout 18 | *.moved-aside 19 | DerivedData 20 | *.hmap 21 | *.ipa 22 | *.xcuserstate 23 | project.xcworkspace 24 | 25 | # Android/IntelliJ 26 | # 27 | build/ 28 | .idea 29 | .gradle 30 | local.properties 31 | *.iml 32 | 33 | # node.js 34 | # 35 | node_modules/ 36 | npm-debug.log 37 | yarn-error.log 38 | 39 | # BUCK 40 | buck-out/ 41 | \.buckd/ 42 | *.keystore 43 | 44 | # fastlane 45 | # 46 | # It is recommended to not store the screenshots in the git repo. Instead, use fastlane to re-generate the 47 | # screenshots whenever they are needed. 48 | # For more information about the recommended setup visit: 49 | # https://github.com/fastlane/fastlane/blob/master/fastlane/docs/Gitignore.md 50 | 51 | fastlane/report.xml 52 | fastlane/Preview.html 53 | fastlane/screenshots 54 | -------------------------------------------------------------------------------- /example/.watchmanconfig: -------------------------------------------------------------------------------- 1 | {} -------------------------------------------------------------------------------- /example/android/app/BUCK: -------------------------------------------------------------------------------- 1 | # To learn about Buck see [Docs](https://buckbuild.com/). 2 | # To run your application with Buck: 3 | # - install Buck 4 | # - `npm start` - to start the packager 5 | # - `cd android` 6 | # - `keytool -genkey -v -keystore keystores/debug.keystore -storepass android -alias androiddebugkey -keypass android -dname "CN=Android Debug,O=Android,C=US"` 7 | # - `./gradlew :app:copyDownloadableDepsToLibs` - make all Gradle compile dependencies available to Buck 8 | # - `buck install -r android/app` - compile, install and run application 9 | # 10 | 11 | lib_deps = [] 12 | 13 | for jarfile in glob(['libs/*.jar']): 14 | name = 'jars__' + jarfile[jarfile.rindex('/') + 1: jarfile.rindex('.jar')] 15 | lib_deps.append(':' + name) 16 | prebuilt_jar( 17 | name = name, 18 | binary_jar = jarfile, 19 | ) 20 | 21 | for aarfile in glob(['libs/*.aar']): 22 | name = 'aars__' + aarfile[aarfile.rindex('/') + 1: aarfile.rindex('.aar')] 23 | lib_deps.append(':' + name) 24 | android_prebuilt_aar( 25 | name = name, 26 | aar = aarfile, 27 | ) 28 | 29 | android_library( 30 | name = "all-libs", 31 | exported_deps = lib_deps, 32 | ) 33 | 34 | android_library( 35 | name = "app-code", 36 | srcs = glob([ 37 | "src/main/java/**/*.java", 38 | ]), 39 | deps = [ 40 | ":all-libs", 41 | ":build_config", 42 | ":res", 43 | ], 44 | ) 45 | 46 | android_build_config( 47 | name = "build_config", 48 | package = "com.example", 49 | ) 50 | 51 | android_resource( 52 | name = "res", 53 | package = "com.example", 54 | res = "src/main/res", 55 | ) 56 | 57 | android_binary( 58 | name = "app", 59 | keystore = "//android/keystores:debug", 60 | manifest = "src/main/AndroidManifest.xml", 61 | package_type = "debug", 62 | deps = [ 63 | ":app-code", 64 | ], 65 | ) 66 | -------------------------------------------------------------------------------- /example/android/app/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: "com.android.application" 2 | 3 | import com.android.build.OutputFile 4 | 5 | /** 6 | * The react.gradle file registers a task for each build variant (e.g. bundleDebugJsAndAssets 7 | * and bundleReleaseJsAndAssets). 8 | * These basically call `react-native bundle` with the correct arguments during the Android build 9 | * cycle. By default, bundleDebugJsAndAssets is skipped, as in debug/dev mode we prefer to load the 10 | * bundle directly from the development server. Below you can see all the possible configurations 11 | * and their defaults. If you decide to add a configuration block, make sure to add it before the 12 | * `apply from: "../../node_modules/react-native/react.gradle"` line. 13 | * 14 | * project.ext.react = [ 15 | * // the name of the generated asset file containing your JS bundle 16 | * bundleAssetName: "index.android.bundle", 17 | * 18 | * // the entry file for bundle generation 19 | * entryFile: "index.android.js", 20 | * 21 | * // whether to bundle JS and assets in debug mode 22 | * bundleInDebug: false, 23 | * 24 | * // whether to bundle JS and assets in release mode 25 | * bundleInRelease: true, 26 | * 27 | * // whether to bundle JS and assets in another build variant (if configured). 28 | * // See http://tools.android.com/tech-docs/new-build-system/user-guide#TOC-Build-Variants 29 | * // The configuration property can be in the following formats 30 | * // 'bundleIn${productFlavor}${buildType}' 31 | * // 'bundleIn${buildType}' 32 | * // bundleInFreeDebug: true, 33 | * // bundleInPaidRelease: true, 34 | * // bundleInBeta: true, 35 | * 36 | * // the root of your project, i.e. where "package.json" lives 37 | * root: "../../", 38 | * 39 | * // where to put the JS bundle asset in debug mode 40 | * jsBundleDirDebug: "$buildDir/intermediates/assets/debug", 41 | * 42 | * // where to put the JS bundle asset in release mode 43 | * jsBundleDirRelease: "$buildDir/intermediates/assets/release", 44 | * 45 | * // where to put drawable resources / React Native assets, e.g. the ones you use via 46 | * // require('./image.png')), in debug mode 47 | * resourcesDirDebug: "$buildDir/intermediates/res/merged/debug", 48 | * 49 | * // where to put drawable resources / React Native assets, e.g. the ones you use via 50 | * // require('./image.png')), in release mode 51 | * resourcesDirRelease: "$buildDir/intermediates/res/merged/release", 52 | * 53 | * // by default the gradle tasks are skipped if none of the JS files or assets change; this means 54 | * // that we don't look at files in android/ or ios/ to determine whether the tasks are up to 55 | * // date; if you have any other folders that you want to ignore for performance reasons (gradle 56 | * // indexes the entire tree), add them here. Alternatively, if you have JS files in android/ 57 | * // for example, you might want to remove it from here. 58 | * inputExcludes: ["android/**", "ios/**"], 59 | * 60 | * // override which node gets called and with what additional arguments 61 | * nodeExecutableAndArgs: ["node"] 62 | * 63 | * // supply additional arguments to the packager 64 | * extraPackagerArgs: [] 65 | * ] 66 | */ 67 | 68 | apply from: "../../node_modules/react-native/react.gradle" 69 | 70 | /** 71 | * Set this to true to create two separate APKs instead of one: 72 | * - An APK that only works on ARM devices 73 | * - An APK that only works on x86 devices 74 | * The advantage is the size of the APK is reduced by about 4MB. 75 | * Upload all the APKs to the Play Store and people will download 76 | * the correct one based on the CPU architecture of their device. 77 | */ 78 | def enableSeparateBuildPerCPUArchitecture = false 79 | 80 | /** 81 | * Run Proguard to shrink the Java bytecode in release builds. 82 | */ 83 | def enableProguardInReleaseBuilds = false 84 | 85 | android { 86 | compileSdkVersion 23 87 | buildToolsVersion "23.0.1" 88 | 89 | defaultConfig { 90 | applicationId "com.example" 91 | minSdkVersion 16 92 | targetSdkVersion 22 93 | versionCode 1 94 | versionName "1.0" 95 | ndk { 96 | abiFilters "armeabi-v7a", "x86" 97 | } 98 | } 99 | splits { 100 | abi { 101 | reset() 102 | enable enableSeparateBuildPerCPUArchitecture 103 | universalApk false // If true, also generate a universal APK 104 | include "armeabi-v7a", "x86" 105 | } 106 | } 107 | buildTypes { 108 | release { 109 | minifyEnabled enableProguardInReleaseBuilds 110 | proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro" 111 | } 112 | } 113 | // applicationVariants are e.g. debug, release 114 | applicationVariants.all { variant -> 115 | variant.outputs.each { output -> 116 | // For each separate APK per architecture, set a unique version code as described here: 117 | // http://tools.android.com/tech-docs/new-build-system/user-guide/apk-splits 118 | def versionCodes = ["armeabi-v7a":1, "x86":2] 119 | def abi = output.getFilter(OutputFile.ABI) 120 | if (abi != null) { // null for the universal-debug, universal-release variants 121 | output.versionCodeOverride = 122 | versionCodes.get(abi) * 1048576 + defaultConfig.versionCode 123 | } 124 | } 125 | } 126 | } 127 | 128 | dependencies { 129 | compile project(':react-native-aws-cognito-js') 130 | compile fileTree(dir: "libs", include: ["*.jar"]) 131 | compile "com.android.support:appcompat-v7:23.0.1" 132 | compile "com.facebook.react:react-native:+" // From node_modules 133 | } 134 | 135 | // Run this once to be able to run the application with BUCK 136 | // puts all compile dependencies into folder libs for BUCK to use 137 | task copyDownloadableDepsToLibs(type: Copy) { 138 | from configurations.compile 139 | into 'libs' 140 | } 141 | -------------------------------------------------------------------------------- /example/android/app/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # By default, the flags in this file are appended to flags specified 3 | # in /usr/local/Cellar/android-sdk/24.3.3/tools/proguard/proguard-android.txt 4 | # You can edit the include path and order by changing the proguardFiles 5 | # directive in build.gradle. 6 | # 7 | # For more details, see 8 | # http://developer.android.com/guide/developing/tools/proguard.html 9 | 10 | # Add any project specific keep options here: 11 | 12 | # If your project uses WebView with JS, uncomment the following 13 | # and specify the fully qualified class name to the JavaScript interface 14 | # class: 15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 16 | # public *; 17 | #} 18 | 19 | # Disabling obfuscation is useful if you collect stack traces from production crashes 20 | # (unless you are using a system that supports de-obfuscate the stack traces). 21 | -dontobfuscate 22 | 23 | # React Native 24 | 25 | # Keep our interfaces so they can be used by other ProGuard rules. 26 | # See http://sourceforge.net/p/proguard/bugs/466/ 27 | -keep,allowobfuscation @interface com.facebook.proguard.annotations.DoNotStrip 28 | -keep,allowobfuscation @interface com.facebook.proguard.annotations.KeepGettersAndSetters 29 | -keep,allowobfuscation @interface com.facebook.common.internal.DoNotStrip 30 | 31 | # Do not strip any method/class that is annotated with @DoNotStrip 32 | -keep @com.facebook.proguard.annotations.DoNotStrip class * 33 | -keep @com.facebook.common.internal.DoNotStrip class * 34 | -keepclassmembers class * { 35 | @com.facebook.proguard.annotations.DoNotStrip *; 36 | @com.facebook.common.internal.DoNotStrip *; 37 | } 38 | 39 | -keepclassmembers @com.facebook.proguard.annotations.KeepGettersAndSetters class * { 40 | void set*(***); 41 | *** get*(); 42 | } 43 | 44 | -keep class * extends com.facebook.react.bridge.JavaScriptModule { *; } 45 | -keep class * extends com.facebook.react.bridge.NativeModule { *; } 46 | -keepclassmembers,includedescriptorclasses class * { native ; } 47 | -keepclassmembers class * { @com.facebook.react.uimanager.UIProp ; } 48 | -keepclassmembers class * { @com.facebook.react.uimanager.annotations.ReactProp ; } 49 | -keepclassmembers class * { @com.facebook.react.uimanager.annotations.ReactPropGroup ; } 50 | 51 | -dontwarn com.facebook.react.** 52 | 53 | # okhttp 54 | 55 | -keepattributes Signature 56 | -keepattributes *Annotation* 57 | -keep class okhttp3.** { *; } 58 | -keep interface okhttp3.** { *; } 59 | -dontwarn okhttp3.** 60 | 61 | # okio 62 | 63 | -keep class sun.misc.Unsafe { *; } 64 | -dontwarn java.nio.file.* 65 | -dontwarn org.codehaus.mojo.animal_sniffer.IgnoreJRERequirement 66 | -dontwarn okio.** 67 | -------------------------------------------------------------------------------- /example/android/app/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 5 | 6 | 7 | 8 | 9 | 12 | 13 | 19 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | -------------------------------------------------------------------------------- /example/android/app/src/main/java/com/example/MainActivity.java: -------------------------------------------------------------------------------- 1 | package com.example; 2 | 3 | import com.facebook.react.ReactActivity; 4 | 5 | public class MainActivity extends ReactActivity { 6 | 7 | /** 8 | * Returns the name of the main component registered from JavaScript. 9 | * This is used to schedule rendering of the component. 10 | */ 11 | @Override 12 | protected String getMainComponentName() { 13 | return "example"; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /example/android/app/src/main/java/com/example/MainApplication.java: -------------------------------------------------------------------------------- 1 | package com.example; 2 | 3 | import android.app.Application; 4 | 5 | import com.facebook.react.ReactApplication; 6 | import com.airlabsinc.RNAWSCognitoPackage; 7 | import com.facebook.react.ReactNativeHost; 8 | import com.facebook.react.ReactPackage; 9 | import com.facebook.react.shell.MainReactPackage; 10 | import com.facebook.soloader.SoLoader; 11 | 12 | import java.util.Arrays; 13 | import java.util.List; 14 | 15 | public class MainApplication extends Application implements ReactApplication { 16 | 17 | private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) { 18 | @Override 19 | public boolean getUseDeveloperSupport() { 20 | return BuildConfig.DEBUG; 21 | } 22 | 23 | @Override 24 | protected List getPackages() { 25 | return Arrays.asList( 26 | new MainReactPackage(), 27 | new RNAWSCognitoPackage() 28 | ); 29 | } 30 | }; 31 | 32 | @Override 33 | public ReactNativeHost getReactNativeHost() { 34 | return mReactNativeHost; 35 | } 36 | 37 | @Override 38 | public void onCreate() { 39 | super.onCreate(); 40 | SoLoader.init(this, /* native exopackage */ false); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /example/android/app/src/main/res/mipmap-hdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AirLabsTeam/react-native-aws-cognito-js/b59ac92c583274804a374fc3ba0c302430af5341/example/android/app/src/main/res/mipmap-hdpi/ic_launcher.png -------------------------------------------------------------------------------- /example/android/app/src/main/res/mipmap-mdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AirLabsTeam/react-native-aws-cognito-js/b59ac92c583274804a374fc3ba0c302430af5341/example/android/app/src/main/res/mipmap-mdpi/ic_launcher.png -------------------------------------------------------------------------------- /example/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AirLabsTeam/react-native-aws-cognito-js/b59ac92c583274804a374fc3ba0c302430af5341/example/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png -------------------------------------------------------------------------------- /example/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AirLabsTeam/react-native-aws-cognito-js/b59ac92c583274804a374fc3ba0c302430af5341/example/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /example/android/app/src/main/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | example 3 | 4 | -------------------------------------------------------------------------------- /example/android/app/src/main/res/values/styles.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /example/android/build.gradle: -------------------------------------------------------------------------------- 1 | // Top-level build file where you can add configuration options common to all sub-projects/modules. 2 | 3 | buildscript { 4 | repositories { 5 | jcenter() 6 | } 7 | dependencies { 8 | classpath 'com.android.tools.build:gradle:2.2.3' 9 | 10 | // NOTE: Do not place your application dependencies here; they belong 11 | // in the individual module build.gradle files 12 | } 13 | } 14 | 15 | allprojects { 16 | repositories { 17 | mavenLocal() 18 | jcenter() 19 | maven { 20 | // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm 21 | url "$rootDir/../node_modules/react-native/android" 22 | } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /example/android/gradle.properties: -------------------------------------------------------------------------------- 1 | # Project-wide Gradle settings. 2 | 3 | # IDE (e.g. Android Studio) users: 4 | # Gradle settings configured through the IDE *will override* 5 | # any settings specified in this file. 6 | 7 | # For more details on how to configure your build environment visit 8 | # http://www.gradle.org/docs/current/userguide/build_environment.html 9 | 10 | # Specifies the JVM arguments used for the daemon process. 11 | # The setting is particularly useful for tweaking memory settings. 12 | # Default value: -Xmx10248m -XX:MaxPermSize=256m 13 | # org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8 14 | 15 | # When configured, Gradle will run in incubating parallel mode. 16 | # This option should only be used with decoupled projects. More details, visit 17 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects 18 | # org.gradle.parallel=true 19 | 20 | android.useDeprecatedNdk=true 21 | -------------------------------------------------------------------------------- /example/android/gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AirLabsTeam/react-native-aws-cognito-js/b59ac92c583274804a374fc3ba0c302430af5341/example/android/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /example/android/gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | zipStoreBase=GRADLE_USER_HOME 4 | zipStorePath=wrapper/dists 5 | distributionUrl=https\://services.gradle.org/distributions/gradle-2.14.1-all.zip 6 | -------------------------------------------------------------------------------- /example/android/gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 10 | DEFAULT_JVM_OPTS="" 11 | 12 | APP_NAME="Gradle" 13 | APP_BASE_NAME=`basename "$0"` 14 | 15 | # Use the maximum available, or set MAX_FD != -1 to use that value. 16 | MAX_FD="maximum" 17 | 18 | warn ( ) { 19 | echo "$*" 20 | } 21 | 22 | die ( ) { 23 | echo 24 | echo "$*" 25 | echo 26 | exit 1 27 | } 28 | 29 | # OS specific support (must be 'true' or 'false'). 30 | cygwin=false 31 | msys=false 32 | darwin=false 33 | case "`uname`" in 34 | CYGWIN* ) 35 | cygwin=true 36 | ;; 37 | Darwin* ) 38 | darwin=true 39 | ;; 40 | MINGW* ) 41 | msys=true 42 | ;; 43 | esac 44 | 45 | # For Cygwin, ensure paths are in UNIX format before anything is touched. 46 | if $cygwin ; then 47 | [ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"` 48 | fi 49 | 50 | # Attempt to set APP_HOME 51 | # Resolve links: $0 may be a link 52 | PRG="$0" 53 | # Need this for relative symlinks. 54 | while [ -h "$PRG" ] ; do 55 | ls=`ls -ld "$PRG"` 56 | link=`expr "$ls" : '.*-> \(.*\)$'` 57 | if expr "$link" : '/.*' > /dev/null; then 58 | PRG="$link" 59 | else 60 | PRG=`dirname "$PRG"`"/$link" 61 | fi 62 | done 63 | SAVED="`pwd`" 64 | cd "`dirname \"$PRG\"`/" >&- 65 | APP_HOME="`pwd -P`" 66 | cd "$SAVED" >&- 67 | 68 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 69 | 70 | # Determine the Java command to use to start the JVM. 71 | if [ -n "$JAVA_HOME" ] ; then 72 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 73 | # IBM's JDK on AIX uses strange locations for the executables 74 | JAVACMD="$JAVA_HOME/jre/sh/java" 75 | else 76 | JAVACMD="$JAVA_HOME/bin/java" 77 | fi 78 | if [ ! -x "$JAVACMD" ] ; then 79 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 80 | 81 | Please set the JAVA_HOME variable in your environment to match the 82 | location of your Java installation." 83 | fi 84 | else 85 | JAVACMD="java" 86 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 87 | 88 | Please set the JAVA_HOME variable in your environment to match the 89 | location of your Java installation." 90 | fi 91 | 92 | # Increase the maximum file descriptors if we can. 93 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then 94 | MAX_FD_LIMIT=`ulimit -H -n` 95 | if [ $? -eq 0 ] ; then 96 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 97 | MAX_FD="$MAX_FD_LIMIT" 98 | fi 99 | ulimit -n $MAX_FD 100 | if [ $? -ne 0 ] ; then 101 | warn "Could not set maximum file descriptor limit: $MAX_FD" 102 | fi 103 | else 104 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 105 | fi 106 | fi 107 | 108 | # For Darwin, add options to specify how the application appears in the dock 109 | if $darwin; then 110 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 111 | fi 112 | 113 | # For Cygwin, switch paths to Windows format before running java 114 | if $cygwin ; then 115 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 116 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 117 | 118 | # We build the pattern for arguments to be converted via cygpath 119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 120 | SEP="" 121 | for dir in $ROOTDIRSRAW ; do 122 | ROOTDIRS="$ROOTDIRS$SEP$dir" 123 | SEP="|" 124 | done 125 | OURCYGPATTERN="(^($ROOTDIRS))" 126 | # Add a user-defined pattern to the cygpath arguments 127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 129 | fi 130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 131 | i=0 132 | for arg in "$@" ; do 133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 135 | 136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 138 | else 139 | eval `echo args$i`="\"$arg\"" 140 | fi 141 | i=$((i+1)) 142 | done 143 | case $i in 144 | (0) set -- ;; 145 | (1) set -- "$args0" ;; 146 | (2) set -- "$args0" "$args1" ;; 147 | (3) set -- "$args0" "$args1" "$args2" ;; 148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 154 | esac 155 | fi 156 | 157 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules 158 | function splitJvmOpts() { 159 | JVM_OPTS=("$@") 160 | } 161 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS 162 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" 163 | 164 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" 165 | -------------------------------------------------------------------------------- /example/android/gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 12 | set DEFAULT_JVM_OPTS= 13 | 14 | set DIRNAME=%~dp0 15 | if "%DIRNAME%" == "" set DIRNAME=. 16 | set APP_BASE_NAME=%~n0 17 | set APP_HOME=%DIRNAME% 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windowz variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | if "%@eval[2+2]" == "4" goto 4NT_args 53 | 54 | :win9xME_args 55 | @rem Slurp the command line arguments. 56 | set CMD_LINE_ARGS= 57 | set _SKIP=2 58 | 59 | :win9xME_args_slurp 60 | if "x%~1" == "x" goto execute 61 | 62 | set CMD_LINE_ARGS=%* 63 | goto execute 64 | 65 | :4NT_args 66 | @rem Get arguments from the 4NT Shell from JP Software 67 | set CMD_LINE_ARGS=%$ 68 | 69 | :execute 70 | @rem Setup the command line 71 | 72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 73 | 74 | @rem Execute Gradle 75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 76 | 77 | :end 78 | @rem End local scope for the variables with windows NT shell 79 | if "%ERRORLEVEL%"=="0" goto mainEnd 80 | 81 | :fail 82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 83 | rem the _cmd.exe /c_ return code! 84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 85 | exit /b 1 86 | 87 | :mainEnd 88 | if "%OS%"=="Windows_NT" endlocal 89 | 90 | :omega 91 | -------------------------------------------------------------------------------- /example/android/keystores/BUCK: -------------------------------------------------------------------------------- 1 | keystore( 2 | name = "debug", 3 | properties = "debug.keystore.properties", 4 | store = "debug.keystore", 5 | visibility = [ 6 | "PUBLIC", 7 | ], 8 | ) 9 | -------------------------------------------------------------------------------- /example/android/keystores/debug.keystore.properties: -------------------------------------------------------------------------------- 1 | key.store=debug.keystore 2 | key.alias=androiddebugkey 3 | key.store.password=android 4 | key.alias.password=android 5 | -------------------------------------------------------------------------------- /example/android/settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'example' 2 | include ':react-native-aws-cognito-js' 3 | project(':react-native-aws-cognito-js').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-aws-cognito-js/android') 4 | 5 | include ':app' 6 | -------------------------------------------------------------------------------- /example/app.js: -------------------------------------------------------------------------------- 1 | import React, { Component } from 'react'; 2 | import { 3 | AppRegistry, 4 | StyleSheet, 5 | Text, 6 | TextInput, 7 | TouchableOpacity, 8 | View 9 | } from 'react-native'; 10 | 11 | import { 12 | Config, 13 | CognitoIdentityCredentials 14 | } from 'aws-sdk/dist/aws-sdk-react-native'; 15 | 16 | import { 17 | AuthenticationDetails, 18 | CognitoUser, 19 | CognitoUserPool, 20 | CognitoUserAttribute 21 | } from 'react-native-aws-cognito-js'; 22 | 23 | const appConfig = { 24 | region: '', 25 | IdentityPoolId: '', 26 | UserPoolId: '', 27 | ClientId: '', 28 | } 29 | 30 | Config.region = appConfig.region; 31 | 32 | export default class App extends Component { 33 | 34 | state = { 35 | username: '', 36 | password: '', 37 | } 38 | 39 | componentDidMount() { 40 | this.checkUser(); 41 | } 42 | 43 | checkUser = () => { 44 | const { username, password } = this.state; 45 | const authenticationData = { 46 | Username: username, 47 | Password: password, 48 | }; 49 | const authenticationDetails = new AuthenticationDetails(authenticationData); 50 | const poolData = { 51 | UserPoolId: appConfig.UserPoolId, 52 | ClientId: appConfig.ClientId 53 | }; 54 | const userPool = new CognitoUserPool(poolData); 55 | userPool.storage.sync((err, result) => { 56 | // AsyncStorage MemoryStorage variables are now synced 57 | // to userPool.storage and cognitoUser.storage values 58 | // for checking session and user with built in storage 59 | }); 60 | } 61 | 62 | login = () => { 63 | const { username, password } = this.state; 64 | const authenticationData = { 65 | Username: username, 66 | Password: password, 67 | }; 68 | const authenticationDetails = new AuthenticationDetails(authenticationData); 69 | const poolData = { 70 | UserPoolId: appConfig.UserPoolId, 71 | ClientId: appConfig.ClientId 72 | }; 73 | const userPool = new CognitoUserPool(poolData); 74 | const userData = { 75 | Username: username, 76 | Pool: userPool 77 | }; 78 | const cognitoUser = new CognitoUser(userData); 79 | cognitoUser.authenticateUser(authenticationDetails, { 80 | onSuccess: (result) => { 81 | console.log('access token + ' + result.getAccessToken().getJwtToken()); 82 | Config.credentials = new CognitoIdentityCredentials({ 83 | IdentityPoolId: appConfig.IdentityPoolId, 84 | Logins: { 85 | [`cognito-idp.${appConfig.region}.amazonaws.com/${appConfig.UserPoolId}`]: result.getIdToken().getJwtToken() 86 | } 87 | }); 88 | alert('Success'); 89 | console.log(Config.credentials); 90 | }, 91 | onFailure: (err) => { 92 | alert(err); 93 | }, 94 | }); 95 | } 96 | 97 | render() { 98 | return ( 99 | 100 | this.setState({ username })} 102 | style={[styles.input, styles.formElement]} 103 | autoCapitalize={'none'} 104 | placeholder={'Username'} 105 | spellCheck={false} 106 | placeholderTextColor={'#aaa'} 107 | keyboardType={'default'} 108 | defaultValue="" 109 | /> 110 | this.setState({ password })} 112 | style={[styles.input, styles.formElement]} 113 | placeholder={'Password'} 114 | placeholderTextColor={'#aaa'} 115 | keyboardType={'default'} 116 | secureTextEntry 117 | defaultValue="" 118 | /> 119 | this.login()}> 120 | Submit 121 | 122 | 123 | ); 124 | } 125 | } 126 | 127 | const styles = StyleSheet.create({ 128 | container: { 129 | flex: 1, 130 | justifyContent: 'center', 131 | backgroundColor: '#eeeeee', 132 | }, 133 | input: { 134 | height: 40, 135 | backgroundColor: '#fff', 136 | borderColor: '#777', 137 | color: '#333', 138 | }, 139 | formElement: { 140 | borderWidth: StyleSheet.hairlineWidth, 141 | borderRadius: 4, 142 | marginHorizontal: 20, 143 | marginBottom: 10, 144 | paddingHorizontal: 10, 145 | justifyContent: 'center', 146 | alignItems: 'center', 147 | }, 148 | button: { 149 | height: 40, 150 | backgroundColor: '#333', 151 | }, 152 | buttonText: { 153 | color: '#fff' 154 | }, 155 | }); 156 | -------------------------------------------------------------------------------- /example/app.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "example", 3 | "displayName": "example" 4 | } -------------------------------------------------------------------------------- /example/index.android.js: -------------------------------------------------------------------------------- 1 | import { AppRegistry } from 'react-native'; 2 | import App from './app'; 3 | 4 | AppRegistry.registerComponent('example', () => App); -------------------------------------------------------------------------------- /example/index.ios.js: -------------------------------------------------------------------------------- 1 | import { AppRegistry } from 'react-native'; 2 | import App from './app'; 3 | 4 | AppRegistry.registerComponent('example', () => App); -------------------------------------------------------------------------------- /example/ios/example-tvOS/Info.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | CFBundleDevelopmentRegion 6 | en 7 | CFBundleExecutable 8 | $(EXECUTABLE_NAME) 9 | CFBundleIdentifier 10 | org.reactjs.native.example.$(PRODUCT_NAME:rfc1034identifier) 11 | CFBundleInfoDictionaryVersion 12 | 6.0 13 | CFBundleName 14 | $(PRODUCT_NAME) 15 | CFBundlePackageType 16 | APPL 17 | CFBundleShortVersionString 18 | 1.0 19 | CFBundleSignature 20 | ???? 21 | CFBundleVersion 22 | 1 23 | LSRequiresIPhoneOS 24 | 25 | UILaunchStoryboardName 26 | LaunchScreen 27 | UIRequiredDeviceCapabilities 28 | 29 | armv7 30 | 31 | UISupportedInterfaceOrientations 32 | 33 | UIInterfaceOrientationPortrait 34 | UIInterfaceOrientationLandscapeLeft 35 | UIInterfaceOrientationLandscapeRight 36 | 37 | UIViewControllerBasedStatusBarAppearance 38 | 39 | NSLocationWhenInUseUsageDescription 40 | 41 | NSAppTransportSecurity 42 | 43 | 44 | NSExceptionDomains 45 | 46 | localhost 47 | 48 | NSExceptionAllowsInsecureHTTPLoads 49 | 50 | 51 | 52 | 53 | 54 | 55 | -------------------------------------------------------------------------------- /example/ios/example-tvOSTests/Info.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | CFBundleDevelopmentRegion 6 | en 7 | CFBundleExecutable 8 | $(EXECUTABLE_NAME) 9 | CFBundleIdentifier 10 | org.reactjs.native.example.$(PRODUCT_NAME:rfc1034identifier) 11 | CFBundleInfoDictionaryVersion 12 | 6.0 13 | CFBundleName 14 | $(PRODUCT_NAME) 15 | CFBundlePackageType 16 | BNDL 17 | CFBundleShortVersionString 18 | 1.0 19 | CFBundleSignature 20 | ???? 21 | CFBundleVersion 22 | 1 23 | 24 | 25 | -------------------------------------------------------------------------------- /example/ios/example.xcodeproj/xcshareddata/xcschemes/example-tvOS.xcscheme: -------------------------------------------------------------------------------- 1 | 2 | 5 | 8 | 9 | 15 | 21 | 22 | 23 | 29 | 35 | 36 | 37 | 43 | 49 | 50 | 51 | 52 | 53 | 58 | 59 | 61 | 67 | 68 | 69 | 70 | 71 | 77 | 78 | 79 | 80 | 81 | 82 | 92 | 94 | 100 | 101 | 102 | 103 | 104 | 105 | 111 | 113 | 119 | 120 | 121 | 122 | 124 | 125 | 128 | 129 | 130 | -------------------------------------------------------------------------------- /example/ios/example.xcodeproj/xcshareddata/xcschemes/example.xcscheme: -------------------------------------------------------------------------------- 1 | 2 | 5 | 8 | 9 | 15 | 21 | 22 | 23 | 29 | 35 | 36 | 37 | 43 | 49 | 50 | 51 | 52 | 53 | 58 | 59 | 61 | 67 | 68 | 69 | 70 | 71 | 77 | 78 | 79 | 80 | 81 | 82 | 92 | 94 | 100 | 101 | 102 | 103 | 104 | 105 | 111 | 113 | 119 | 120 | 121 | 122 | 124 | 125 | 128 | 129 | 130 | -------------------------------------------------------------------------------- /example/ios/example/AppDelegate.h: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) 2015-present, Facebook, Inc. 3 | * All rights reserved. 4 | * 5 | * This source code is licensed under the BSD-style license found in the 6 | * LICENSE file in the root directory of this source tree. An additional grant 7 | * of patent rights can be found in the PATENTS file in the same directory. 8 | */ 9 | 10 | #import 11 | 12 | @interface AppDelegate : UIResponder 13 | 14 | @property (nonatomic, strong) UIWindow *window; 15 | 16 | @end 17 | -------------------------------------------------------------------------------- /example/ios/example/AppDelegate.m: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) 2015-present, Facebook, Inc. 3 | * All rights reserved. 4 | * 5 | * This source code is licensed under the BSD-style license found in the 6 | * LICENSE file in the root directory of this source tree. An additional grant 7 | * of patent rights can be found in the PATENTS file in the same directory. 8 | */ 9 | 10 | #import "AppDelegate.h" 11 | 12 | #import 13 | #import 14 | 15 | @implementation AppDelegate 16 | 17 | - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 18 | { 19 | NSURL *jsCodeLocation; 20 | 21 | jsCodeLocation = [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index.ios" fallbackResource:nil]; 22 | 23 | RCTRootView *rootView = [[RCTRootView alloc] initWithBundleURL:jsCodeLocation 24 | moduleName:@"example" 25 | initialProperties:nil 26 | launchOptions:launchOptions]; 27 | rootView.backgroundColor = [[UIColor alloc] initWithRed:1.0f green:1.0f blue:1.0f alpha:1]; 28 | 29 | self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds]; 30 | UIViewController *rootViewController = [UIViewController new]; 31 | rootViewController.view = rootView; 32 | self.window.rootViewController = rootViewController; 33 | [self.window makeKeyAndVisible]; 34 | return YES; 35 | } 36 | 37 | @end 38 | -------------------------------------------------------------------------------- /example/ios/example/Base.lproj/LaunchScreen.xib: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 21 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | -------------------------------------------------------------------------------- /example/ios/example/Images.xcassets/AppIcon.appiconset/Contents.json: -------------------------------------------------------------------------------- 1 | { 2 | "images" : [ 3 | { 4 | "idiom" : "iphone", 5 | "size" : "29x29", 6 | "scale" : "2x" 7 | }, 8 | { 9 | "idiom" : "iphone", 10 | "size" : "29x29", 11 | "scale" : "3x" 12 | }, 13 | { 14 | "idiom" : "iphone", 15 | "size" : "40x40", 16 | "scale" : "2x" 17 | }, 18 | { 19 | "idiom" : "iphone", 20 | "size" : "40x40", 21 | "scale" : "3x" 22 | }, 23 | { 24 | "idiom" : "iphone", 25 | "size" : "60x60", 26 | "scale" : "2x" 27 | }, 28 | { 29 | "idiom" : "iphone", 30 | "size" : "60x60", 31 | "scale" : "3x" 32 | } 33 | ], 34 | "info" : { 35 | "version" : 1, 36 | "author" : "xcode" 37 | } 38 | } -------------------------------------------------------------------------------- /example/ios/example/Info.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | CFBundleDevelopmentRegion 6 | en 7 | CFBundleDisplayName 8 | example 9 | CFBundleExecutable 10 | $(EXECUTABLE_NAME) 11 | CFBundleIdentifier 12 | org.reactjs.native.example.$(PRODUCT_NAME:rfc1034identifier) 13 | CFBundleInfoDictionaryVersion 14 | 6.0 15 | CFBundleName 16 | $(PRODUCT_NAME) 17 | CFBundlePackageType 18 | APPL 19 | CFBundleShortVersionString 20 | 1.0 21 | CFBundleSignature 22 | ???? 23 | CFBundleVersion 24 | 1 25 | LSRequiresIPhoneOS 26 | 27 | UILaunchStoryboardName 28 | LaunchScreen 29 | UIRequiredDeviceCapabilities 30 | 31 | armv7 32 | 33 | UISupportedInterfaceOrientations 34 | 35 | UIInterfaceOrientationPortrait 36 | UIInterfaceOrientationLandscapeLeft 37 | UIInterfaceOrientationLandscapeRight 38 | 39 | UIViewControllerBasedStatusBarAppearance 40 | 41 | NSLocationWhenInUseUsageDescription 42 | 43 | NSAppTransportSecurity 44 | 45 | 46 | NSExceptionDomains 47 | 48 | localhost 49 | 50 | NSExceptionAllowsInsecureHTTPLoads 51 | 52 | 53 | 54 | 55 | 56 | 57 | -------------------------------------------------------------------------------- /example/ios/example/main.m: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) 2015-present, Facebook, Inc. 3 | * All rights reserved. 4 | * 5 | * This source code is licensed under the BSD-style license found in the 6 | * LICENSE file in the root directory of this source tree. An additional grant 7 | * of patent rights can be found in the PATENTS file in the same directory. 8 | */ 9 | 10 | #import 11 | 12 | #import "AppDelegate.h" 13 | 14 | int main(int argc, char * argv[]) { 15 | @autoreleasepool { 16 | return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class])); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /example/ios/exampleTests/Info.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | CFBundleDevelopmentRegion 6 | en 7 | CFBundleExecutable 8 | $(EXECUTABLE_NAME) 9 | CFBundleIdentifier 10 | org.reactjs.native.example.$(PRODUCT_NAME:rfc1034identifier) 11 | CFBundleInfoDictionaryVersion 12 | 6.0 13 | CFBundleName 14 | $(PRODUCT_NAME) 15 | CFBundlePackageType 16 | BNDL 17 | CFBundleShortVersionString 18 | 1.0 19 | CFBundleSignature 20 | ???? 21 | CFBundleVersion 22 | 1 23 | 24 | 25 | -------------------------------------------------------------------------------- /example/ios/exampleTests/exampleTests.m: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) 2015-present, Facebook, Inc. 3 | * All rights reserved. 4 | * 5 | * This source code is licensed under the BSD-style license found in the 6 | * LICENSE file in the root directory of this source tree. An additional grant 7 | * of patent rights can be found in the PATENTS file in the same directory. 8 | */ 9 | 10 | #import 11 | #import 12 | 13 | #import 14 | #import 15 | 16 | #define TIMEOUT_SECONDS 600 17 | #define TEXT_TO_LOOK_FOR @"Welcome to React Native!" 18 | 19 | @interface exampleTests : XCTestCase 20 | 21 | @end 22 | 23 | @implementation exampleTests 24 | 25 | - (BOOL)findSubviewInView:(UIView *)view matching:(BOOL(^)(UIView *view))test 26 | { 27 | if (test(view)) { 28 | return YES; 29 | } 30 | for (UIView *subview in [view subviews]) { 31 | if ([self findSubviewInView:subview matching:test]) { 32 | return YES; 33 | } 34 | } 35 | return NO; 36 | } 37 | 38 | - (void)testRendersWelcomeScreen 39 | { 40 | UIViewController *vc = [[[[UIApplication sharedApplication] delegate] window] rootViewController]; 41 | NSDate *date = [NSDate dateWithTimeIntervalSinceNow:TIMEOUT_SECONDS]; 42 | BOOL foundElement = NO; 43 | 44 | __block NSString *redboxError = nil; 45 | RCTSetLogFunction(^(RCTLogLevel level, RCTLogSource source, NSString *fileName, NSNumber *lineNumber, NSString *message) { 46 | if (level >= RCTLogLevelError) { 47 | redboxError = message; 48 | } 49 | }); 50 | 51 | while ([date timeIntervalSinceNow] > 0 && !foundElement && !redboxError) { 52 | [[NSRunLoop mainRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow:0.1]]; 53 | [[NSRunLoop mainRunLoop] runMode:NSRunLoopCommonModes beforeDate:[NSDate dateWithTimeIntervalSinceNow:0.1]]; 54 | 55 | foundElement = [self findSubviewInView:vc.view matching:^BOOL(UIView *view) { 56 | if ([view.accessibilityLabel isEqualToString:TEXT_TO_LOOK_FOR]) { 57 | return YES; 58 | } 59 | return NO; 60 | }]; 61 | } 62 | 63 | RCTSetLogFunction(RCTDefaultLogFunction); 64 | 65 | XCTAssertNil(redboxError, @"RedBox error: %@", redboxError); 66 | XCTAssertTrue(foundElement, @"Couldn't find element with text '%@' in %d seconds", TEXT_TO_LOOK_FOR, TIMEOUT_SECONDS); 67 | } 68 | 69 | 70 | @end 71 | -------------------------------------------------------------------------------- /example/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "example", 3 | "version": "0.0.1", 4 | "private": true, 5 | "scripts": { 6 | "start": "node node_modules/react-native/local-cli/cli.js start", 7 | "test": "jest" 8 | }, 9 | "dependencies": { 10 | "react": "16.0.0-alpha.6", 11 | "react-native": "0.43.4", 12 | "react-native-aws-cognito-js": "../" 13 | }, 14 | "devDependencies": { 15 | "babel-jest": "19.0.0", 16 | "babel-preset-react-native": "1.9.1", 17 | "jest": "19.0.2", 18 | "react-test-renderer": "16.0.0-alpha.6" 19 | }, 20 | "jest": { 21 | "preset": "react-native" 22 | } 23 | } -------------------------------------------------------------------------------- /index.js: -------------------------------------------------------------------------------- 1 | import { NativeModules } from 'react-native'; 2 | import AWS, { CognitoIdentityServiceProvider } from 'aws-sdk/dist/aws-sdk-react-native'; 3 | import * as enhancements from './src'; 4 | export * from './src'; 5 | 6 | Object.keys(enhancements).forEach(key => { 7 | CognitoIdentityServiceProvider[key] = enhancements[key]; 8 | }); 9 | -------------------------------------------------------------------------------- /ios/JKBigInteger/JKBigDecimal.h: -------------------------------------------------------------------------------- 1 | // 2 | // JKBigDecimal.h 3 | // JKBigInteger 4 | // 5 | // Created by Midfar Sun on 5/4/15. 6 | // Copyright (c) 2015 Midfar Sun. All rights reserved. 7 | // 8 | 9 | #import 10 | #import "JKBigInteger.h" 11 | 12 | @interface JKBigDecimal : NSObject 13 | 14 | @property(nonatomic, retain)JKBigInteger *bigInteger; 15 | @property(nonatomic, assign)NSUInteger figure;//小数位数 16 | 17 | + (id)decimalWithString:(NSString *)string; 18 | - (id)initWithString:(NSString *)string; 19 | 20 | - (id)add:(JKBigDecimal *)bigDecimal; 21 | - (id)subtract:(JKBigDecimal *)bigDecimal; 22 | - (id)multiply:(JKBigDecimal *)bigDecimal; 23 | - (id)divide:(JKBigDecimal *)bigDecimal; 24 | 25 | - (id)remainder:(JKBigDecimal *)bigInteger; 26 | //- (NSArray *)divideAndRemainder:(JKBigDecimal *)bigInteger; 27 | 28 | - (NSComparisonResult) compare:(JKBigDecimal *)other; 29 | - (id)pow:(unsigned int)exponent; 30 | 31 | - (id)negate; 32 | - (id)abs; 33 | 34 | - (NSString *)stringValue; 35 | 36 | - (NSString *)description; 37 | 38 | @end 39 | -------------------------------------------------------------------------------- /ios/JKBigInteger/JKBigDecimal.m: -------------------------------------------------------------------------------- 1 | // 2 | // JKBigDecimal.m 3 | // JKBigInteger 4 | // 5 | // Created by Midfar Sun on 5/4/15. 6 | // Copyright (c) 2015 Midfar Sun. All rights reserved. 7 | // 8 | 9 | #import "JKBigDecimal.h" 10 | 11 | @implementation JKBigDecimal 12 | @synthesize bigInteger, figure; 13 | 14 | - (id)init 15 | { 16 | return [self initWithString:@"0"]; 17 | } 18 | 19 | - (id)initWithString:(NSString *)string 20 | { 21 | self = [super init]; 22 | if (self) { 23 | figure = 0; 24 | if ([string containsString:@"."]) { 25 | NSRange range = [string rangeOfString:@"."]; 26 | figure = string.length-range.location-range.length; 27 | string = [string stringByReplacingCharactersInRange:range withString:@""]; 28 | } 29 | bigInteger = [[JKBigInteger alloc] initWithString:string]; 30 | } 31 | return self; 32 | } 33 | 34 | + (id)decimalWithString:(NSString *)string 35 | { 36 | return [[JKBigDecimal alloc] initWithString:string]; 37 | } 38 | 39 | -(id)initWithBigInteger:(JKBigInteger *)i figure:(NSInteger)f 40 | { 41 | self = [super init]; 42 | if (self) { 43 | bigInteger = i; 44 | figure = f; 45 | } 46 | return self; 47 | } 48 | 49 | - (instancetype)initWithCoder:(NSCoder *)decoder 50 | { 51 | self = [super init]; 52 | if (self) { 53 | bigInteger = [[JKBigInteger alloc] initWithCoder:decoder]; 54 | figure = [decoder decodeInt32ForKey:@"JKBigDecimalFigure"]; 55 | } 56 | return self; 57 | } 58 | -(void)encodeWithCoder:(NSCoder *)encoder 59 | { 60 | [bigInteger encodeWithCoder:encoder]; 61 | [encoder encodeInteger:figure forKey:@"JKBigDecimalFigure"]; 62 | } 63 | 64 | - (id)add:(JKBigDecimal *)bigDecimal 65 | { 66 | NSInteger maxFigure = 0; 67 | if (figure>=bigDecimal.figure) { 68 | maxFigure = figure; 69 | NSInteger exponent = maxFigure-bigDecimal.figure; 70 | JKBigInteger *mInteger = [[JKBigInteger alloc] initWithString:@"10"]; 71 | JKBigInteger *newInteger = [mInteger pow:(unsigned int)exponent]; 72 | bigDecimal.bigInteger = [bigDecimal.bigInteger multiply:newInteger]; 73 | bigDecimal.figure = maxFigure; 74 | 75 | }else{ 76 | maxFigure = bigDecimal.figure; 77 | NSInteger exponent = maxFigure-figure; 78 | JKBigInteger *mInteger = [[JKBigInteger alloc] initWithString:@"10"]; 79 | JKBigInteger *newInteger = [mInteger pow:(unsigned int)exponent]; 80 | bigInteger = [bigInteger multiply:newInteger]; 81 | figure = maxFigure; 82 | 83 | } 84 | JKBigInteger *newBigInteger = [bigInteger add:bigDecimal.bigInteger]; 85 | JKBigDecimal *newBigDecimal = [[JKBigDecimal alloc] initWithBigInteger:newBigInteger figure:maxFigure]; 86 | return newBigDecimal; 87 | } 88 | 89 | - (id)subtract:(JKBigDecimal *)bigDecimal 90 | { 91 | NSInteger maxFigure = 0; 92 | if (figure>=bigDecimal.figure) { 93 | maxFigure = figure; 94 | NSInteger exponent = maxFigure-bigDecimal.figure; 95 | JKBigInteger *mInteger = [[JKBigInteger alloc] initWithString:@"10"]; 96 | JKBigInteger *newInteger = [mInteger pow:(unsigned int)exponent]; 97 | bigDecimal.bigInteger = [bigDecimal.bigInteger multiply:newInteger]; 98 | bigDecimal.figure = maxFigure; 99 | 100 | }else{ 101 | maxFigure = bigDecimal.figure; 102 | NSInteger exponent = maxFigure-figure; 103 | JKBigInteger *mInteger = [[JKBigInteger alloc] initWithString:@"10"]; 104 | JKBigInteger *newInteger = [mInteger pow:(unsigned int)exponent]; 105 | bigInteger = [bigDecimal.bigInteger multiply:newInteger]; 106 | figure = maxFigure; 107 | 108 | } 109 | JKBigInteger *newBigInteger = [bigInteger subtract:bigDecimal.bigInteger]; 110 | JKBigDecimal *newBigDecimal = [[JKBigDecimal alloc] initWithBigInteger:newBigInteger figure:maxFigure]; 111 | return newBigDecimal; 112 | } 113 | 114 | - (id)multiply:(JKBigDecimal *)bigDecimal 115 | { 116 | NSInteger totalFigure = figure+bigDecimal.figure; 117 | JKBigInteger *newBigInteger = [bigInteger multiply:bigDecimal.bigInteger]; 118 | JKBigDecimal *newBigDecimal = [[JKBigDecimal alloc] initWithBigInteger:newBigInteger figure:totalFigure]; 119 | return newBigDecimal; 120 | } 121 | 122 | - (id)divide:(JKBigDecimal *)bigDecimal 123 | { 124 | NSInteger totalFigure = figure-bigDecimal.figure; 125 | if (totalFigure<0) { 126 | NSInteger exponent = -totalFigure; 127 | totalFigure=0; 128 | JKBigInteger *mInteger = [[JKBigInteger alloc] initWithString:@"10"]; 129 | JKBigInteger *newInteger = [mInteger pow:(unsigned int)exponent]; 130 | bigInteger = [bigInteger multiply:newInteger]; 131 | } 132 | JKBigInteger *newBigInteger = [bigInteger divide:bigDecimal.bigInteger]; 133 | JKBigDecimal *newBigDecimal = [[JKBigDecimal alloc] initWithBigInteger:newBigInteger figure:totalFigure]; 134 | return newBigDecimal; 135 | } 136 | 137 | - (id)remainder:(JKBigDecimal *)bigDecimal 138 | { 139 | NSInteger totalFigure = figure-bigDecimal.figure; 140 | if (totalFigure<0) { 141 | NSInteger exponent = -totalFigure; 142 | totalFigure=0; 143 | JKBigInteger *mInteger = [[JKBigInteger alloc] initWithString:@"10"]; 144 | JKBigInteger *newInteger = [mInteger pow:(unsigned int)exponent]; 145 | bigInteger = [bigInteger multiply:newInteger]; 146 | } 147 | JKBigInteger *newBigInteger = [bigInteger remainder:bigDecimal.bigInteger]; 148 | JKBigDecimal *newBigDecimal = [[JKBigDecimal alloc] initWithBigInteger:newBigInteger figure:bigDecimal.figure]; 149 | return newBigDecimal; 150 | } 151 | 152 | //- (NSArray *)divideAndRemainder:(JKBigDecimal *)bigInteger 153 | //{ 154 | // 155 | //} 156 | 157 | -(NSComparisonResult) compare:(JKBigDecimal *)other { 158 | JKBigDecimal *tens = [[JKBigDecimal alloc] initWithString:@"10"]; 159 | JKBigInteger *scaledNum; 160 | JKBigInteger *scaledCompareTo; 161 | 162 | if (figure > other.figure){ 163 | tens = [tens pow:(int)figure]; 164 | } else { 165 | tens = [tens pow:(int)other.figure]; 166 | } 167 | //scale my value to integer value 168 | scaledNum = [[JKBigInteger alloc] initWithString:[[self multiply:tens] stringValue]]; 169 | //scale other value to integer 170 | scaledCompareTo = [[JKBigInteger alloc] initWithString:[[other multiply:tens] stringValue]]; 171 | NSComparisonResult compareBigInteger = [scaledNum compare:scaledCompareTo]; 172 | return compareBigInteger; 173 | } 174 | 175 | - (id)pow:(unsigned int)exponent 176 | { 177 | NSInteger totalFigure = figure*exponent; 178 | JKBigInteger *newBigInteger = [bigInteger pow:exponent]; 179 | JKBigDecimal *newBigDecimal = [[JKBigDecimal alloc] initWithBigInteger:newBigInteger figure:totalFigure]; 180 | return newBigDecimal; 181 | } 182 | 183 | - (id)negate 184 | { 185 | JKBigInteger *newBigInteger = [bigInteger negate]; 186 | JKBigDecimal *newBigDecimal = [[JKBigDecimal alloc] initWithBigInteger:newBigInteger figure:figure]; 187 | return newBigDecimal; 188 | } 189 | 190 | - (id)abs 191 | { 192 | JKBigInteger *newBigInteger = [bigInteger abs]; 193 | JKBigDecimal *newBigDecimal = [[JKBigDecimal alloc] initWithBigInteger:newBigInteger figure:figure]; 194 | return newBigDecimal; 195 | } 196 | 197 | - (NSString *)stringValue 198 | { 199 | NSString *string = [bigInteger stringValue]; 200 | if (figure==0) { 201 | return string; 202 | } 203 | NSMutableString *mString = [NSMutableString stringWithString:string]; 204 | NSInteger newFigure = string.length-figure; 205 | while (newFigure<=0) { 206 | [mString insertString:@"0" atIndex:0]; 207 | newFigure++; 208 | } 209 | [mString insertString:@"." atIndex:newFigure]; 210 | return mString; 211 | } 212 | 213 | - (NSString *)description 214 | { 215 | return [self stringValue]; 216 | } 217 | 218 | @end 219 | -------------------------------------------------------------------------------- /ios/JKBigInteger/JKBigInteger.h: -------------------------------------------------------------------------------- 1 | // 2 | // JKBigInteger.h 3 | // JKBigInteger 4 | // 5 | // Created by Jānis Kiršteins on 5/21/13. 6 | // Copyright (c) 2013 Jānis Kiršteins. All rights reserved. 7 | // 8 | 9 | #import 10 | #include "tommath.h" 11 | 12 | @interface JKBigInteger : NSObject 13 | 14 | - (id)initWithValue:(mp_int *)value; 15 | - (mp_int *)value; 16 | 17 | - (id)initWithUnsignedLong:(unsigned long)ul; 18 | - (id)initWithString:(NSString *)string; 19 | - (id)initWithString:(NSString *)string andRadix:(int)radix; 20 | - (id)initWithCString:(char *)cString; 21 | - (id)initWithCString:(char *)cString andRadix:(int)radix; 22 | 23 | - (id)add:(JKBigInteger *)bigInteger; 24 | - (id)subtract:(JKBigInteger *)bigInteger; 25 | - (id)multiply:(JKBigInteger *)bigInteger; 26 | - (id)divide:(JKBigInteger *)bigInteger; 27 | 28 | - (id)remainder:(JKBigInteger *)bigInteger; 29 | - (NSArray *)divideAndRemainder:(JKBigInteger *)bigInteger; 30 | 31 | - (id)pow:(unsigned int)exponent; 32 | - (id)pow:(JKBigInteger*)exponent andMod:(JKBigInteger*)modulus; 33 | - (id)negate; 34 | - (id)abs; 35 | 36 | - (id)bitwiseXor:(JKBigInteger *)bigInteger; 37 | - (id)bitwiseOr:(JKBigInteger *)bigInteger; 38 | - (id)bitwiseAnd:(JKBigInteger *)bigInteger; 39 | - (id)shiftLeft:(unsigned int)n; 40 | - (id)shiftRight:(unsigned int)n; 41 | 42 | - (id)gcd:(JKBigInteger *)bigInteger; 43 | 44 | - (NSComparisonResult) compare:(JKBigInteger *)bigInteger; 45 | 46 | - (unsigned long)unsignedIntValue; 47 | - (NSString *)stringValue; 48 | - (NSString *)stringValueWithRadix:(int)radix; 49 | 50 | - (NSString *)description; 51 | 52 | - (unsigned int)countBytes; 53 | - (void)toByteArraySigned: (unsigned char*) byteArray; 54 | - (void)toByteArrayUnsigned: (unsigned char*) byteArray; 55 | 56 | @end 57 | -------------------------------------------------------------------------------- /ios/JKBigInteger/JKBigInteger.m: -------------------------------------------------------------------------------- 1 | // 2 | // JKBigInteger.m 3 | // JKBigInteger 4 | // 5 | // Created by Jānis Kiršteins on 5/21/13. 6 | // Copyright (c) 2013 Jānis Kiršteins. All rights reserved. 7 | // 8 | #import "JKBigInteger.h" 9 | 10 | @implementation JKBigInteger { 11 | @private 12 | mp_int m_value; 13 | } 14 | 15 | - (id)initWithValue:(mp_int *)value { 16 | 17 | self = [super init]; 18 | 19 | if (self) { 20 | mp_init_copy(&m_value, value); 21 | } 22 | 23 | return self; 24 | } 25 | 26 | - (mp_int *)value { 27 | return &m_value; 28 | } 29 | 30 | - (id)initWithUnsignedLong:(unsigned long)unsignedLong { 31 | 32 | self = [super init]; 33 | 34 | if (self) { 35 | mp_set_int(&m_value, unsignedLong); 36 | } 37 | 38 | return self; 39 | } 40 | 41 | - (id)init { 42 | return [self initWithUnsignedLong:0]; 43 | } 44 | 45 | - (id)initWithCString:(char *)cString andRadix:(int)radix { 46 | 47 | if (radix < 2 || radix > 64) { 48 | return nil; 49 | } 50 | 51 | self = [super init]; 52 | 53 | if (self) { 54 | mp_init(&m_value); 55 | int result; 56 | result = mp_read_radix(&m_value, cString, radix); 57 | 58 | if (result != MP_OKAY) { 59 | mp_clear(&m_value); 60 | return nil; 61 | } 62 | } 63 | 64 | return self; 65 | } 66 | - (id)initWithCString:(char *)cString { 67 | 68 | int radix = 10; 69 | return [self initWithCString:cString andRadix:radix]; 70 | } 71 | 72 | - (id)initWithString:(NSString *)string andRadix:(int)radix { 73 | return [self initWithCString:(char *)[string UTF8String] andRadix:radix]; 74 | } 75 | 76 | - (id)initWithString:(NSString *)string { 77 | 78 | int radix = 10; 79 | return [self initWithCString:(char *)[string UTF8String] andRadix:radix]; 80 | } 81 | 82 | - (id)initWithCoder:(NSCoder *)decoder { 83 | 84 | self = [super init]; 85 | 86 | if (self) { 87 | int sign = [decoder decodeInt32ForKey:@"JKBigIntegerSign"]; 88 | int alloc = [decoder decodeInt32ForKey:@"JKBigIntegerAlloc"]; 89 | 90 | mp_init_size(&m_value, alloc); 91 | 92 | NSData *data = (NSData *)[decoder decodeObjectForKey:@"JKBigIntegerDP"]; 93 | mp_digit *temp = (mp_digit *)[data bytes]; 94 | 95 | for (unsigned int i = 0; i < alloc; ++i) { 96 | m_value.dp[i] = temp[i]; 97 | } 98 | 99 | m_value.used = alloc; 100 | m_value.sign = sign; 101 | } 102 | 103 | return self; 104 | } 105 | - (void)encodeWithCoder:(NSCoder *)encoder { 106 | 107 | mp_clamp(&m_value); 108 | 109 | NSData *data = [NSData dataWithBytes:(const void *)m_value.dp 110 | length:m_value.alloc * sizeof(mp_digit)]; 111 | 112 | [encoder encodeObject:data forKey:@"JKBigIntegerDP"]; 113 | [encoder encodeInteger:m_value.alloc forKey:@"JKBigIntegerAlloc"]; 114 | [encoder encodeInteger:m_value.sign forKey:@"JKBigIntegerSign"]; 115 | } 116 | 117 | - (id)add:(JKBigInteger *)bigInteger { 118 | 119 | mp_int sum; 120 | mp_init(&sum); 121 | 122 | mp_add(&m_value, [bigInteger value], &sum); 123 | 124 | id newBigInteger = [[JKBigInteger alloc] initWithValue:&sum]; 125 | mp_clear(&sum); 126 | 127 | return newBigInteger; 128 | } 129 | 130 | - (id)subtract:(JKBigInteger *)bigInteger { 131 | 132 | mp_int difference; 133 | mp_init(&difference); 134 | 135 | mp_sub(&m_value, [bigInteger value], &difference); 136 | 137 | id newBigInteger = [[JKBigInteger alloc] initWithValue:&difference]; 138 | mp_clear(&difference); 139 | 140 | return newBigInteger; 141 | } 142 | 143 | - (id)multiply:(JKBigInteger *)bigInteger { 144 | 145 | mp_int product; 146 | mp_init(&product); 147 | 148 | mp_mul(&m_value, [bigInteger value], &product); 149 | 150 | JKBigInteger *newBigInteger = [[JKBigInteger alloc] initWithValue:&product]; 151 | mp_clear(&product); 152 | 153 | return newBigInteger; 154 | } 155 | 156 | - (id)divide:(JKBigInteger *)bigInteger { 157 | 158 | int result; 159 | mp_int quotient; 160 | mp_init("ient); 161 | 162 | result = mp_div(&m_value, [bigInteger value], "ient, NULL); 163 | if (result == MP_VAL) { 164 | mp_clear("ient); 165 | return nil; 166 | } 167 | 168 | JKBigInteger *newBigInteger = [[JKBigInteger alloc] initWithValue:"ient]; 169 | mp_clear("ient); 170 | 171 | return newBigInteger; 172 | } 173 | 174 | - (id)remainder:(JKBigInteger *)bigInteger { 175 | 176 | int result; 177 | mp_int remainder; 178 | mp_init(&remainder); 179 | 180 | result = mp_div(&m_value, [bigInteger value], NULL, &remainder); 181 | if (result == MP_VAL) { 182 | mp_clear(&remainder); 183 | return nil; 184 | } 185 | 186 | JKBigInteger *newBigInteger = [[JKBigInteger alloc] initWithValue:&remainder]; 187 | mp_clear(&remainder); 188 | 189 | return newBigInteger; 190 | } 191 | 192 | - (NSArray *)divideAndRemainder:(JKBigInteger *)bigInteger { 193 | 194 | int result; 195 | mp_int quotient, remainder; 196 | mp_init_multi("ient, &remainder, NULL); 197 | 198 | result = mp_div(&m_value, [bigInteger value], "ient, &remainder); 199 | if (result == MP_VAL) { 200 | mp_clear_multi("ient, &remainder, NULL); 201 | return nil; 202 | } 203 | 204 | JKBigInteger *quotientBigInteger = [[JKBigInteger alloc] initWithValue:"ient]; 205 | JKBigInteger *remainderBigInteger = [[JKBigInteger alloc] initWithValue:&remainder]; 206 | mp_clear_multi("ient, &remainder, NULL); 207 | 208 | return @[quotientBigInteger, remainderBigInteger]; 209 | } 210 | 211 | - (id)pow:(unsigned int)exponent { 212 | 213 | int result; 214 | mp_int power; 215 | mp_init(&power); 216 | 217 | result = mp_expt_d(&m_value, (mp_digit)exponent, &power); 218 | if (result == MP_VAL) { 219 | mp_clear(&power); 220 | return nil; 221 | } 222 | 223 | JKBigInteger *newBigInteger = [[JKBigInteger alloc] initWithValue:&power]; 224 | mp_clear(&power); 225 | 226 | return newBigInteger; 227 | } 228 | 229 | - (id)pow:(JKBigInteger*)exponent andMod: (JKBigInteger*)modulus { 230 | 231 | int result; 232 | mp_int output; 233 | mp_init(&output); 234 | 235 | result = mp_exptmod(&m_value, &exponent->m_value, &modulus->m_value, &output); 236 | if (result == MP_VAL) { 237 | mp_clear(&output); 238 | return nil; 239 | } 240 | 241 | JKBigInteger *newBigInteger = [[JKBigInteger alloc] initWithValue:&output]; 242 | mp_clear(&output); 243 | 244 | return newBigInteger; 245 | } 246 | 247 | - (id)negate { 248 | 249 | mp_int negate; 250 | mp_init(&negate); 251 | mp_neg(&m_value, &negate); 252 | 253 | JKBigInteger *newBigInteger = [[JKBigInteger alloc] initWithValue:&negate]; 254 | mp_clear(&negate); 255 | 256 | return newBigInteger; 257 | } 258 | 259 | - (id)abs { 260 | 261 | mp_int absolute; 262 | mp_init(&absolute); 263 | mp_abs(&m_value, &absolute); 264 | 265 | JKBigInteger *newBigInteger = [[JKBigInteger alloc] initWithValue:&absolute]; 266 | mp_clear(&absolute); 267 | 268 | return newBigInteger; 269 | } 270 | 271 | - (id)bitwiseXor:(JKBigInteger *)bigInteger { 272 | 273 | mp_int xor; 274 | mp_init(&xor); 275 | mp_xor(&m_value, [bigInteger value], &xor); 276 | 277 | JKBigInteger *newBigInteger = [[JKBigInteger alloc] initWithValue:&xor]; 278 | mp_clear(&xor); 279 | 280 | return newBigInteger; 281 | } 282 | 283 | - (id)bitwiseOr:(JKBigInteger *)bigInteger { 284 | 285 | mp_int or; 286 | mp_init(&or); 287 | mp_or(&m_value, [bigInteger value], &or); 288 | 289 | JKBigInteger *newBigInteger = [[JKBigInteger alloc] initWithValue:&or]; 290 | mp_clear(&or); 291 | 292 | return newBigInteger; 293 | } 294 | 295 | - (id)bitwiseAnd:(JKBigInteger *)bigInteger { 296 | 297 | mp_int and; 298 | mp_init(&and); 299 | mp_and(&m_value, [bigInteger value], &and); 300 | 301 | JKBigInteger *newBigInteger = [[JKBigInteger alloc] initWithValue:&and]; 302 | mp_clear(&and); 303 | 304 | return newBigInteger; 305 | } 306 | 307 | - (id)shiftLeft:(unsigned int)n { 308 | 309 | mp_int lShift; 310 | mp_init(&lShift); 311 | mp_mul_2d(&m_value, n, &lShift); 312 | 313 | JKBigInteger *newBigInteger = [[JKBigInteger alloc] initWithValue:&lShift]; 314 | mp_clear(&lShift); 315 | 316 | return newBigInteger; 317 | } 318 | 319 | - (id)shiftRight:(unsigned int)n { 320 | 321 | mp_int rShift; 322 | mp_init(&rShift); 323 | mp_div_2d(&m_value, n, &rShift, NULL); 324 | 325 | JKBigInteger *newBigInteger = [[JKBigInteger alloc] initWithValue:&rShift]; 326 | mp_clear(&rShift); 327 | 328 | return newBigInteger; 329 | } 330 | - (id)gcd:(JKBigInteger *)bigInteger { 331 | 332 | int result; 333 | mp_int gcd; 334 | mp_init(&gcd); 335 | 336 | result = mp_gcd(&m_value, [bigInteger value], &gcd); 337 | if (result == MP_VAL) { 338 | mp_clear(&gcd); 339 | return nil; 340 | } 341 | 342 | JKBigInteger *newBigInteger = [[JKBigInteger alloc] initWithValue:&gcd]; 343 | mp_clear(&gcd); 344 | 345 | return newBigInteger; 346 | } 347 | 348 | - (NSComparisonResult) compare:(JKBigInteger *)bigInteger { 349 | 350 | NSComparisonResult comparisonResult; 351 | comparisonResult = mp_cmp([bigInteger value], &m_value); 352 | 353 | switch (comparisonResult) { 354 | case MP_GT: 355 | return NSOrderedAscending; 356 | case MP_EQ: 357 | return NSOrderedSame; 358 | case MP_LT: 359 | return NSOrderedDescending; 360 | default: 361 | return 0; 362 | } 363 | } 364 | 365 | - (unsigned long)unsignedIntValue { 366 | return mp_get_int(&m_value); 367 | } 368 | 369 | - (NSString *)stringValue { 370 | 371 | int radix = 10; 372 | return [self stringValueWithRadix:radix]; 373 | } 374 | 375 | - (NSString *)stringValueWithRadix:(int)radix { 376 | 377 | int stringSize; 378 | mp_radix_size(&m_value, radix, &stringSize); 379 | char cString[stringSize]; 380 | mp_toradix(&m_value, cString, radix); 381 | 382 | for (int i = 0; i < stringSize; ++i) { 383 | cString[i] = (char)tolower(cString[i]); 384 | } 385 | 386 | return [NSString stringWithUTF8String:cString]; 387 | } 388 | 389 | - (NSString *)description { 390 | return [self stringValue]; 391 | } 392 | 393 | - (void)dealloc { 394 | mp_clear(&m_value); 395 | } 396 | 397 | /* Returns the number of bytes required to store this JKBigInteger as binary */ 398 | - (unsigned int)countBytes { 399 | return (unsigned int) mp_unsigned_bin_size(&m_value); 400 | } 401 | 402 | /* Retrieves the signed [big endian] format of this JKBigInteger */ 403 | - (void)toByteArraySigned: (unsigned char*) byteArray { 404 | mp_to_signed_bin(&m_value, byteArray); 405 | } 406 | 407 | /* Retrieves the unsigned [big endian] format of this JKBigInteger */ 408 | - (void)toByteArrayUnsigned: (unsigned char*) byteArray { 409 | mp_to_unsigned_bin(&m_value, byteArray); 410 | } 411 | 412 | @end 413 | -------------------------------------------------------------------------------- /ios/JKBigInteger/LibTomMath/tommath.h: -------------------------------------------------------------------------------- 1 | /* LibTomMath, multiple-precision integer library -- Tom St Denis 2 | * 3 | * LibTomMath is a library that provides multiple-precision 4 | * integer arithmetic as well as number theoretic functionality. 5 | * 6 | * The library was designed directly after the MPI library by 7 | * Michael Fromberger but has been written from scratch with 8 | * additional optimizations in place. 9 | * 10 | * The library is free for all purposes without any express 11 | * guarantee it works. 12 | * 13 | * Tom St Denis, tomstdenis@gmail.com, http://math.libtomcrypt.com 14 | */ 15 | #ifndef BN_H_ 16 | #define BN_H_ 17 | 18 | #include 19 | #include 20 | #include 21 | #include 22 | #include 23 | 24 | #include "tommath_class.h" 25 | 26 | #ifndef MIN 27 | #define MIN(x,y) ((x)<(y)?(x):(y)) 28 | #endif 29 | 30 | #ifndef MAX 31 | #define MAX(x,y) ((x)>(y)?(x):(y)) 32 | #endif 33 | 34 | #ifdef __cplusplus 35 | extern "C" { 36 | 37 | /* C++ compilers don't like assigning void * to mp_digit * */ 38 | #define OPT_CAST(x) (x *) 39 | 40 | #else 41 | 42 | /* C on the other hand doesn't care */ 43 | #define OPT_CAST(x) 44 | 45 | #endif 46 | 47 | 48 | /* detect 64-bit mode if possible */ 49 | #if defined(__x86_64__) 50 | #if !(defined(MP_64BIT) && defined(MP_16BIT) && defined(MP_8BIT)) 51 | #define MP_64BIT 52 | #endif 53 | #endif 54 | 55 | /* some default configurations. 56 | * 57 | * A "mp_digit" must be able to hold DIGIT_BIT + 1 bits 58 | * A "mp_word" must be able to hold 2*DIGIT_BIT + 1 bits 59 | * 60 | * At the very least a mp_digit must be able to hold 7 bits 61 | * [any size beyond that is ok provided it doesn't overflow the data type] 62 | */ 63 | #ifdef MP_8BIT 64 | typedef unsigned char mp_digit; 65 | typedef unsigned short mp_word; 66 | #elif defined(MP_16BIT) 67 | typedef unsigned short mp_digit; 68 | typedef unsigned long mp_word; 69 | #elif defined(MP_64BIT) 70 | /* for GCC only on supported platforms */ 71 | #ifndef CRYPT 72 | typedef unsigned long long ulong64; 73 | typedef signed long long long64; 74 | #endif 75 | 76 | typedef unsigned long mp_digit; 77 | typedef unsigned long mp_word __attribute__ ((mode(TI))); 78 | 79 | #define DIGIT_BIT 60 80 | #else 81 | /* this is the default case, 28-bit digits */ 82 | 83 | /* this is to make porting into LibTomCrypt easier :-) */ 84 | #ifndef CRYPT 85 | #if defined(_MSC_VER) || defined(__BORLANDC__) 86 | typedef unsigned __int64 ulong64; 87 | typedef signed __int64 long64; 88 | #else 89 | typedef unsigned long long ulong64; 90 | typedef signed long long long64; 91 | #endif 92 | #endif 93 | 94 | typedef unsigned long mp_digit; 95 | typedef ulong64 mp_word; 96 | 97 | #ifdef MP_31BIT 98 | /* this is an extension that uses 31-bit digits */ 99 | #define DIGIT_BIT 31 100 | #else 101 | /* default case is 28-bit digits, defines MP_28BIT as a handy macro to test */ 102 | #define DIGIT_BIT 28 103 | #define MP_28BIT 104 | #endif 105 | #endif 106 | 107 | /* define heap macros */ 108 | #ifndef CRYPT 109 | /* default to libc stuff */ 110 | #ifndef XMALLOC 111 | #define XMALLOC malloc 112 | #define XFREE free 113 | #define XREALLOC realloc 114 | #define XCALLOC calloc 115 | #else 116 | /* prototypes for our heap functions */ 117 | extern void *XMALLOC(size_t n); 118 | extern void *XREALLOC(void *p, size_t n); 119 | extern void *XCALLOC(size_t n, size_t s); 120 | extern void XFREE(void *p); 121 | #endif 122 | #endif 123 | 124 | 125 | /* otherwise the bits per digit is calculated automatically from the size of a mp_digit */ 126 | #ifndef DIGIT_BIT 127 | #define DIGIT_BIT ((int)((CHAR_BIT * sizeof(mp_digit) - 1))) /* bits per digit */ 128 | #endif 129 | 130 | #define MP_DIGIT_BIT DIGIT_BIT 131 | #define MP_MASK ((((mp_digit)1)<<((mp_digit)DIGIT_BIT))-((mp_digit)1)) 132 | #define MP_DIGIT_MAX MP_MASK 133 | 134 | /* equalities */ 135 | #define MP_LT -1 /* less than */ 136 | #define MP_EQ 0 /* equal to */ 137 | #define MP_GT 1 /* greater than */ 138 | 139 | #define MP_ZPOS 0 /* positive integer */ 140 | #define MP_NEG 1 /* negative */ 141 | 142 | #define MP_OKAY 0 /* ok result */ 143 | #define MP_MEM -2 /* out of mem */ 144 | #define MP_VAL -3 /* invalid input */ 145 | #define MP_RANGE MP_VAL 146 | 147 | #define MP_YES 1 /* yes response */ 148 | #define MP_NO 0 /* no response */ 149 | 150 | /* Primality generation flags */ 151 | #define LTM_PRIME_BBS 0x0001 /* BBS style prime */ 152 | #define LTM_PRIME_SAFE 0x0002 /* Safe prime (p-1)/2 == prime */ 153 | #define LTM_PRIME_2MSB_ON 0x0008 /* force 2nd MSB to 1 */ 154 | 155 | typedef int mp_err; 156 | 157 | /* you'll have to tune these... */ 158 | extern int KARATSUBA_MUL_CUTOFF, 159 | KARATSUBA_SQR_CUTOFF, 160 | TOOM_MUL_CUTOFF, 161 | TOOM_SQR_CUTOFF; 162 | 163 | /* define this to use lower memory usage routines (exptmods mostly) */ 164 | /* #define MP_LOW_MEM */ 165 | 166 | /* default precision */ 167 | #ifndef MP_PREC 168 | #ifndef MP_LOW_MEM 169 | #define MP_PREC 32 /* default digits of precision */ 170 | #else 171 | #define MP_PREC 8 /* default digits of precision */ 172 | #endif 173 | #endif 174 | 175 | /* size of comba arrays, should be at least 2 * 2**(BITS_PER_WORD - BITS_PER_DIGIT*2) */ 176 | #define MP_WARRAY (1 << (sizeof(mp_word) * CHAR_BIT - 2 * DIGIT_BIT + 1)) 177 | 178 | /* the infamous mp_int structure */ 179 | typedef struct { 180 | int used, alloc, sign; 181 | mp_digit *dp; 182 | } mp_int; 183 | 184 | /* callback for mp_prime_random, should fill dst with random bytes and return how many read [upto len] */ 185 | typedef int ltm_prime_callback(unsigned char *dst, int len, void *dat); 186 | 187 | 188 | #define USED(m) ((m)->used) 189 | #define DIGIT(m,k) ((m)->dp[(k)]) 190 | #define SIGN(m) ((m)->sign) 191 | 192 | /* error code to char* string */ 193 | char *mp_error_to_string(int code); 194 | 195 | /* ---> init and deinit bignum functions <--- */ 196 | /* init a bignum */ 197 | int mp_init(mp_int *a); 198 | 199 | /* free a bignum */ 200 | void mp_clear(mp_int *a); 201 | 202 | /* init a null terminated series of arguments */ 203 | int mp_init_multi(mp_int *mp, ...); 204 | 205 | /* clear a null terminated series of arguments */ 206 | void mp_clear_multi(mp_int *mp, ...); 207 | 208 | /* exchange two ints */ 209 | void mp_exch(mp_int *a, mp_int *b); 210 | 211 | /* shrink ram required for a bignum */ 212 | int mp_shrink(mp_int *a); 213 | 214 | /* grow an int to a given size */ 215 | int mp_grow(mp_int *a, int size); 216 | 217 | /* init to a given number of digits */ 218 | int mp_init_size(mp_int *a, int size); 219 | 220 | /* ---> Basic Manipulations <--- */ 221 | #define mp_iszero(a) (((a)->used == 0) ? MP_YES : MP_NO) 222 | #define mp_iseven(a) (((a)->used > 0 && (((a)->dp[0] & 1) == 0)) ? MP_YES : MP_NO) 223 | #define mp_isodd(a) (((a)->used > 0 && (((a)->dp[0] & 1) == 1)) ? MP_YES : MP_NO) 224 | 225 | /* set to zero */ 226 | void mp_zero(mp_int *a); 227 | 228 | /* set to a digit */ 229 | void mp_set(mp_int *a, mp_digit b); 230 | 231 | /* set a 32-bit const */ 232 | int mp_set_int(mp_int *a, unsigned long b); 233 | 234 | /* get a 32-bit value */ 235 | unsigned long mp_get_int(mp_int * a); 236 | 237 | /* initialize and set a digit */ 238 | int mp_init_set (mp_int * a, mp_digit b); 239 | 240 | /* initialize and set 32-bit value */ 241 | int mp_init_set_int (mp_int * a, unsigned long b); 242 | 243 | /* copy, b = a */ 244 | int mp_copy(mp_int *a, mp_int *b); 245 | 246 | /* inits and copies, a = b */ 247 | int mp_init_copy(mp_int *a, mp_int *b); 248 | 249 | /* trim unused digits */ 250 | void mp_clamp(mp_int *a); 251 | 252 | /* ---> digit manipulation <--- */ 253 | 254 | /* right shift by "b" digits */ 255 | void mp_rshd(mp_int *a, int b); 256 | 257 | /* left shift by "b" digits */ 258 | int mp_lshd(mp_int *a, int b); 259 | 260 | /* c = a / 2**b */ 261 | int mp_div_2d(mp_int *a, int b, mp_int *c, mp_int *d); 262 | 263 | /* b = a/2 */ 264 | int mp_div_2(mp_int *a, mp_int *b); 265 | 266 | /* c = a * 2**b */ 267 | int mp_mul_2d(mp_int *a, int b, mp_int *c); 268 | 269 | /* b = a*2 */ 270 | int mp_mul_2(mp_int *a, mp_int *b); 271 | 272 | /* c = a mod 2**d */ 273 | int mp_mod_2d(mp_int *a, int b, mp_int *c); 274 | 275 | /* computes a = 2**b */ 276 | int mp_2expt(mp_int *a, int b); 277 | 278 | /* Counts the number of lsbs which are zero before the first zero bit */ 279 | int mp_cnt_lsb(mp_int *a); 280 | 281 | /* I Love Earth! */ 282 | 283 | /* makes a pseudo-random int of a given size */ 284 | int mp_rand(mp_int *a, int digits); 285 | 286 | /* ---> binary operations <--- */ 287 | /* c = a XOR b */ 288 | int mp_xor(mp_int *a, mp_int *b, mp_int *c); 289 | 290 | /* c = a OR b */ 291 | int mp_or(mp_int *a, mp_int *b, mp_int *c); 292 | 293 | /* c = a AND b */ 294 | int mp_and(mp_int *a, mp_int *b, mp_int *c); 295 | 296 | /* ---> Basic arithmetic <--- */ 297 | 298 | /* b = -a */ 299 | int mp_neg(mp_int *a, mp_int *b); 300 | 301 | /* b = |a| */ 302 | int mp_abs(mp_int *a, mp_int *b); 303 | 304 | /* compare a to b */ 305 | int mp_cmp(mp_int *a, mp_int *b); 306 | 307 | /* compare |a| to |b| */ 308 | int mp_cmp_mag(mp_int *a, mp_int *b); 309 | 310 | /* c = a + b */ 311 | int mp_add(mp_int *a, mp_int *b, mp_int *c); 312 | 313 | /* c = a - b */ 314 | int mp_sub(mp_int *a, mp_int *b, mp_int *c); 315 | 316 | /* c = a * b */ 317 | int mp_mul(mp_int *a, mp_int *b, mp_int *c); 318 | 319 | /* b = a*a */ 320 | int mp_sqr(mp_int *a, mp_int *b); 321 | 322 | /* a/b => cb + d == a */ 323 | int mp_div(mp_int *a, mp_int *b, mp_int *c, mp_int *d); 324 | 325 | /* c = a mod b, 0 <= c < b */ 326 | int mp_mod(mp_int *a, mp_int *b, mp_int *c); 327 | 328 | /* ---> single digit functions <--- */ 329 | 330 | /* compare against a single digit */ 331 | int mp_cmp_d(mp_int *a, mp_digit b); 332 | 333 | /* c = a + b */ 334 | int mp_add_d(mp_int *a, mp_digit b, mp_int *c); 335 | 336 | /* c = a - b */ 337 | int mp_sub_d(mp_int *a, mp_digit b, mp_int *c); 338 | 339 | /* c = a * b */ 340 | int mp_mul_d(mp_int *a, mp_digit b, mp_int *c); 341 | 342 | /* a/b => cb + d == a */ 343 | int mp_div_d(mp_int *a, mp_digit b, mp_int *c, mp_digit *d); 344 | 345 | /* a/3 => 3c + d == a */ 346 | int mp_div_3(mp_int *a, mp_int *c, mp_digit *d); 347 | 348 | /* c = a**b */ 349 | int mp_expt_d(mp_int *a, mp_digit b, mp_int *c); 350 | 351 | /* c = a mod b, 0 <= c < b */ 352 | int mp_mod_d(mp_int *a, mp_digit b, mp_digit *c); 353 | 354 | /* ---> number theory <--- */ 355 | 356 | /* d = a + b (mod c) */ 357 | int mp_addmod(mp_int *a, mp_int *b, mp_int *c, mp_int *d); 358 | 359 | /* d = a - b (mod c) */ 360 | int mp_submod(mp_int *a, mp_int *b, mp_int *c, mp_int *d); 361 | 362 | /* d = a * b (mod c) */ 363 | int mp_mulmod(mp_int *a, mp_int *b, mp_int *c, mp_int *d); 364 | 365 | /* c = a * a (mod b) */ 366 | int mp_sqrmod(mp_int *a, mp_int *b, mp_int *c); 367 | 368 | /* c = 1/a (mod b) */ 369 | int mp_invmod(mp_int *a, mp_int *b, mp_int *c); 370 | 371 | /* c = (a, b) */ 372 | int mp_gcd(mp_int *a, mp_int *b, mp_int *c); 373 | 374 | /* produces value such that U1*a + U2*b = U3 */ 375 | int mp_exteuclid(mp_int *a, mp_int *b, mp_int *U1, mp_int *U2, mp_int *U3); 376 | 377 | /* c = [a, b] or (a*b)/(a, b) */ 378 | int mp_lcm(mp_int *a, mp_int *b, mp_int *c); 379 | 380 | /* finds one of the b'th root of a, such that |c|**b <= |a| 381 | * 382 | * returns error if a < 0 and b is even 383 | */ 384 | int mp_n_root(mp_int *a, mp_digit b, mp_int *c); 385 | 386 | /* special sqrt algo */ 387 | int mp_sqrt(mp_int *arg, mp_int *ret); 388 | 389 | /* is number a square? */ 390 | int mp_is_square(mp_int *arg, int *ret); 391 | 392 | /* computes the jacobi c = (a | n) (or Legendre if b is prime) */ 393 | int mp_jacobi(mp_int *a, mp_int *n, int *c); 394 | 395 | /* used to setup the Barrett reduction for a given modulus b */ 396 | int mp_reduce_setup(mp_int *a, mp_int *b); 397 | 398 | /* Barrett Reduction, computes a (mod b) with a precomputed value c 399 | * 400 | * Assumes that 0 < a <= b*b, note if 0 > a > -(b*b) then you can merely 401 | * compute the reduction as -1 * mp_reduce(mp_abs(a)) [pseudo code]. 402 | */ 403 | int mp_reduce(mp_int *a, mp_int *b, mp_int *c); 404 | 405 | /* setups the montgomery reduction */ 406 | int mp_montgomery_setup(mp_int *a, mp_digit *mp); 407 | 408 | /* computes a = B**n mod b without division or multiplication useful for 409 | * normalizing numbers in a Montgomery system. 410 | */ 411 | int mp_montgomery_calc_normalization(mp_int *a, mp_int *b); 412 | 413 | /* computes x/R == x (mod N) via Montgomery Reduction */ 414 | int mp_montgomery_reduce(mp_int *a, mp_int *m, mp_digit mp); 415 | 416 | /* returns 1 if a is a valid DR modulus */ 417 | int mp_dr_is_modulus(mp_int *a); 418 | 419 | /* sets the value of "d" required for mp_dr_reduce */ 420 | void mp_dr_setup(mp_int *a, mp_digit *d); 421 | 422 | /* reduces a modulo b using the Diminished Radix method */ 423 | int mp_dr_reduce(mp_int *a, mp_int *b, mp_digit mp); 424 | 425 | /* returns true if a can be reduced with mp_reduce_2k */ 426 | int mp_reduce_is_2k(mp_int *a); 427 | 428 | /* determines k value for 2k reduction */ 429 | int mp_reduce_2k_setup(mp_int *a, mp_digit *d); 430 | 431 | /* reduces a modulo b where b is of the form 2**p - k [0 <= a] */ 432 | int mp_reduce_2k(mp_int *a, mp_int *n, mp_digit d); 433 | 434 | /* returns true if a can be reduced with mp_reduce_2k_l */ 435 | int mp_reduce_is_2k_l(mp_int *a); 436 | 437 | /* determines k value for 2k reduction */ 438 | int mp_reduce_2k_setup_l(mp_int *a, mp_int *d); 439 | 440 | /* reduces a modulo b where b is of the form 2**p - k [0 <= a] */ 441 | int mp_reduce_2k_l(mp_int *a, mp_int *n, mp_int *d); 442 | 443 | /* d = a**b (mod c) */ 444 | int mp_exptmod(mp_int *a, mp_int *b, mp_int *c, mp_int *d); 445 | 446 | /* ---> Primes <--- */ 447 | 448 | /* number of primes */ 449 | #ifdef MP_8BIT 450 | #define PRIME_SIZE 31 451 | #else 452 | #define PRIME_SIZE 256 453 | #endif 454 | 455 | /* table of first PRIME_SIZE primes */ 456 | extern const mp_digit ltm_prime_tab[]; 457 | 458 | /* result=1 if a is divisible by one of the first PRIME_SIZE primes */ 459 | int mp_prime_is_divisible(mp_int *a, int *result); 460 | 461 | /* performs one Fermat test of "a" using base "b". 462 | * Sets result to 0 if composite or 1 if probable prime 463 | */ 464 | int mp_prime_fermat(mp_int *a, mp_int *b, int *result); 465 | 466 | /* performs one Miller-Rabin test of "a" using base "b". 467 | * Sets result to 0 if composite or 1 if probable prime 468 | */ 469 | int mp_prime_miller_rabin(mp_int *a, mp_int *b, int *result); 470 | 471 | /* This gives [for a given bit size] the number of trials required 472 | * such that Miller-Rabin gives a prob of failure lower than 2^-96 473 | */ 474 | int mp_prime_rabin_miller_trials(int size); 475 | 476 | /* performs t rounds of Miller-Rabin on "a" using the first 477 | * t prime bases. Also performs an initial sieve of trial 478 | * division. Determines if "a" is prime with probability 479 | * of error no more than (1/4)**t. 480 | * 481 | * Sets result to 1 if probably prime, 0 otherwise 482 | */ 483 | int mp_prime_is_prime(mp_int *a, int t, int *result); 484 | 485 | /* finds the next prime after the number "a" using "t" trials 486 | * of Miller-Rabin. 487 | * 488 | * bbs_style = 1 means the prime must be congruent to 3 mod 4 489 | */ 490 | int mp_prime_next_prime(mp_int *a, int t, int bbs_style); 491 | 492 | /* makes a truly random prime of a given size (bytes), 493 | * call with bbs = 1 if you want it to be congruent to 3 mod 4 494 | * 495 | * You have to supply a callback which fills in a buffer with random bytes. "dat" is a parameter you can 496 | * have passed to the callback (e.g. a state or something). This function doesn't use "dat" itself 497 | * so it can be NULL 498 | * 499 | * The prime generated will be larger than 2^(8*size). 500 | */ 501 | #define mp_prime_random(a, t, size, bbs, cb, dat) mp_prime_random_ex(a, t, ((size) * 8) + 1, (bbs==1)?LTM_PRIME_BBS:0, cb, dat) 502 | 503 | /* makes a truly random prime of a given size (bits), 504 | * 505 | * Flags are as follows: 506 | * 507 | * LTM_PRIME_BBS - make prime congruent to 3 mod 4 508 | * LTM_PRIME_SAFE - make sure (p-1)/2 is prime as well (implies LTM_PRIME_BBS) 509 | * LTM_PRIME_2MSB_OFF - make the 2nd highest bit zero 510 | * LTM_PRIME_2MSB_ON - make the 2nd highest bit one 511 | * 512 | * You have to supply a callback which fills in a buffer with random bytes. "dat" is a parameter you can 513 | * have passed to the callback (e.g. a state or something). This function doesn't use "dat" itself 514 | * so it can be NULL 515 | * 516 | */ 517 | int mp_prime_random_ex(mp_int *a, int t, int size, int flags, ltm_prime_callback cb, void *dat); 518 | 519 | /* ---> radix conversion <--- */ 520 | int mp_count_bits(mp_int *a); 521 | 522 | int mp_unsigned_bin_size(mp_int *a); 523 | int mp_read_unsigned_bin(mp_int *a, const unsigned char *b, int c); 524 | int mp_to_unsigned_bin(mp_int *a, unsigned char *b); 525 | int mp_to_unsigned_bin_n (mp_int * a, unsigned char *b, unsigned long *outlen); 526 | 527 | int mp_signed_bin_size(mp_int *a); 528 | int mp_read_signed_bin(mp_int *a, const unsigned char *b, int c); 529 | int mp_to_signed_bin(mp_int *a, unsigned char *b); 530 | int mp_to_signed_bin_n (mp_int * a, unsigned char *b, unsigned long *outlen); 531 | 532 | int mp_read_radix(mp_int *a, const char *str, int radix); 533 | int mp_toradix(mp_int *a, char *str, int radix); 534 | int mp_toradix_n(mp_int * a, char *str, int radix, int maxlen); 535 | int mp_radix_size(mp_int *a, int radix, int *size); 536 | 537 | int mp_fread(mp_int *a, int radix, FILE *stream); 538 | int mp_fwrite(mp_int *a, int radix, FILE *stream); 539 | 540 | #define mp_read_raw(mp, str, len) mp_read_signed_bin((mp), (str), (len)) 541 | #define mp_raw_size(mp) mp_signed_bin_size(mp) 542 | #define mp_toraw(mp, str) mp_to_signed_bin((mp), (str)) 543 | #define mp_read_mag(mp, str, len) mp_read_unsigned_bin((mp), (str), (len)) 544 | #define mp_mag_size(mp) mp_unsigned_bin_size(mp) 545 | #define mp_tomag(mp, str) mp_to_unsigned_bin((mp), (str)) 546 | 547 | #define mp_tobinary(M, S) mp_toradix((M), (S), 2) 548 | #define mp_tooctal(M, S) mp_toradix((M), (S), 8) 549 | #define mp_todecimal(M, S) mp_toradix((M), (S), 10) 550 | #define mp_tohex(M, S) mp_toradix((M), (S), 16) 551 | 552 | /* lowlevel functions, do not call! */ 553 | int s_mp_add(mp_int *a, mp_int *b, mp_int *c); 554 | int s_mp_sub(mp_int *a, mp_int *b, mp_int *c); 555 | #define s_mp_mul(a, b, c) s_mp_mul_digs(a, b, c, (a)->used + (b)->used + 1) 556 | int fast_s_mp_mul_digs(mp_int *a, mp_int *b, mp_int *c, int digs); 557 | int s_mp_mul_digs(mp_int *a, mp_int *b, mp_int *c, int digs); 558 | int fast_s_mp_mul_high_digs(mp_int *a, mp_int *b, mp_int *c, int digs); 559 | int s_mp_mul_high_digs(mp_int *a, mp_int *b, mp_int *c, int digs); 560 | int fast_s_mp_sqr(mp_int *a, mp_int *b); 561 | int s_mp_sqr(mp_int *a, mp_int *b); 562 | int mp_karatsuba_mul(mp_int *a, mp_int *b, mp_int *c); 563 | int mp_toom_mul(mp_int *a, mp_int *b, mp_int *c); 564 | int mp_karatsuba_sqr(mp_int *a, mp_int *b); 565 | int mp_toom_sqr(mp_int *a, mp_int *b); 566 | int fast_mp_invmod(mp_int *a, mp_int *b, mp_int *c); 567 | int mp_invmod_slow (mp_int * a, mp_int * b, mp_int * c); 568 | int fast_mp_montgomery_reduce(mp_int *a, mp_int *m, mp_digit mp); 569 | int mp_exptmod_fast(mp_int *G, mp_int *X, mp_int *P, mp_int *Y, int mode); 570 | int s_mp_exptmod (mp_int * G, mp_int * X, mp_int * P, mp_int * Y, int mode); 571 | void bn_reverse(unsigned char *s, int len); 572 | 573 | extern const char *mp_s_rmap; 574 | 575 | #ifdef __cplusplus 576 | } 577 | #endif 578 | 579 | #endif 580 | 581 | 582 | /* $Source$ */ 583 | /* $Revision: 0.39 $ */ 584 | /* $Date: 2006-04-06 19:49:59 +0000 $ */ 585 | -------------------------------------------------------------------------------- /ios/JKBigInteger/LibTomMath/tommath_superclass.h: -------------------------------------------------------------------------------- 1 | /* super class file for PK algos */ 2 | 3 | /* default ... include all MPI */ 4 | #define LTM_ALL 5 | 6 | /* RSA only (does not support DH/DSA/ECC) */ 7 | /* #define SC_RSA_1 */ 8 | 9 | /* For reference.... On an Athlon64 optimizing for speed... 10 | 11 | LTM's mpi.o with all functions [striped] is 142KiB in size. 12 | 13 | */ 14 | 15 | /* Works for RSA only, mpi.o is 68KiB */ 16 | #ifdef SC_RSA_1 17 | #define BN_MP_SHRINK_C 18 | #define BN_MP_LCM_C 19 | #define BN_MP_PRIME_RANDOM_EX_C 20 | #define BN_MP_INVMOD_C 21 | #define BN_MP_GCD_C 22 | #define BN_MP_MOD_C 23 | #define BN_MP_MULMOD_C 24 | #define BN_MP_ADDMOD_C 25 | #define BN_MP_EXPTMOD_C 26 | #define BN_MP_SET_INT_C 27 | #define BN_MP_INIT_MULTI_C 28 | #define BN_MP_CLEAR_MULTI_C 29 | #define BN_MP_UNSIGNED_BIN_SIZE_C 30 | #define BN_MP_TO_UNSIGNED_BIN_C 31 | #define BN_MP_MOD_D_C 32 | #define BN_MP_PRIME_RABIN_MILLER_TRIALS_C 33 | #define BN_REVERSE_C 34 | #define BN_PRIME_TAB_C 35 | 36 | /* other modifiers */ 37 | #define BN_MP_DIV_SMALL /* Slower division, not critical */ 38 | 39 | /* here we are on the last pass so we turn things off. The functions classes are still there 40 | * but we remove them specifically from the build. This also invokes tweaks in functions 41 | * like removing support for even moduli, etc... 42 | */ 43 | #ifdef LTM_LAST 44 | #undef BN_MP_TOOM_MUL_C 45 | #undef BN_MP_TOOM_SQR_C 46 | #undef BN_MP_KARATSUBA_MUL_C 47 | #undef BN_MP_KARATSUBA_SQR_C 48 | #undef BN_MP_REDUCE_C 49 | #undef BN_MP_REDUCE_SETUP_C 50 | #undef BN_MP_DR_IS_MODULUS_C 51 | #undef BN_MP_DR_SETUP_C 52 | #undef BN_MP_DR_REDUCE_C 53 | #undef BN_MP_REDUCE_IS_2K_C 54 | #undef BN_MP_REDUCE_2K_SETUP_C 55 | #undef BN_MP_REDUCE_2K_C 56 | #undef BN_S_MP_EXPTMOD_C 57 | #undef BN_MP_DIV_3_C 58 | #undef BN_S_MP_MUL_HIGH_DIGS_C 59 | #undef BN_FAST_S_MP_MUL_HIGH_DIGS_C 60 | #undef BN_FAST_MP_INVMOD_C 61 | 62 | /* To safely undefine these you have to make sure your RSA key won't exceed the Comba threshold 63 | * which is roughly 255 digits [7140 bits for 32-bit machines, 15300 bits for 64-bit machines] 64 | * which means roughly speaking you can handle upto 2536-bit RSA keys with these defined without 65 | * trouble. 66 | */ 67 | #undef BN_S_MP_MUL_DIGS_C 68 | #undef BN_S_MP_SQR_C 69 | #undef BN_MP_MONTGOMERY_REDUCE_C 70 | #endif 71 | 72 | #endif 73 | 74 | /* $Source$ */ 75 | /* $Revision: 0.36 $ */ 76 | /* $Date: 2005-08-01 16:37:28 +0000 $ */ 77 | -------------------------------------------------------------------------------- /ios/RNAWSCognito.h: -------------------------------------------------------------------------------- 1 | #if __has_include("RCTBridgeModule.h") 2 | #import "RCTBridgeModule.h" 3 | #else 4 | #import 5 | #endif 6 | 7 | #if __has_include("RCTLog.h") 8 | #import "RCTLog.h" 9 | #else 10 | #import 11 | #endif 12 | 13 | #if __has_include("RCTUtils.h") 14 | #import "RCTUtils.h" 15 | #else 16 | #import 17 | #endif 18 | 19 | #import "JKBigInteger.h" 20 | 21 | @interface RNAWSCognito : NSObject 22 | 23 | @end 24 | -------------------------------------------------------------------------------- /ios/RNAWSCognito.m: -------------------------------------------------------------------------------- 1 | #import "RNAWSCognito.h" 2 | 3 | static NSString* N_IN_HEX = @"FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D670C354E4ABC9804F1746C08CA18217C32905E462E36CE3BE39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF6955817183995497CEA956AE515D2261898FA051015728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6BF12FFA06D98A0864D87602733EC86A64521F2B18177B200CBBE117577A615D6C770988C0BAD946E208E24FA074E5AB3143DB5BFCE0FD108E4B82D120A93AD2CAFFFFFFFFFFFFFFFF"; 4 | 5 | @implementation RNAWSCognito 6 | 7 | - (dispatch_queue_t)methodQueue 8 | { 9 | return dispatch_get_main_queue(); 10 | } 11 | RCT_EXPORT_MODULE() 12 | 13 | RCT_EXPORT_METHOD(computeModPow:(NSDictionary *)values 14 | callback:(RCTResponseSenderBlock)callback) 15 | { 16 | JKBigInteger *N = [[JKBigInteger alloc] initWithString:N_IN_HEX andRadix:16]; 17 | JKBigInteger *target = [[JKBigInteger alloc] initWithString:values[@"target"] andRadix:16]; 18 | JKBigInteger *value = [[JKBigInteger alloc] initWithString:values[@"value"] andRadix:16]; 19 | JKBigInteger *result = [target pow:value andMod:N]; 20 | if (result) { 21 | callback(@[[NSNull null], [result stringValueWithRadix:16]]); 22 | } else { 23 | callback(@[@[RCTMakeError(@"computeModPow error", nil, nil)], [NSNull null]]); 24 | } 25 | 26 | } 27 | 28 | RCT_EXPORT_METHOD(computeS:(NSDictionary *)values 29 | callback:(RCTResponseSenderBlock)callback) 30 | { 31 | JKBigInteger *N = [[JKBigInteger alloc] initWithString:N_IN_HEX andRadix:16]; 32 | JKBigInteger *g = [[JKBigInteger alloc] initWithString:values[@"g"] andRadix:16]; 33 | JKBigInteger *x = [[JKBigInteger alloc] initWithString:values[@"x"] andRadix:16]; 34 | JKBigInteger *k = [[JKBigInteger alloc] initWithString:values[@"k"] andRadix:16]; 35 | JKBigInteger *a = [[JKBigInteger alloc] initWithString:values[@"a"] andRadix:16]; 36 | JKBigInteger *b = [[JKBigInteger alloc] initWithString:values[@"b"] andRadix:16]; 37 | JKBigInteger *u = [[JKBigInteger alloc] initWithString:values[@"u"] andRadix:16]; 38 | JKBigInteger *exp = [a add:[u multiply:x]]; 39 | JKBigInteger *base = [b subtract:[k multiply:[g pow:x andMod:N]]]; 40 | base = [self mod:base divisor:N]; 41 | JKBigInteger *result = [base pow:exp andMod:N]; 42 | result = [self mod:result divisor:N]; 43 | if (result) { 44 | callback(@[[NSNull null], [result stringValueWithRadix:16]]); 45 | } else { 46 | callback(@[@[RCTMakeError(@"computeS error", nil, nil)], [NSNull null]]); 47 | } 48 | } 49 | 50 | - (JKBigInteger*) mod:(JKBigInteger*)dividend divisor:(JKBigInteger*) divisor { 51 | return [[divisor add:[dividend remainder:divisor]] remainder:divisor]; 52 | } 53 | 54 | @end 55 | -------------------------------------------------------------------------------- /ios/RNAWSCognito.xcodeproj/project.pbxproj: -------------------------------------------------------------------------------- 1 | // !$*UTF8*$! 2 | { 3 | archiveVersion = 1; 4 | classes = { 5 | }; 6 | objectVersion = 46; 7 | objects = { 8 | 9 | /* Begin PBXBuildFile section */ 10 | B3E7B58A1CC2AC0600A0062D /* RNAWSCognito.m in Sources */ = {isa = PBXBuildFile; fileRef = B3E7B5891CC2AC0600A0062D /* RNAWSCognito.m */; }; 11 | E2C4A2A31EAEEA5500F05BD3 /* JKBigDecimal.m in Sources */ = {isa = PBXBuildFile; fileRef = E2C4A29B1EAEEA5500F05BD3 /* JKBigDecimal.m */; }; 12 | E2C4A2A41EAEEA5500F05BD3 /* JKBigInteger.m in Sources */ = {isa = PBXBuildFile; fileRef = E2C4A29D1EAEEA5500F05BD3 /* JKBigInteger.m */; }; 13 | E2C4A2A51EAEEA5500F05BD3 /* tommath.c in Sources */ = {isa = PBXBuildFile; fileRef = E2C4A29F1EAEEA5500F05BD3 /* tommath.c */; }; 14 | /* End PBXBuildFile section */ 15 | 16 | /* Begin PBXCopyFilesBuildPhase section */ 17 | 58B511D91A9E6C8500147676 /* CopyFiles */ = { 18 | isa = PBXCopyFilesBuildPhase; 19 | buildActionMask = 2147483647; 20 | dstPath = "include/$(PRODUCT_NAME)"; 21 | dstSubfolderSpec = 16; 22 | files = ( 23 | ); 24 | runOnlyForDeploymentPostprocessing = 0; 25 | }; 26 | /* End PBXCopyFilesBuildPhase section */ 27 | 28 | /* Begin PBXFileReference section */ 29 | 134814201AA4EA6300B7C361 /* libRNAWSCognito.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = libRNAWSCognito.a; sourceTree = BUILT_PRODUCTS_DIR; }; 30 | B3E7B5881CC2AC0600A0062D /* RNAWSCognito.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = RNAWSCognito.h; sourceTree = ""; }; 31 | B3E7B5891CC2AC0600A0062D /* RNAWSCognito.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = RNAWSCognito.m; sourceTree = ""; }; 32 | E2C4A29A1EAEEA5500F05BD3 /* JKBigDecimal.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = JKBigDecimal.h; sourceTree = ""; }; 33 | E2C4A29B1EAEEA5500F05BD3 /* JKBigDecimal.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = JKBigDecimal.m; sourceTree = ""; }; 34 | E2C4A29C1EAEEA5500F05BD3 /* JKBigInteger.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = JKBigInteger.h; sourceTree = ""; }; 35 | E2C4A29D1EAEEA5500F05BD3 /* JKBigInteger.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = JKBigInteger.m; sourceTree = ""; }; 36 | E2C4A29F1EAEEA5500F05BD3 /* tommath.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = tommath.c; sourceTree = ""; }; 37 | E2C4A2A01EAEEA5500F05BD3 /* tommath.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = tommath.h; sourceTree = ""; }; 38 | E2C4A2A11EAEEA5500F05BD3 /* tommath_class.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = tommath_class.h; sourceTree = ""; }; 39 | E2C4A2A21EAEEA5500F05BD3 /* tommath_superclass.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = tommath_superclass.h; sourceTree = ""; }; 40 | /* End PBXFileReference section */ 41 | 42 | /* Begin PBXFrameworksBuildPhase section */ 43 | 58B511D81A9E6C8500147676 /* Frameworks */ = { 44 | isa = PBXFrameworksBuildPhase; 45 | buildActionMask = 2147483647; 46 | files = ( 47 | ); 48 | runOnlyForDeploymentPostprocessing = 0; 49 | }; 50 | /* End PBXFrameworksBuildPhase section */ 51 | 52 | /* Begin PBXGroup section */ 53 | 134814211AA4EA7D00B7C361 /* Products */ = { 54 | isa = PBXGroup; 55 | children = ( 56 | 134814201AA4EA6300B7C361 /* libRNAWSCognito.a */, 57 | ); 58 | name = Products; 59 | sourceTree = ""; 60 | }; 61 | 58B511D21A9E6C8500147676 = { 62 | isa = PBXGroup; 63 | children = ( 64 | E2C4A2991EAEEA5500F05BD3 /* JKBigInteger */, 65 | B3E7B5881CC2AC0600A0062D /* RNAWSCognito.h */, 66 | B3E7B5891CC2AC0600A0062D /* RNAWSCognito.m */, 67 | 134814211AA4EA7D00B7C361 /* Products */, 68 | ); 69 | sourceTree = ""; 70 | }; 71 | E2C4A2991EAEEA5500F05BD3 /* JKBigInteger */ = { 72 | isa = PBXGroup; 73 | children = ( 74 | E2C4A29A1EAEEA5500F05BD3 /* JKBigDecimal.h */, 75 | E2C4A29B1EAEEA5500F05BD3 /* JKBigDecimal.m */, 76 | E2C4A29C1EAEEA5500F05BD3 /* JKBigInteger.h */, 77 | E2C4A29D1EAEEA5500F05BD3 /* JKBigInteger.m */, 78 | E2C4A29E1EAEEA5500F05BD3 /* LibTomMath */, 79 | ); 80 | path = JKBigInteger; 81 | sourceTree = ""; 82 | }; 83 | E2C4A29E1EAEEA5500F05BD3 /* LibTomMath */ = { 84 | isa = PBXGroup; 85 | children = ( 86 | E2C4A29F1EAEEA5500F05BD3 /* tommath.c */, 87 | E2C4A2A01EAEEA5500F05BD3 /* tommath.h */, 88 | E2C4A2A11EAEEA5500F05BD3 /* tommath_class.h */, 89 | E2C4A2A21EAEEA5500F05BD3 /* tommath_superclass.h */, 90 | ); 91 | path = LibTomMath; 92 | sourceTree = ""; 93 | }; 94 | /* End PBXGroup section */ 95 | 96 | /* Begin PBXNativeTarget section */ 97 | 58B511DA1A9E6C8500147676 /* RNAWSCognito */ = { 98 | isa = PBXNativeTarget; 99 | buildConfigurationList = 58B511EF1A9E6C8500147676 /* Build configuration list for PBXNativeTarget "RNAWSCognito" */; 100 | buildPhases = ( 101 | 58B511D71A9E6C8500147676 /* Sources */, 102 | 58B511D81A9E6C8500147676 /* Frameworks */, 103 | 58B511D91A9E6C8500147676 /* CopyFiles */, 104 | ); 105 | buildRules = ( 106 | ); 107 | dependencies = ( 108 | ); 109 | name = RNAWSCognito; 110 | productName = RCTDataManager; 111 | productReference = 134814201AA4EA6300B7C361 /* libRNAWSCognito.a */; 112 | productType = "com.apple.product-type.library.static"; 113 | }; 114 | /* End PBXNativeTarget section */ 115 | 116 | /* Begin PBXProject section */ 117 | 58B511D31A9E6C8500147676 /* Project object */ = { 118 | isa = PBXProject; 119 | attributes = { 120 | LastUpgradeCheck = 0830; 121 | ORGANIZATIONNAME = Facebook; 122 | TargetAttributes = { 123 | 58B511DA1A9E6C8500147676 = { 124 | CreatedOnToolsVersion = 6.1.1; 125 | }; 126 | }; 127 | }; 128 | buildConfigurationList = 58B511D61A9E6C8500147676 /* Build configuration list for PBXProject "RNAWSCognito" */; 129 | compatibilityVersion = "Xcode 3.2"; 130 | developmentRegion = English; 131 | hasScannedForEncodings = 0; 132 | knownRegions = ( 133 | en, 134 | ); 135 | mainGroup = 58B511D21A9E6C8500147676; 136 | productRefGroup = 58B511D21A9E6C8500147676; 137 | projectDirPath = ""; 138 | projectRoot = ""; 139 | targets = ( 140 | 58B511DA1A9E6C8500147676 /* RNAWSCognito */, 141 | ); 142 | }; 143 | /* End PBXProject section */ 144 | 145 | /* Begin PBXSourcesBuildPhase section */ 146 | 58B511D71A9E6C8500147676 /* Sources */ = { 147 | isa = PBXSourcesBuildPhase; 148 | buildActionMask = 2147483647; 149 | files = ( 150 | E2C4A2A51EAEEA5500F05BD3 /* tommath.c in Sources */, 151 | B3E7B58A1CC2AC0600A0062D /* RNAWSCognito.m in Sources */, 152 | E2C4A2A41EAEEA5500F05BD3 /* JKBigInteger.m in Sources */, 153 | E2C4A2A31EAEEA5500F05BD3 /* JKBigDecimal.m in Sources */, 154 | ); 155 | runOnlyForDeploymentPostprocessing = 0; 156 | }; 157 | /* End PBXSourcesBuildPhase section */ 158 | 159 | /* Begin XCBuildConfiguration section */ 160 | 58B511ED1A9E6C8500147676 /* Debug */ = { 161 | isa = XCBuildConfiguration; 162 | buildSettings = { 163 | ALWAYS_SEARCH_USER_PATHS = NO; 164 | CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; 165 | CLANG_CXX_LIBRARY = "libc++"; 166 | CLANG_ENABLE_MODULES = YES; 167 | CLANG_ENABLE_OBJC_ARC = YES; 168 | CLANG_WARN_BOOL_CONVERSION = YES; 169 | CLANG_WARN_CONSTANT_CONVERSION = YES; 170 | CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; 171 | CLANG_WARN_EMPTY_BODY = YES; 172 | CLANG_WARN_ENUM_CONVERSION = YES; 173 | CLANG_WARN_INFINITE_RECURSION = YES; 174 | CLANG_WARN_INT_CONVERSION = YES; 175 | CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; 176 | CLANG_WARN_SUSPICIOUS_MOVE = YES; 177 | CLANG_WARN_UNREACHABLE_CODE = YES; 178 | CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; 179 | COPY_PHASE_STRIP = NO; 180 | ENABLE_STRICT_OBJC_MSGSEND = YES; 181 | ENABLE_TESTABILITY = YES; 182 | GCC_C_LANGUAGE_STANDARD = gnu99; 183 | GCC_DYNAMIC_NO_PIC = NO; 184 | GCC_NO_COMMON_BLOCKS = YES; 185 | GCC_OPTIMIZATION_LEVEL = 0; 186 | GCC_PREPROCESSOR_DEFINITIONS = ( 187 | "DEBUG=1", 188 | "$(inherited)", 189 | ); 190 | GCC_SYMBOLS_PRIVATE_EXTERN = NO; 191 | GCC_WARN_64_TO_32_BIT_CONVERSION = YES; 192 | GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; 193 | GCC_WARN_UNDECLARED_SELECTOR = YES; 194 | GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; 195 | GCC_WARN_UNUSED_FUNCTION = YES; 196 | GCC_WARN_UNUSED_VARIABLE = YES; 197 | IPHONEOS_DEPLOYMENT_TARGET = 8.0; 198 | MTL_ENABLE_DEBUG_INFO = YES; 199 | ONLY_ACTIVE_ARCH = YES; 200 | SDKROOT = iphoneos; 201 | }; 202 | name = Debug; 203 | }; 204 | 58B511EE1A9E6C8500147676 /* Release */ = { 205 | isa = XCBuildConfiguration; 206 | buildSettings = { 207 | ALWAYS_SEARCH_USER_PATHS = NO; 208 | CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; 209 | CLANG_CXX_LIBRARY = "libc++"; 210 | CLANG_ENABLE_MODULES = YES; 211 | CLANG_ENABLE_OBJC_ARC = YES; 212 | CLANG_WARN_BOOL_CONVERSION = YES; 213 | CLANG_WARN_CONSTANT_CONVERSION = YES; 214 | CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; 215 | CLANG_WARN_EMPTY_BODY = YES; 216 | CLANG_WARN_ENUM_CONVERSION = YES; 217 | CLANG_WARN_INFINITE_RECURSION = YES; 218 | CLANG_WARN_INT_CONVERSION = YES; 219 | CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; 220 | CLANG_WARN_SUSPICIOUS_MOVE = YES; 221 | CLANG_WARN_UNREACHABLE_CODE = YES; 222 | CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; 223 | COPY_PHASE_STRIP = YES; 224 | ENABLE_NS_ASSERTIONS = NO; 225 | ENABLE_STRICT_OBJC_MSGSEND = YES; 226 | GCC_C_LANGUAGE_STANDARD = gnu99; 227 | GCC_NO_COMMON_BLOCKS = YES; 228 | GCC_WARN_64_TO_32_BIT_CONVERSION = YES; 229 | GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; 230 | GCC_WARN_UNDECLARED_SELECTOR = YES; 231 | GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; 232 | GCC_WARN_UNUSED_FUNCTION = YES; 233 | GCC_WARN_UNUSED_VARIABLE = YES; 234 | IPHONEOS_DEPLOYMENT_TARGET = 8.0; 235 | MTL_ENABLE_DEBUG_INFO = NO; 236 | SDKROOT = iphoneos; 237 | VALIDATE_PRODUCT = YES; 238 | }; 239 | name = Release; 240 | }; 241 | 58B511F01A9E6C8500147676 /* Debug */ = { 242 | isa = XCBuildConfiguration; 243 | buildSettings = { 244 | HEADER_SEARCH_PATHS = ( 245 | "$(inherited)", 246 | /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include, 247 | "$(SRCROOT)/../node_modules/react-native/React/**", 248 | ); 249 | LIBRARY_SEARCH_PATHS = "$(inherited)"; 250 | OTHER_LDFLAGS = "-ObjC"; 251 | PRODUCT_NAME = RNAWSCognito; 252 | SKIP_INSTALL = YES; 253 | }; 254 | name = Debug; 255 | }; 256 | 58B511F11A9E6C8500147676 /* Release */ = { 257 | isa = XCBuildConfiguration; 258 | buildSettings = { 259 | HEADER_SEARCH_PATHS = ( 260 | "$(inherited)", 261 | /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include, 262 | "$(SRCROOT)/../node_modules/react-native/React/**", 263 | ); 264 | LIBRARY_SEARCH_PATHS = "$(inherited)"; 265 | OTHER_LDFLAGS = "-ObjC"; 266 | PRODUCT_NAME = RNAWSCognito; 267 | SKIP_INSTALL = YES; 268 | }; 269 | name = Release; 270 | }; 271 | /* End XCBuildConfiguration section */ 272 | 273 | /* Begin XCConfigurationList section */ 274 | 58B511D61A9E6C8500147676 /* Build configuration list for PBXProject "RNAWSCognito" */ = { 275 | isa = XCConfigurationList; 276 | buildConfigurations = ( 277 | 58B511ED1A9E6C8500147676 /* Debug */, 278 | 58B511EE1A9E6C8500147676 /* Release */, 279 | ); 280 | defaultConfigurationIsVisible = 0; 281 | defaultConfigurationName = Release; 282 | }; 283 | 58B511EF1A9E6C8500147676 /* Build configuration list for PBXNativeTarget "RNAWSCognito" */ = { 284 | isa = XCConfigurationList; 285 | buildConfigurations = ( 286 | 58B511F01A9E6C8500147676 /* Debug */, 287 | 58B511F11A9E6C8500147676 /* Release */, 288 | ); 289 | defaultConfigurationIsVisible = 0; 290 | defaultConfigurationName = Release; 291 | }; 292 | /* End XCConfigurationList section */ 293 | }; 294 | rootObject = 58B511D31A9E6C8500147676 /* Project object */; 295 | } 296 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "react-native-aws-cognito-js", 3 | "version": "0.0.7", 4 | "description": "React Native AWS Cognito JS library.", 5 | "main": "index.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1" 8 | }, 9 | "repository": { 10 | "type": "git", 11 | "url": "https://github.com/AirLabsTeam/react-native-aws-cognito-js.git" 12 | }, 13 | "keywords": [ 14 | "react-native", 15 | "amazon", 16 | "aws", 17 | "cognito", 18 | "identity" 19 | ], 20 | "homepage": "https://github.com/AirLabsTeam/react-native-aws-cognito-js", 21 | "author": "Jon Parsons (https://github.com/jmparsons)", 22 | "license": "SEE LICENSE IN LICENSE", 23 | "dependencies": { 24 | "aws-sdk": "*" 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /react-native-aws-cognito-js.podspec: -------------------------------------------------------------------------------- 1 | require 'json' 2 | 3 | package = JSON.parse(File.read(File.join(__dir__, 'package.json'))) 4 | 5 | Pod::Spec.new do |s| 6 | s.name = package['name'] 7 | s.version = package['version'] 8 | s.summary = package['description'] 9 | s.author = package['author'] 10 | s.homepage = package['homepage'] 11 | s.license = package['license'] 12 | s.author = { "Jon Parsons" => "jonparsons@gmail.com" } 13 | s.source = { :git => "https://github.com/AirLabsTeam/react-native-aws-cognito-js.git", :tag => "v#{s.version}" } 14 | s.platform = :ios, "8.0" 15 | s.source_files = "ios/JKBigInteger/**/*.{h,c,m}", "ios/*.{h,m}" 16 | s.requires_arc = true 17 | s.dependency 'React' 18 | end 19 | -------------------------------------------------------------------------------- /src/AuthenticationDetails.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 | 18 | /** @class */ 19 | export default class AuthenticationDetails { 20 | /** 21 | * Constructs a new AuthenticationDetails object 22 | * @param {object=} data Creation options. 23 | * @param {string} data.Username User being authenticated. 24 | * @param {string} data.Password Plain-text password to authenticate with. 25 | * @param {(AttributeArg[])?} data.ValidationData Application extra metadata. 26 | * @param {(AttributeArg[])?} data.AuthParamaters Authentication paramaters for custom auth. 27 | */ 28 | constructor(data) { 29 | const { ValidationData, Username, Password, AuthParameters } = data || {}; 30 | this.validationData = ValidationData || []; 31 | this.authParameters = AuthParameters || []; 32 | this.username = Username; 33 | this.password = Password; 34 | } 35 | 36 | /** 37 | * @returns {string} the record's username 38 | */ 39 | getUsername() { 40 | return this.username; 41 | } 42 | 43 | /** 44 | * @returns {string} the record's password 45 | */ 46 | getPassword() { 47 | return this.password; 48 | } 49 | 50 | /** 51 | * @returns {Array} the record's validationData 52 | */ 53 | getValidationData() { 54 | return this.validationData; 55 | } 56 | 57 | /** 58 | * @returns {Array} the record's authParameters 59 | */ 60 | getAuthParameters() { 61 | return this.authParameters; 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /src/AuthenticationHelper.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 | 18 | import { util } from 'aws-sdk/dist/aws-sdk-react-native'; 19 | 20 | import BigInteger from './BigInteger'; 21 | 22 | import { NativeModules } from 'react-native'; 23 | 24 | const { RNAWSCognito } = NativeModules; 25 | 26 | const initN = 'FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1' 27 | + '29024E088A67CC74020BBEA63B139B22514A08798E3404DD' 28 | + 'EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245' 29 | + 'E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED' 30 | + 'EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D' 31 | + 'C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F' 32 | + '83655D23DCA3AD961C62F356208552BB9ED529077096966D' 33 | + '670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B' 34 | + 'E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9' 35 | + 'DE2BCBF6955817183995497CEA956AE515D2261898FA0510' 36 | + '15728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64' 37 | + 'ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7' 38 | + 'ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6B' 39 | + 'F12FFA06D98A0864D87602733EC86A64521F2B18177B200C' 40 | + 'BBE117577A615D6C770988C0BAD946E208E24FA074E5AB31' 41 | + '43DB5BFCE0FD108E4B82D120A93AD2CAFFFFFFFFFFFFFFFF'; 42 | 43 | const newPasswordRequiredChallengeUserAttributePrefix = 'userAttributes.'; 44 | 45 | /** @class */ 46 | export default class AuthenticationHelper { 47 | /** 48 | * Constructs a new AuthenticationHelper object 49 | * @param {string} PoolName Cognito user pool name. 50 | */ 51 | constructor(PoolName) { 52 | this.N = new BigInteger(initN, 16); 53 | this.g = new BigInteger('2', 16); 54 | this.k = new BigInteger(this.hexHash(`00${this.N.toString(16)}0${this.g.toString(16)}`), 16); 55 | 56 | this.smallAValue = this.generateRandomSmallA(); 57 | 58 | this.infoBits = new util.Buffer('Caldera Derived Key', 'utf8'); 59 | 60 | this.poolName = PoolName; 61 | } 62 | 63 | /** 64 | * Calculate mod pow with target, value and modifier. 65 | * @param {BigInteger} target Target to run mod pow against. 66 | * @param {BigInteger} value Actual mod pow value. 67 | * @param {BigInteger} modifier Modifier value for mod pow. 68 | * @param {nodeCallback} callback Called on success or error. 69 | * @returns {void} 70 | */ 71 | computeModPow(target, value, modifier, callback) { 72 | RNAWSCognito.computeModPow({ 73 | target: target.toString(16), 74 | value: value.toString(16) 75 | }, (err, result) => { 76 | if (err) { 77 | return callback(new Error(err), null); 78 | } 79 | const bigIntResult = new BigInteger(result, 16); 80 | return callback(null, bigIntResult); 81 | }); 82 | return undefined; 83 | } 84 | 85 | /** 86 | * Calculate mod pow with target, value and modifier. 87 | * @param {BigInteger} xValue Hex hashed salted username and password. 88 | * @param {BigInteger} serverBValue Server B value. 89 | * @param {nodeCallback} callback Called on success or error. 90 | * @returns {void} 91 | */ 92 | computeS(xValue, serverBValue, callback) { 93 | RNAWSCognito.computeS({ 94 | g: this.g.toString(16), 95 | x: xValue.toString(16), 96 | k: this.k.toString(16), 97 | a: this.smallAValue.toString(16), 98 | b: serverBValue.toString(16), 99 | u: this.UValue.toString(16) 100 | }, (err, result) => { 101 | if (err) { 102 | return callback(new Error(err), null); 103 | } 104 | const bigIntResult = new BigInteger(result, 16); 105 | return callback(null, bigIntResult); 106 | }); 107 | return undefined; 108 | } 109 | 110 | /** 111 | * @returns {BigInteger} small A, a random number 112 | */ 113 | getSmallAValue() { 114 | return this.smallAValue; 115 | } 116 | 117 | /** 118 | * @param {nodeCallback} callback Called on success or error. 119 | * @returns {BigInteger} large A, a value generated from small A 120 | */ 121 | getLargeAValue(callback) { 122 | if (this.largeAValue) { 123 | return callback(null, this.largeAValue); 124 | } 125 | this.calculateA(this.smallAValue, (err, result) => { 126 | if (err) { 127 | return callback(new Error(err), null); 128 | } 129 | this.largeAValue = result; 130 | return callback(null, this.largeAValue); 131 | }); 132 | return undefined; 133 | } 134 | 135 | /** 136 | * helper function to generate a random big integer 137 | * @returns {BigInteger} a random value. 138 | * @private 139 | */ 140 | generateRandomSmallA() { 141 | const hexRandom = util.crypto.lib.randomBytes(128).toString('hex'); 142 | 143 | const randomBigInt = new BigInteger(hexRandom, 16); 144 | const smallABigInt = randomBigInt.mod(this.N); 145 | 146 | return smallABigInt; 147 | } 148 | 149 | /** 150 | * helper function to generate a random string 151 | * @returns {string} a random value. 152 | * @private 153 | */ 154 | generateRandomString() { 155 | return util.crypto.lib.randomBytes(40).toString('base64'); 156 | } 157 | 158 | /** 159 | * @returns {string} Generated random value included in password hash. 160 | */ 161 | getRandomPassword() { 162 | return this.randomPassword; 163 | } 164 | 165 | /** 166 | * @returns {string} Generated random value included in devices hash. 167 | */ 168 | getSaltDevices() { 169 | return this.SaltToHashDevices; 170 | } 171 | 172 | /** 173 | * @returns {string} Value used to verify devices. 174 | */ 175 | getVerifierDevices() { 176 | return this.verifierDevices; 177 | } 178 | 179 | /** 180 | * Generate salts and compute verifier. 181 | * @param {string} deviceGroupKey Devices to generate verifier for. 182 | * @param {string} username User to generate verifier for. 183 | * @returns {void} 184 | */ 185 | generateHashDevice(deviceGroupKey, username, callback) { 186 | this.randomPassword = this.generateRandomString(); 187 | const combinedString = `${deviceGroupKey}${username}:${this.randomPassword}`; 188 | const hashedString = this.hash(combinedString); 189 | 190 | const hexRandom = util.crypto.lib.randomBytes(16).toString('hex'); 191 | this.SaltToHashDevices = this.padHex(new BigInteger(hexRandom, 16)); 192 | 193 | this.computeModPow(this.g, new BigInteger(this.hexHash(this.SaltToHashDevices + hashedString), 16), this.N, (err, result) => { 194 | if (err) { 195 | return callback(new Error(err), null); 196 | } 197 | const verifierDevicesNotPadded = result; 198 | this.verifierDevices = this.padHex(verifierDevicesNotPadded); 199 | callback(null, 'SUCCESS'); 200 | }); 201 | return undefined; 202 | } 203 | 204 | /** 205 | * Calculate the client's public value A = g^a%N 206 | * with the generated random number a 207 | * @param {BigInteger} a Randomly generated small A. 208 | * @param {nodeCallback} callback Called on success or error. 209 | * @returns {void} 210 | * @private 211 | */ 212 | calculateA(a, callback) { 213 | this.computeModPow(this.g, a, this.N, (err, result) => { 214 | if (err) { 215 | return callback(new Error(err), null); 216 | } 217 | const A = result; 218 | if (A.mod(this.N).equals(BigInteger.ZERO)) { 219 | return callback(new Error('Illegal paramater. A mod N cannot be 0.'), null); 220 | } 221 | return callback(null, A); 222 | }); 223 | return undefined; 224 | } 225 | 226 | /** 227 | * Calculate the client's value U which is the hash of A and B 228 | * @param {BigInteger} A Large A value. 229 | * @param {BigInteger} B Server B value. 230 | * @returns {BigInteger} Computed U value. 231 | * @private 232 | */ 233 | calculateU(A, B) { 234 | this.UHexHash = this.hexHash(this.padHex(A) + this.padHex(B)); 235 | const finalU = new BigInteger(this.UHexHash, 16); 236 | 237 | return finalU; 238 | } 239 | 240 | /** 241 | * Calculate a hash from a bitArray 242 | * @param {Buffer} buf Value to hash. 243 | * @returns {String} Hex-encoded hash. 244 | * @private 245 | */ 246 | hash(buf) { 247 | const hashHex = util.crypto.sha256(buf, 'hex'); 248 | return (new Array(64 - hashHex.length).join('0')) + hashHex; 249 | } 250 | 251 | /** 252 | * Calculate a hash from a hex string 253 | * @param {String} hexStr Value to hash. 254 | * @returns {String} Hex-encoded hash. 255 | * @private 256 | */ 257 | hexHash(hexStr) { 258 | return this.hash(new util.Buffer(hexStr, 'hex')); 259 | } 260 | 261 | /** 262 | * Standard hkdf algorithm 263 | * @param {Buffer} ikm Input key material. 264 | * @param {Buffer} salt Salt value. 265 | * @returns {Buffer} Strong key material. 266 | * @private 267 | */ 268 | computehkdf(ikm, salt) { 269 | const prk = util.crypto.hmac(salt, ikm, 'buffer', 'sha256'); 270 | const infoBitsUpdate = util.buffer.concat([ 271 | this.infoBits, 272 | new util.Buffer(String.fromCharCode(1), 'utf8'), 273 | ]); 274 | const hmac = util.crypto.hmac(prk, infoBitsUpdate, 'buffer', 'sha256'); 275 | return hmac.slice(0, 16); 276 | } 277 | 278 | /** 279 | * Calculates the final hkdf based on computed S value, and computed U value and the key 280 | * @param {String} username Username. 281 | * @param {String} password Password. 282 | * @param {BigInteger} serverBValue Server B value. 283 | * @param {BigInteger} salt Generated salt. 284 | * @param {object} callback Result callback map. 285 | * @returns {void} 286 | */ 287 | getPasswordAuthenticationKey(username, password, serverBValue, salt, callback) { 288 | if (serverBValue.mod(this.N).equals(BigInteger.ZERO)) { 289 | callback(new Error('B cannot be zero.'), null); 290 | } 291 | 292 | this.UValue = this.calculateU(this.largeAValue, serverBValue); 293 | 294 | if (this.UValue.equals(BigInteger.ZERO)) { 295 | callback(new Error('U cannot be zero.'), null); 296 | } 297 | 298 | const usernamePassword = `${this.poolName}${username}:${password}`; 299 | const usernamePasswordHash = this.hash(usernamePassword); 300 | 301 | const xValue = new BigInteger(this.hexHash(this.padHex(salt) + usernamePasswordHash), 16); 302 | 303 | this.computeS(xValue, serverBValue, (err, result) => { 304 | if (err) { 305 | throw new Error(err); 306 | return; 307 | } 308 | const sValue = result; 309 | const hkdf = this.computehkdf( 310 | new util.Buffer(this.padHex(sValue), 'hex'), 311 | new util.Buffer(this.padHex(this.UValue.toString(16)), 'hex')); 312 | callback(null, hkdf); 313 | }); 314 | return undefined; 315 | } 316 | 317 | /** 318 | * Return constant newPasswordRequiredChallengeUserAttributePrefix 319 | * @return {newPasswordRequiredChallengeUserAttributePrefix} constant prefix value 320 | */ 321 | getNewPasswordRequiredChallengeUserAttributePrefix() { 322 | return newPasswordRequiredChallengeUserAttributePrefix; 323 | } 324 | 325 | /** 326 | * Converts a BigInteger (or hex string) to hex format padded with zeroes for hashing 327 | * @param {BigInteger|String} bigInt Number or string to pad. 328 | * @returns {String} Padded hex string. 329 | */ 330 | padHex(bigInt) { 331 | let hashStr = bigInt.toString(16); 332 | if (hashStr.length % 2 === 1) { 333 | hashStr = `0${hashStr}`; 334 | } else if ('89ABCDEFabcdef'.indexOf(hashStr[0]) !== -1) { 335 | hashStr = `00${hashStr}`; 336 | } 337 | return hashStr; 338 | } 339 | } 340 | -------------------------------------------------------------------------------- /src/BigInteger.js: -------------------------------------------------------------------------------- 1 | // A small implementation of BigInteger based on http://www-cs-students.stanford.edu/~tjw/jsbn/ 2 | // 3 | // All public methods have been removed except the following: 4 | // new BigInteger(a, b) (only radix 2, 4, 8, 16 and 32 supported) 5 | // toString (only radix 2, 4, 8, 16 and 32 supported) 6 | // negate 7 | // abs 8 | // compareTo 9 | // bitLength 10 | // mod 11 | // equals 12 | // add 13 | // subtract 14 | // multiply 15 | // divide 16 | // modPow 17 | 18 | export default BigInteger; 19 | 20 | /* 21 | * Copyright (c) 2003-2005 Tom Wu 22 | * All Rights Reserved. 23 | * 24 | * Permission is hereby granted, free of charge, to any person obtaining 25 | * a copy of this software and associated documentation files (the 26 | * "Software"), to deal in the Software without restriction, including 27 | * without limitation the rights to use, copy, modify, merge, publish, 28 | * distribute, sublicense, and/or sell copies of the Software, and to 29 | * permit persons to whom the Software is furnished to do so, subject to 30 | * the following conditions: 31 | * 32 | * The above copyright notice and this permission notice shall be 33 | * included in all copies or substantial portions of the Software. 34 | * 35 | * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, 36 | * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY 37 | * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. 38 | * 39 | * IN NO EVENT SHALL TOM WU BE LIABLE FOR ANY SPECIAL, INCIDENTAL, 40 | * INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, OR ANY DAMAGES WHATSOEVER 41 | * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER OR NOT ADVISED OF 42 | * THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF LIABILITY, ARISING OUT 43 | * OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. 44 | * 45 | * In addition, the following condition applies: 46 | * 47 | * All redistributions must retain an intact copy of this copyright notice 48 | * and disclaimer. 49 | */ 50 | 51 | // (public) Constructor 52 | function BigInteger(a, b) { 53 | if (a != null) this.fromString(a, b); 54 | } 55 | 56 | // return new, unset BigInteger 57 | function nbi() { 58 | return new BigInteger(null); 59 | } 60 | 61 | // Bits per digit 62 | var dbits; 63 | 64 | // JavaScript engine analysis 65 | var canary = 0xdeadbeefcafe; 66 | var j_lm = ((canary&0xffffff)==0xefcafe); 67 | 68 | // am: Compute w_j += (x*this_i), propagate carries, 69 | // c is initial carry, returns final carry. 70 | // c < 3*dvalue, x < 2*dvalue, this_i < dvalue 71 | // We need to select the fastest one that works in this environment. 72 | 73 | // am1: use a single mult and divide to get the high bits, 74 | // max digit bits should be 26 because 75 | // max internal value = 2*dvalue^2-2*dvalue (< 2^53) 76 | function am1(i,x,w,j,c,n) { 77 | while(--n >= 0) { 78 | var v = x*this[i++]+w[j]+c; 79 | c = Math.floor(v/0x4000000); 80 | w[j++] = v&0x3ffffff; 81 | } 82 | return c; 83 | } 84 | // am2 avoids a big mult-and-extract completely. 85 | // Max digit bits should be <= 30 because we do bitwise ops 86 | // on values up to 2*hdvalue^2-hdvalue-1 (< 2^31) 87 | function am2(i,x,w,j,c,n) { 88 | var xl = x&0x7fff, xh = x>>15; 89 | while(--n >= 0) { 90 | var l = this[i]&0x7fff; 91 | var h = this[i++]>>15; 92 | var m = xh*l+h*xl; 93 | l = xl*l+((m&0x7fff)<<15)+w[j]+(c&0x3fffffff); 94 | c = (l>>>30)+(m>>>15)+xh*h+(c>>>30); 95 | w[j++] = l&0x3fffffff; 96 | } 97 | return c; 98 | } 99 | // Alternately, set max digit bits to 28 since some 100 | // browsers slow down when dealing with 32-bit numbers. 101 | function am3(i,x,w,j,c,n) { 102 | var xl = x&0x3fff, xh = x>>14; 103 | while(--n >= 0) { 104 | var l = this[i]&0x3fff; 105 | var h = this[i++]>>14; 106 | var m = xh*l+h*xl; 107 | l = xl*l+((m&0x3fff)<<14)+w[j]+c; 108 | c = (l>>28)+(m>>14)+xh*h; 109 | w[j++] = l&0xfffffff; 110 | } 111 | return c; 112 | } 113 | var inBrowser = typeof navigator !== "undefined"; 114 | if(inBrowser && j_lm && (navigator.appName == "Microsoft Internet Explorer")) { 115 | BigInteger.prototype.am = am2; 116 | dbits = 30; 117 | } 118 | else if(inBrowser && j_lm && (navigator.appName != "Netscape")) { 119 | BigInteger.prototype.am = am1; 120 | dbits = 26; 121 | } 122 | else { // Mozilla/Netscape seems to prefer am3 123 | BigInteger.prototype.am = am3; 124 | dbits = 28; 125 | } 126 | 127 | BigInteger.prototype.DB = dbits; 128 | BigInteger.prototype.DM = (1 << dbits) - 1; 129 | BigInteger.prototype.DV = 1 << dbits; 130 | 131 | var BI_FP = 52; 132 | BigInteger.prototype.FV = Math.pow(2, BI_FP); 133 | BigInteger.prototype.F1 = BI_FP - dbits; 134 | BigInteger.prototype.F2 = 2 * dbits - BI_FP; 135 | 136 | // Digit conversions 137 | var BI_RM = "0123456789abcdefghijklmnopqrstuvwxyz"; 138 | var BI_RC = new Array(); 139 | var rr, vv; 140 | rr = "0".charCodeAt(0); 141 | for (vv = 0; vv <= 9; ++vv) 142 | BI_RC[rr++] = vv; 143 | rr = "a".charCodeAt(0); 144 | for (vv = 10; vv < 36; ++vv) 145 | BI_RC[rr++] = vv; 146 | rr = "A".charCodeAt(0); 147 | for (vv = 10; vv < 36; ++vv) 148 | BI_RC[rr++] = vv; 149 | 150 | function int2char(n) { 151 | return BI_RM.charAt(n); 152 | } 153 | function intAt(s, i) { 154 | var c = BI_RC[s.charCodeAt(i)]; 155 | return c == null ? -1 : c; 156 | } 157 | 158 | // (protected) copy this to r 159 | function bnpCopyTo(r) { 160 | for (var i = this.t - 1; i >= 0; --i) 161 | r[i] = this[i]; 162 | r.t = this.t; 163 | r.s = this.s; 164 | } 165 | 166 | // (protected) set from integer value x, -DV <= x < DV 167 | function bnpFromInt(x) { 168 | this.t = 1; 169 | this.s = x < 0 ? -1 : 0; 170 | if (x > 0) this[0] = x; 171 | else if (x < -1) this[0] = x + this.DV; 172 | else this.t = 0; 173 | } 174 | 175 | // return bigint initialized to value 176 | function nbv(i) { 177 | var r = nbi(); 178 | 179 | r.fromInt(i); 180 | 181 | return r; 182 | } 183 | 184 | // (protected) set from string and radix 185 | function bnpFromString(s, b) { 186 | var k; 187 | if (b == 16) k = 4; 188 | else if (b == 8) k = 3; 189 | else if (b == 2) k = 1; 190 | else if (b == 32) k = 5; 191 | else if (b == 4) k = 2; 192 | else throw new Error("Only radix 2, 4, 8, 16, 32 are supported"); 193 | this.t = 0; 194 | this.s = 0; 195 | var i = s.length, mi = false, sh = 0; 196 | while (--i >= 0) { 197 | var x = intAt(s, i); 198 | if (x < 0) { 199 | if (s.charAt(i) == "-") mi = true; 200 | continue; 201 | } 202 | mi = false; 203 | if (sh == 0) this[this.t++] = x; 204 | else if (sh + k > this.DB) { 205 | this[this.t - 1] |= (x & (1 << this.DB - sh) - 1) << sh; 206 | this[this.t++] = x >> this.DB - sh; 207 | } else this[this.t - 1] |= x << sh; 208 | sh += k; 209 | if (sh >= this.DB) sh -= this.DB; 210 | } 211 | this.clamp(); 212 | if (mi) BigInteger.ZERO.subTo(this, this); 213 | } 214 | 215 | // (protected) clamp off excess high words 216 | function bnpClamp() { 217 | var c = this.s & this.DM; 218 | while (this.t > 0 && this[this.t - 1] == c) 219 | --this.t; 220 | } 221 | 222 | // (public) return string representation in given radix 223 | function bnToString(b) { 224 | if (this.s < 0) return "-" + this.negate().toString(); 225 | var k; 226 | if (b == 16) k = 4; 227 | else if (b == 8) k = 3; 228 | else if (b == 2) k = 1; 229 | else if (b == 32) k = 5; 230 | else if (b == 4) k = 2; 231 | else throw new Error("Only radix 2, 4, 8, 16, 32 are supported"); 232 | var km = (1 << k) - 1, d, m = false, r = "", i = this.t; 233 | var p = this.DB - i * this.DB % k; 234 | if (i-- > 0) { 235 | if (p < this.DB && (d = this[i] >> p) > 0) { 236 | m = true; 237 | r = int2char(d); 238 | } 239 | while (i >= 0) { 240 | if (p < k) { 241 | d = (this[i] & (1 << p) - 1) << k - p; 242 | d |= this[--i] >> (p += this.DB - k); 243 | } else { 244 | d = this[i] >> (p -= k) & km; 245 | if (p <= 0) { 246 | p += this.DB; 247 | --i; 248 | } 249 | } 250 | if (d > 0) m = true; 251 | if (m) r += int2char(d); 252 | } 253 | } 254 | return m ? r : "0"; 255 | } 256 | 257 | // (public) -this 258 | function bnNegate() { 259 | var r = nbi(); 260 | 261 | BigInteger.ZERO.subTo(this, r); 262 | 263 | return r; 264 | } 265 | 266 | // (public) |this| 267 | function bnAbs() { 268 | return this.s < 0 ? this.negate() : this; 269 | } 270 | 271 | // (public) return + if this > a, - if this < a, 0 if equal 272 | function bnCompareTo(a) { 273 | var r = this.s - a.s; 274 | if (r != 0) return r; 275 | var i = this.t; 276 | r = i - a.t; 277 | if (r != 0) return this.s < 0 ? -r : r; 278 | while (--i >= 0) 279 | if ((r = this[i] - a[i]) != 0) return r; 280 | return 0; 281 | } 282 | 283 | // returns bit length of the integer x 284 | function nbits(x) { 285 | var r = 1, t; 286 | if ((t = x >>> 16) != 0) { 287 | x = t; 288 | r += 16; 289 | } 290 | if ((t = x >> 8) != 0) { 291 | x = t; 292 | r += 8; 293 | } 294 | if ((t = x >> 4) != 0) { 295 | x = t; 296 | r += 4; 297 | } 298 | if ((t = x >> 2) != 0) { 299 | x = t; 300 | r += 2; 301 | } 302 | if ((t = x >> 1) != 0) { 303 | x = t; 304 | r += 1; 305 | } 306 | return r; 307 | } 308 | 309 | // (public) return the number of bits in "this" 310 | function bnBitLength() { 311 | if (this.t <= 0) return 0; 312 | return this.DB * (this.t - 1) + nbits(this[this.t - 1] ^ this.s & this.DM); 313 | } 314 | 315 | // (protected) r = this << n*DB 316 | function bnpDLShiftTo(n, r) { 317 | var i; 318 | for (i = this.t - 1; i >= 0; --i) 319 | r[i + n] = this[i]; 320 | for (i = n - 1; i >= 0; --i) 321 | r[i] = 0; 322 | r.t = this.t + n; 323 | r.s = this.s; 324 | } 325 | 326 | // (protected) r = this >> n*DB 327 | function bnpDRShiftTo(n, r) { 328 | for (var i = n; i < this.t; ++i) 329 | r[i - n] = this[i]; 330 | r.t = Math.max(this.t - n, 0); 331 | r.s = this.s; 332 | } 333 | 334 | // (protected) r = this << n 335 | function bnpLShiftTo(n, r) { 336 | var bs = n % this.DB; 337 | var cbs = this.DB - bs; 338 | var bm = (1 << cbs) - 1; 339 | var ds = Math.floor(n / this.DB), c = this.s << bs & this.DM, i; 340 | for (i = this.t - 1; i >= 0; --i) { 341 | r[i + ds + 1] = this[i] >> cbs | c; 342 | c = (this[i] & bm) << bs; 343 | } 344 | for (i = ds - 1; i >= 0; --i) 345 | r[i] = 0; 346 | r[ds] = c; 347 | r.t = this.t + ds + 1; 348 | r.s = this.s; 349 | r.clamp(); 350 | } 351 | 352 | // (protected) r = this >> n 353 | function bnpRShiftTo(n, r) { 354 | r.s = this.s; 355 | var ds = Math.floor(n / this.DB); 356 | if (ds >= this.t) { 357 | r.t = 0; 358 | return; 359 | } 360 | var bs = n % this.DB; 361 | var cbs = this.DB - bs; 362 | var bm = (1 << bs) - 1; 363 | r[0] = this[ds] >> bs; 364 | for (var i = ds + 1; i < this.t; ++i) { 365 | r[i - ds - 1] |= (this[i] & bm) << cbs; 366 | r[i - ds] = this[i] >> bs; 367 | } 368 | if (bs > 0) r[this.t - ds - 1] |= (this.s & bm) << cbs; 369 | r.t = this.t - ds; 370 | r.clamp(); 371 | } 372 | 373 | // (protected) r = this - a 374 | function bnpSubTo(a, r) { 375 | var i = 0, c = 0, m = Math.min(a.t, this.t); 376 | while (i < m) { 377 | c += this[i] - a[i]; 378 | r[i++] = c & this.DM; 379 | c >>= this.DB; 380 | } 381 | if (a.t < this.t) { 382 | c -= a.s; 383 | while (i < this.t) { 384 | c += this[i]; 385 | r[i++] = c & this.DM; 386 | c >>= this.DB; 387 | } 388 | c += this.s; 389 | } else { 390 | c += this.s; 391 | while (i < a.t) { 392 | c -= a[i]; 393 | r[i++] = c & this.DM; 394 | c >>= this.DB; 395 | } 396 | c -= a.s; 397 | } 398 | r.s = c < 0 ? -1 : 0; 399 | if (c < -1) r[i++] = this.DV + c; 400 | else if (c > 0) r[i++] = c; 401 | r.t = i; 402 | r.clamp(); 403 | } 404 | 405 | // (protected) r = this * a, r != this,a (HAC 14.12) 406 | // "this" should be the larger one if appropriate. 407 | function bnpMultiplyTo(a, r) { 408 | var x = this.abs(), y = a.abs(); 409 | var i = x.t; 410 | r.t = i + y.t; 411 | while (--i >= 0) 412 | r[i] = 0; 413 | for (i = 0; i < y.t; ++i) 414 | r[i + x.t] = x.am(0, y[i], r, i, 0, x.t); 415 | r.s = 0; 416 | r.clamp(); 417 | if (this.s != a.s) BigInteger.ZERO.subTo(r, r); 418 | } 419 | 420 | // (protected) r = this^2, r != this (HAC 14.16) 421 | function bnpSquareTo(r) { 422 | var x = this.abs(); 423 | var i = r.t = 2 * x.t; 424 | while (--i >= 0) 425 | r[i] = 0; 426 | for (i = 0; i < x.t - 1; ++i) { 427 | var c = x.am(i, x[i], r, 2 * i, 0, 1); 428 | if ( 429 | (r[i + x.t] += x.am(i + 1, 2 * x[i], r, 2 * i + 1, c, x.t - i - 1)) >= 430 | x.DV 431 | ) { 432 | r[i + x.t] -= x.DV; 433 | r[i + x.t + 1] = 1; 434 | } 435 | } 436 | if (r.t > 0) r[r.t - 1] += x.am(i, x[i], r, 2 * i, 0, 1); 437 | r.s = 0; 438 | r.clamp(); 439 | } 440 | 441 | // (protected) divide this by m, quotient and remainder to q, r (HAC 14.20) 442 | // r != q, this != m. q or r may be null. 443 | function bnpDivRemTo(m, q, r) { 444 | var pm = m.abs(); 445 | if (pm.t <= 0) return; 446 | var pt = this.abs(); 447 | if (pt.t < pm.t) { 448 | if (q != null) q.fromInt(0); 449 | if (r != null) this.copyTo(r); 450 | return; 451 | } 452 | if (r == null) r = nbi(); 453 | var y = nbi(), ts = this.s, ms = m.s; 454 | var nsh = this.DB - nbits(pm[pm.t - 1]); 455 | // normalize modulus 456 | if (nsh > 0) { 457 | pm.lShiftTo(nsh, y); 458 | pt.lShiftTo(nsh, r); 459 | } else { 460 | pm.copyTo(y); 461 | pt.copyTo(r); 462 | } 463 | var ys = y.t; 464 | var y0 = y[ys - 1]; 465 | if (y0 == 0) return; 466 | var yt = y0 * (1 << this.F1) + (ys > 1 ? y[ys - 2] >> this.F2 : 0); 467 | var d1 = this.FV / yt, d2 = (1 << this.F1) / yt, e = 1 << this.F2; 468 | var i = r.t, j = i - ys, t = q == null ? nbi() : q; 469 | y.dlShiftTo(j, t); 470 | if (r.compareTo(t) >= 0) { 471 | r[r.t++] = 1; 472 | r.subTo(t, r); 473 | } 474 | BigInteger.ONE.dlShiftTo(ys, t); 475 | t.subTo(y, y); 476 | // "negative" y so we can replace sub with am later 477 | while (y.t < ys) 478 | y[y.t++] = 0; 479 | while (--j >= 0) { 480 | // Estimate quotient digit 481 | var qd = r[--i] == y0 482 | ? this.DM 483 | : Math.floor(r[i] * d1 + (r[i - 1] + e) * d2); 484 | if ((r[i] += y.am(0, qd, r, j, 0, ys)) < qd) { 485 | // Try it out 486 | y.dlShiftTo(j, t); 487 | r.subTo(t, r); 488 | while (r[i] < --qd) r.subTo(t, r); 489 | } 490 | } 491 | if (q != null) { 492 | r.drShiftTo(ys, q); 493 | if (ts != ms) BigInteger.ZERO.subTo(q, q); 494 | } 495 | r.t = ys; 496 | r.clamp(); 497 | if (nsh > 0) r.rShiftTo(nsh, r); 498 | // Denormalize remainder 499 | if (ts < 0) BigInteger.ZERO.subTo(r, r); 500 | } 501 | 502 | // (public) this mod a 503 | function bnMod(a) { 504 | var r = nbi(); 505 | this.abs().divRemTo(a, null, r); 506 | if (this.s < 0 && r.compareTo(BigInteger.ZERO) > 0) a.subTo(r, r); 507 | return r; 508 | } 509 | 510 | // (protected) return "-1/this % 2^DB"; useful for Mont. reduction 511 | // justification: 512 | // xy == 1 (mod m) 513 | // xy = 1+km 514 | // xy(2-xy) = (1+km)(1-km) 515 | // x[y(2-xy)] = 1-k^2m^2 516 | // x[y(2-xy)] == 1 (mod m^2) 517 | // if y is 1/x mod m, then y(2-xy) is 1/x mod m^2 518 | // should reduce x and y(2-xy) by m^2 at each step to keep size bounded. 519 | // JS multiply "overflows" differently from C/C++, so care is needed here. 520 | function bnpInvDigit() { 521 | if (this.t < 1) return 0; 522 | var x = this[0]; 523 | if ((x & 1) == 0) return 0; 524 | var y = x & 3; 525 | // y == 1/x mod 2^2 526 | y = y * (2 - (x & 0xf) * y) & 0xf; 527 | // y == 1/x mod 2^4 528 | y = y * (2 - (x & 0xff) * y) & 0xff; 529 | // y == 1/x mod 2^8 530 | y = y * (2 - ((x & 0xffff) * y & 0xffff)) & 0xffff; 531 | // y == 1/x mod 2^16 532 | // last step - calculate inverse mod DV directly; 533 | // assumes 16 < DB <= 32 and assumes ability to handle 48-bit ints 534 | y = y * (2 - x * y % this.DV) % this.DV; 535 | // y == 1/x mod 2^dbits 536 | // we really want the negative inverse, and -DV < y < DV 537 | return y > 0 ? this.DV - y : -y; 538 | } 539 | 540 | function bnEquals(a) { 541 | return this.compareTo(a) == 0; 542 | } 543 | 544 | // (protected) r = this + a 545 | function bnpAddTo(a, r) { 546 | var i = 0, c = 0, m = Math.min(a.t, this.t); 547 | while (i < m) { 548 | c += this[i] + a[i]; 549 | r[i++] = c & this.DM; 550 | c >>= this.DB; 551 | } 552 | if (a.t < this.t) { 553 | c += a.s; 554 | while (i < this.t) { 555 | c += this[i]; 556 | r[i++] = c & this.DM; 557 | c >>= this.DB; 558 | } 559 | c += this.s; 560 | } else { 561 | c += this.s; 562 | while (i < a.t) { 563 | c += a[i]; 564 | r[i++] = c & this.DM; 565 | c >>= this.DB; 566 | } 567 | c += a.s; 568 | } 569 | r.s = c < 0 ? -1 : 0; 570 | if (c > 0) r[i++] = c; 571 | else if (c < -1) r[i++] = this.DV + c; 572 | r.t = i; 573 | r.clamp(); 574 | } 575 | 576 | // (public) this + a 577 | function bnAdd(a) { 578 | var r = nbi(); 579 | 580 | this.addTo(a, r); 581 | 582 | return r; 583 | } 584 | 585 | // (public) this - a 586 | function bnSubtract(a) { 587 | var r = nbi(); 588 | 589 | this.subTo(a, r); 590 | 591 | return r; 592 | } 593 | 594 | // (public) this * a 595 | function bnMultiply(a) { 596 | var r = nbi(); 597 | 598 | this.multiplyTo(a, r); 599 | 600 | return r; 601 | } 602 | 603 | // (public) this / a 604 | function bnDivide(a) { 605 | var r = nbi(); 606 | 607 | this.divRemTo(a, r, null); 608 | 609 | return r; 610 | } 611 | 612 | // Montgomery reduction 613 | function Montgomery(m) { 614 | this.m = m; 615 | this.mp = m.invDigit(); 616 | this.mpl = this.mp & 0x7fff; 617 | this.mph = this.mp >> 15; 618 | this.um = (1 << m.DB - 15) - 1; 619 | this.mt2 = 2 * m.t; 620 | } 621 | 622 | // xR mod m 623 | function montConvert(x) { 624 | var r = nbi(); 625 | x.abs().dlShiftTo(this.m.t, r); 626 | r.divRemTo(this.m, null, r); 627 | if (x.s < 0 && r.compareTo(BigInteger.ZERO) > 0) this.m.subTo(r, r); 628 | return r; 629 | } 630 | 631 | // x/R mod m 632 | function montRevert(x) { 633 | var r = nbi(); 634 | x.copyTo(r); 635 | this.reduce(r); 636 | return r; 637 | } 638 | 639 | // x = x/R mod m (HAC 14.32) 640 | function montReduce(x) { 641 | while (x.t <= this.mt2) 642 | // pad x so am has enough room later 643 | x[x.t++] = 0; 644 | for (var i = 0; i < this.m.t; ++i) { 645 | // faster way of calculating u0 = x[i]*mp mod DV 646 | var j = x[i] & 0x7fff; 647 | var u0 = j * this.mpl + 648 | ((j * this.mph + (x[i] >> 15) * this.mpl & this.um) << 15) & 649 | x.DM; 650 | // use am to combine the multiply-shift-add into one call 651 | j = i + this.m.t; 652 | x[j] += this.m.am(0, u0, x, i, 0, this.m.t); 653 | // propagate carry 654 | while (x[j] >= x.DV) { 655 | x[j] -= x.DV; 656 | x[++j]++; 657 | } 658 | } 659 | x.clamp(); 660 | x.drShiftTo(this.m.t, x); 661 | if (x.compareTo(this.m) >= 0) x.subTo(this.m, x); 662 | } 663 | 664 | // r = "x^2/R mod m"; x != r 665 | function montSqrTo(x, r) { 666 | x.squareTo(r); 667 | 668 | this.reduce(r); 669 | } 670 | 671 | // r = "xy/R mod m"; x,y != r 672 | function montMulTo(x, y, r) { 673 | x.multiplyTo(y, r); 674 | 675 | this.reduce(r); 676 | } 677 | 678 | Montgomery.prototype.convert = montConvert; 679 | Montgomery.prototype.revert = montRevert; 680 | Montgomery.prototype.reduce = montReduce; 681 | Montgomery.prototype.mulTo = montMulTo; 682 | Montgomery.prototype.sqrTo = montSqrTo; 683 | 684 | // (public) this^e % m (HAC 14.85) 685 | function bnModPow(e, m) { 686 | var i = e.bitLength(), k, r = nbv(1), z = new Montgomery(m); 687 | if (i <= 0) return r; 688 | else if (i < 18) k = 1; 689 | else if (i < 48) k = 3; 690 | else if (i < 144) k = 4; 691 | else if (i < 768) k = 5; 692 | else k = 6; 693 | 694 | // precomputation 695 | var g = new Array(), n = 3, k1 = k - 1, km = (1 << k) - 1; 696 | g[1] = z.convert(this); 697 | if (k > 1) { 698 | var g2 = nbi(); 699 | z.sqrTo(g[1], g2); 700 | while (n <= km) { 701 | g[n] = nbi(); 702 | z.mulTo(g2, g[n - 2], g[n]); 703 | n += 2; 704 | } 705 | } 706 | 707 | var j = e.t - 1, w, is1 = true, r2 = nbi(), t; 708 | i = nbits(e[j]) - 1; 709 | while (j >= 0) { 710 | if (i >= k1) w = e[j] >> i - k1 & km; 711 | else { 712 | w = (e[j] & (1 << i + 1) - 1) << k1 - i; 713 | if (j > 0) w |= e[j - 1] >> this.DB + i - k1; 714 | } 715 | 716 | n = k; 717 | while ((w & 1) == 0) { 718 | w >>= 1; 719 | --n; 720 | } 721 | if ((i -= n) < 0) { 722 | i += this.DB; 723 | --j; 724 | } 725 | if (is1) { 726 | // ret == 1, don't bother squaring or multiplying it 727 | g[w].copyTo(r); 728 | is1 = false; 729 | } else { 730 | while (n > 1) { 731 | z.sqrTo(r, r2); 732 | z.sqrTo(r2, r); 733 | n -= 2; 734 | } 735 | if (n > 0) z.sqrTo(r, r2); 736 | else { 737 | t = r; 738 | r = r2; 739 | r2 = t; 740 | } 741 | z.mulTo(r2, g[w], r); 742 | } 743 | 744 | while (j >= 0 && (e[j] & 1 << i) == 0) { 745 | z.sqrTo(r, r2); 746 | t = r; 747 | r = r2; 748 | r2 = t; 749 | if (--i < 0) { 750 | i = this.DB - 1; 751 | --j; 752 | } 753 | } 754 | } 755 | return z.revert(r); 756 | } 757 | 758 | // protected 759 | BigInteger.prototype.copyTo = bnpCopyTo; 760 | BigInteger.prototype.fromInt = bnpFromInt; 761 | BigInteger.prototype.fromString = bnpFromString; 762 | BigInteger.prototype.clamp = bnpClamp; 763 | BigInteger.prototype.dlShiftTo = bnpDLShiftTo; 764 | BigInteger.prototype.drShiftTo = bnpDRShiftTo; 765 | BigInteger.prototype.lShiftTo = bnpLShiftTo; 766 | BigInteger.prototype.rShiftTo = bnpRShiftTo; 767 | BigInteger.prototype.subTo = bnpSubTo; 768 | BigInteger.prototype.multiplyTo = bnpMultiplyTo; 769 | BigInteger.prototype.squareTo = bnpSquareTo; 770 | BigInteger.prototype.divRemTo = bnpDivRemTo; 771 | BigInteger.prototype.invDigit = bnpInvDigit; 772 | BigInteger.prototype.addTo = bnpAddTo; 773 | 774 | // public 775 | BigInteger.prototype.toString = bnToString; 776 | BigInteger.prototype.negate = bnNegate; 777 | BigInteger.prototype.abs = bnAbs; 778 | BigInteger.prototype.compareTo = bnCompareTo; 779 | BigInteger.prototype.bitLength = bnBitLength; 780 | BigInteger.prototype.mod = bnMod; 781 | BigInteger.prototype.equals = bnEquals; 782 | BigInteger.prototype.add = bnAdd; 783 | BigInteger.prototype.subtract = bnSubtract; 784 | BigInteger.prototype.multiply = bnMultiply; 785 | BigInteger.prototype.divide = bnDivide; 786 | BigInteger.prototype.modPow = bnModPow; 787 | 788 | // "constants" 789 | BigInteger.ZERO = nbv(0); 790 | BigInteger.ONE = nbv(1); 791 | 792 | -------------------------------------------------------------------------------- /src/CognitoAccessToken.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 | 18 | import { util } from 'aws-sdk/dist/aws-sdk-react-native'; 19 | 20 | /** @class */ 21 | export default class CognitoAccessToken { 22 | /** 23 | * Constructs a new CognitoAccessToken object 24 | * @param {string=} AccessToken The JWT access token. 25 | */ 26 | constructor({ AccessToken } = {}) { 27 | // Assign object 28 | this.jwtToken = AccessToken || ''; 29 | } 30 | 31 | /** 32 | * @returns {string} the record's token. 33 | */ 34 | getJwtToken() { 35 | return this.jwtToken; 36 | } 37 | 38 | /** 39 | * @returns {int} the token's expiration (exp member). 40 | */ 41 | getExpiration() { 42 | const payload = this.jwtToken.split('.')[1]; 43 | const expiration = JSON.parse(util.base64.decode(payload).toString('utf8')); 44 | return expiration.exp; 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /src/CognitoIdToken.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 | 18 | import { util } from 'aws-sdk/dist/aws-sdk-react-native'; 19 | 20 | /** @class */ 21 | export default class CognitoIdToken { 22 | /** 23 | * Constructs a new CognitoIdToken object 24 | * @param {string=} IdToken The JWT Id token 25 | */ 26 | constructor({ IdToken } = {}) { 27 | // Assign object 28 | this.jwtToken = IdToken || ''; 29 | } 30 | 31 | /** 32 | * @returns {string} the record's token. 33 | */ 34 | getJwtToken() { 35 | return this.jwtToken; 36 | } 37 | 38 | /** 39 | * @returns {int} the token's expiration (exp member). 40 | */ 41 | getExpiration() { 42 | const payload = this.jwtToken.split('.')[1]; 43 | const expiration = JSON.parse(util.base64.decode(payload).toString('utf8')); 44 | return expiration.exp; 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /src/CognitoRefreshToken.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 | 18 | /** @class */ 19 | export default class CognitoRefreshToken { 20 | /** 21 | * Constructs a new CognitoRefreshToken object 22 | * @param {string=} RefreshToken The JWT refresh token. 23 | */ 24 | constructor({ RefreshToken } = {}) { 25 | // Assign object 26 | this.token = RefreshToken || ''; 27 | } 28 | 29 | /** 30 | * @returns {string} the record's token. 31 | */ 32 | getToken() { 33 | return this.token; 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/CognitoUserAttribute.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 | 18 | /** @class */ 19 | export default class CognitoUserAttribute { 20 | /** 21 | * Constructs a new CognitoUserAttribute object 22 | * @param {string=} Name The record's name 23 | * @param {string=} Value The record's value 24 | */ 25 | constructor({ Name, Value } = {}) { 26 | this.Name = Name || ''; 27 | this.Value = Value || ''; 28 | } 29 | 30 | /** 31 | * @returns {string} the record's value. 32 | */ 33 | getValue() { 34 | return this.Value; 35 | } 36 | 37 | /** 38 | * Sets the record's value. 39 | * @param {string} value The new value. 40 | * @returns {CognitoUserAttribute} The record for method chaining. 41 | */ 42 | setValue(value) { 43 | this.Value = value; 44 | return this; 45 | } 46 | 47 | /** 48 | * @returns {string} the record's name. 49 | */ 50 | getName() { 51 | return this.Name; 52 | } 53 | 54 | /** 55 | * Sets the record's name 56 | * @param {string} name The new name. 57 | * @returns {CognitoUserAttribute} The record for method chaining. 58 | */ 59 | setName(name) { 60 | this.Name = name; 61 | return this; 62 | } 63 | 64 | /** 65 | * @returns {string} a string representation of the record. 66 | */ 67 | toString() { 68 | return JSON.stringify(this); 69 | } 70 | 71 | /** 72 | * @returns {object} a flat object representing the record. 73 | */ 74 | toJSON() { 75 | return { 76 | Name: this.Name, 77 | Value: this.Value, 78 | }; 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /src/CognitoUserPool.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 | 18 | import { CognitoIdentityServiceProvider } from 'aws-sdk/dist/aws-sdk-react-native'; 19 | 20 | import CognitoUser from './CognitoUser'; 21 | import StorageHelper from './StorageHelper'; 22 | 23 | /** @class */ 24 | export default class CognitoUserPool { 25 | /** 26 | * Constructs a new CognitoUserPool object 27 | * @param {object} data Creation options. 28 | * @param {string} data.UserPoolId Cognito user pool id. 29 | * @param {string} data.ClientId User pool application client id. 30 | * @param {object} data.Storage Optional storage object. 31 | */ 32 | constructor(data) { 33 | const { UserPoolId, ClientId, endpoint } = data || {}; 34 | if (!UserPoolId || !ClientId) { 35 | throw new Error('Both UserPoolId and ClientId are required.'); 36 | } 37 | if (!/^[\w-]+_.+$/.test(UserPoolId)) { 38 | throw new Error('Invalid UserPoolId format.'); 39 | } 40 | const region = UserPoolId.split('_')[0]; 41 | 42 | this.userPoolId = UserPoolId; 43 | this.clientId = ClientId; 44 | 45 | this.client = new CognitoIdentityServiceProvider({ apiVersion: '2016-04-19', region, endpoint }); 46 | 47 | this.storage = data.Storage || new StorageHelper().getStorage(); 48 | } 49 | 50 | /** 51 | * @returns {string} the user pool id 52 | */ 53 | getUserPoolId() { 54 | return this.userPoolId; 55 | } 56 | 57 | /** 58 | * @returns {string} the client id 59 | */ 60 | getClientId() { 61 | return this.clientId; 62 | } 63 | 64 | /** 65 | * @typedef {object} SignUpResult 66 | * @property {CognitoUser} user New user. 67 | * @property {bool} userConfirmed If the user is already confirmed. 68 | */ 69 | /** 70 | * method for signing up a user 71 | * @param {string} username User's username. 72 | * @param {string} password Plain-text initial password entered by user. 73 | * @param {(AttributeArg[])=} userAttributes New user attributes. 74 | * @param {(AttributeArg[])=} validationData Application metadata. 75 | * @param {nodeCallback} callback Called on error or with the new user. 76 | * @returns {void} 77 | */ 78 | signUp(username, password, userAttributes, validationData, callback) { 79 | this.client.makeUnauthenticatedRequest('signUp', { 80 | ClientId: this.clientId, 81 | Username: username, 82 | Password: password, 83 | UserAttributes: userAttributes, 84 | ValidationData: validationData, 85 | }, (err, data) => { 86 | if (err) { 87 | return callback(err, null); 88 | } 89 | 90 | const cognitoUser = { 91 | Username: username, 92 | Pool: this, 93 | Storage: this.storage, 94 | }; 95 | 96 | const returnData = { 97 | user: new CognitoUser(cognitoUser), 98 | userConfirmed: data.UserConfirmed, 99 | userSub: data.UserSub, 100 | }; 101 | 102 | return callback(null, returnData); 103 | }); 104 | } 105 | 106 | 107 | /** 108 | * method for getting the current user of the application from the local storage 109 | * 110 | * @returns {CognitoUser} the user retrieved from storage 111 | */ 112 | getCurrentUser() { 113 | const lastUserKey = `CognitoIdentityServiceProvider.${this.clientId}.LastAuthUser`; 114 | 115 | const lastAuthUser = this.storage.getItem(lastUserKey); 116 | if (lastAuthUser) { 117 | const cognitoUser = { 118 | Username: lastAuthUser, 119 | Pool: this, 120 | Storage: this.storage, 121 | }; 122 | 123 | return new CognitoUser(cognitoUser); 124 | } 125 | 126 | return null; 127 | } 128 | } 129 | -------------------------------------------------------------------------------- /src/CognitoUserSession.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 | 18 | /** @class */ 19 | export default class CognitoUserSession { 20 | /** 21 | * Constructs a new CognitoUserSession object 22 | * @param {string} IdToken The session's Id token. 23 | * @param {string=} RefreshToken The session's refresh token. 24 | * @param {string} AccessToken The session's access token. 25 | */ 26 | constructor({ IdToken, RefreshToken, AccessToken } = {}) { 27 | if (AccessToken == null || IdToken == null) { 28 | throw new Error('Id token and Access Token must be present.'); 29 | } 30 | 31 | this.idToken = IdToken; 32 | this.refreshToken = RefreshToken; 33 | this.accessToken = AccessToken; 34 | } 35 | 36 | /** 37 | * @returns {CognitoIdToken} the session's Id token 38 | */ 39 | getIdToken() { 40 | return this.idToken; 41 | } 42 | 43 | /** 44 | * @returns {CognitoRefreshToken} the session's refresh token 45 | */ 46 | getRefreshToken() { 47 | return this.refreshToken; 48 | } 49 | 50 | /** 51 | * @returns {CognitoAccessToken} the session's access token 52 | */ 53 | getAccessToken() { 54 | return this.accessToken; 55 | } 56 | 57 | /** 58 | * Checks to see if the session is still valid based on session expiry information found 59 | * in tokens and the current time 60 | * @returns {boolean} if the session is still valid 61 | */ 62 | isValid() { 63 | const now = Math.floor(new Date() / 1000); 64 | 65 | return now < this.accessToken.getExpiration() && now < this.idToken.getExpiration(); 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /src/DateHelper.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 | 18 | const monthNames = 19 | ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; 20 | const weekNames = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']; 21 | 22 | /** @class */ 23 | export default class DateHelper { 24 | /** 25 | * @returns {string} The current time in "ddd MMM D HH:mm:ss UTC YYYY" format. 26 | */ 27 | getNowString() { 28 | const now = new Date(); 29 | 30 | const weekDay = weekNames[now.getUTCDay()]; 31 | const month = monthNames[now.getUTCMonth()]; 32 | const day = now.getUTCDate(); 33 | 34 | let hours = now.getUTCHours(); 35 | if (hours < 10) { 36 | hours = `0${hours}`; 37 | } 38 | 39 | let minutes = now.getUTCMinutes(); 40 | if (minutes < 10) { 41 | minutes = `0${minutes}`; 42 | } 43 | 44 | let seconds = now.getUTCSeconds(); 45 | if (seconds < 10) { 46 | seconds = `0${seconds}`; 47 | } 48 | 49 | const year = now.getUTCFullYear(); 50 | 51 | // ddd MMM D HH:mm:ss UTC YYYY 52 | const dateNow = `${weekDay} ${month} ${day} ${hours}:${minutes}:${seconds} UTC ${year}`; 53 | 54 | return dateNow; 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /src/StorageHelper.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 | 18 | import { AsyncStorage } from 'react-native'; 19 | 20 | const MEMORY_KEY_PREFIX = '@MemoryStorage:'; 21 | let dataMemory = {}; 22 | 23 | /** @class */ 24 | class MemoryStorage { 25 | 26 | /** 27 | * This is used to set a specific item in storage 28 | * @param {string} key - the key for the item 29 | * @param {object} value - the value 30 | * @returns {string} value that was set 31 | */ 32 | static setItem(key, value) { 33 | AsyncStorage.setItem(MEMORY_KEY_PREFIX + key, value); 34 | dataMemory[key] = value; 35 | return dataMemory[key]; 36 | } 37 | 38 | /** 39 | * This is used to get a specific key from storage 40 | * @param {string} key - the key for the item 41 | * This is used to clear the storage 42 | * @returns {string} the data item 43 | */ 44 | static getItem(key) { 45 | return Object.prototype.hasOwnProperty.call(dataMemory, key) ? dataMemory[key] : undefined; 46 | } 47 | 48 | /** 49 | * This is used to remove an item from storage 50 | * @param {string} key - the key being set 51 | * @returns {string} value - value that was deleted 52 | */ 53 | static removeItem(key) { 54 | AsyncStorage.removeItem(MEMORY_KEY_PREFIX + key); 55 | return delete dataMemory[key]; 56 | } 57 | 58 | /** 59 | * This is used to clear the storage 60 | * @returns {string} nothing 61 | */ 62 | static clear() { 63 | dataMemory = {}; 64 | return dataMemory; 65 | } 66 | 67 | /** 68 | * Will sync the MemoryStorage data from AsyncStorage to storageWindow MemoryStorage 69 | * @returns {void} 70 | */ 71 | static sync(callback) { 72 | AsyncStorage.getAllKeys((err, keys) => { 73 | if (err) return callback(err, null); 74 | const memoryKeys = keys.filter((key) => key.startsWith(MEMORY_KEY_PREFIX)); 75 | AsyncStorage.multiGet(memoryKeys, (err, stores) => { 76 | if (err) return callback(err, null); 77 | stores.map((result, index, store) => { 78 | const key = store[index][0]; 79 | const value = store[index][1]; 80 | const memoryKey = key.replace(MEMORY_KEY_PREFIX, ''); 81 | dataMemory[memoryKey] = value; 82 | }); 83 | callback(null, 'SUCCESS'); 84 | }); 85 | }); 86 | } 87 | } 88 | 89 | /** @class */ 90 | export default class StorageHelper { 91 | 92 | /** 93 | * This is used to get a storage object 94 | * @returns {object} the storage 95 | */ 96 | constructor() { 97 | this.storageWindow = MemoryStorage; 98 | } 99 | 100 | /** 101 | * This is used to return the storage 102 | * @returns {object} the storage 103 | */ 104 | getStorage() { 105 | return this.storageWindow; 106 | } 107 | } 108 | -------------------------------------------------------------------------------- /src/index.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 | 18 | export { default as AuthenticationDetails } from './AuthenticationDetails'; 19 | export { default as AuthenticationHelper } from './AuthenticationHelper'; 20 | export { default as CognitoAccessToken } from './CognitoAccessToken'; 21 | export { default as CognitoIdToken } from './CognitoIdToken'; 22 | export { default as CognitoRefreshToken } from './CognitoRefreshToken'; 23 | export { default as CognitoUser } from './CognitoUser'; 24 | export { default as CognitoUserAttribute } from './CognitoUserAttribute'; 25 | export { default as CognitoUserPool } from './CognitoUserPool'; 26 | export { default as CognitoUserSession } from './CognitoUserSession'; 27 | export { default as DateHelper } from './DateHelper'; 28 | -------------------------------------------------------------------------------- /yarn.lock: -------------------------------------------------------------------------------- 1 | # THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY. 2 | # yarn lockfile v1 3 | 4 | 5 | aws-sdk@*: 6 | version "2.106.0" 7 | resolved "https://registry.yarnpkg.com/aws-sdk/-/aws-sdk-2.106.0.tgz#8296b8ffbc63be61ae0a73b0e66f72b98baf293c" 8 | dependencies: 9 | buffer "4.9.1" 10 | crypto-browserify "1.0.9" 11 | events "^1.1.1" 12 | jmespath "0.15.0" 13 | querystring "0.2.0" 14 | sax "1.2.1" 15 | url "0.10.3" 16 | uuid "3.0.1" 17 | xml2js "0.4.17" 18 | xmlbuilder "4.2.1" 19 | 20 | base64-js@^1.0.2: 21 | version "1.2.0" 22 | resolved "https://registry.yarnpkg.com/base64-js/-/base64-js-1.2.0.tgz#a39992d723584811982be5e290bb6a53d86700f1" 23 | 24 | buffer@4.9.1: 25 | version "4.9.1" 26 | resolved "https://registry.yarnpkg.com/buffer/-/buffer-4.9.1.tgz#6d1bb601b07a4efced97094132093027c95bc298" 27 | dependencies: 28 | base64-js "^1.0.2" 29 | ieee754 "^1.1.4" 30 | isarray "^1.0.0" 31 | 32 | crypto-browserify@1.0.9: 33 | version "1.0.9" 34 | resolved "https://registry.yarnpkg.com/crypto-browserify/-/crypto-browserify-1.0.9.tgz#cc5449685dfb85eb11c9828acc7cb87ab5bbfcc0" 35 | 36 | events@^1.1.1: 37 | version "1.1.1" 38 | resolved "https://registry.yarnpkg.com/events/-/events-1.1.1.tgz#9ebdb7635ad099c70dcc4c2a1f5004288e8bd924" 39 | 40 | ieee754@^1.1.4: 41 | version "1.1.8" 42 | resolved "https://registry.yarnpkg.com/ieee754/-/ieee754-1.1.8.tgz#be33d40ac10ef1926701f6f08a2d86fbfd1ad3e4" 43 | 44 | isarray@^1.0.0: 45 | version "1.0.0" 46 | resolved "https://registry.yarnpkg.com/isarray/-/isarray-1.0.0.tgz#bb935d48582cba168c06834957a54a3e07124f11" 47 | 48 | jmespath@0.15.0: 49 | version "0.15.0" 50 | resolved "https://registry.yarnpkg.com/jmespath/-/jmespath-0.15.0.tgz#a3f222a9aae9f966f5d27c796510e28091764217" 51 | 52 | lodash@^4.0.0: 53 | version "4.17.4" 54 | resolved "https://registry.yarnpkg.com/lodash/-/lodash-4.17.4.tgz#78203a4d1c328ae1d86dca6460e369b57f4055ae" 55 | 56 | punycode@1.3.2: 57 | version "1.3.2" 58 | resolved "https://registry.yarnpkg.com/punycode/-/punycode-1.3.2.tgz#9653a036fb7c1ee42342f2325cceefea3926c48d" 59 | 60 | querystring@0.2.0: 61 | version "0.2.0" 62 | resolved "https://registry.yarnpkg.com/querystring/-/querystring-0.2.0.tgz#b209849203bb25df820da756e747005878521620" 63 | 64 | sax@1.2.1: 65 | version "1.2.1" 66 | resolved "https://registry.yarnpkg.com/sax/-/sax-1.2.1.tgz#7b8e656190b228e81a66aea748480d828cd2d37a" 67 | 68 | sax@>=0.6.0: 69 | version "1.1.5" 70 | resolved "https://registry.yarnpkg.com/sax/-/sax-1.1.5.tgz#1da50a8d00cdecd59405659f5ff85349fe773743" 71 | 72 | url@0.10.3: 73 | version "0.10.3" 74 | resolved "https://registry.yarnpkg.com/url/-/url-0.10.3.tgz#021e4d9c7705f21bbf37d03ceb58767402774c64" 75 | dependencies: 76 | punycode "1.3.2" 77 | querystring "0.2.0" 78 | 79 | uuid@3.0.1: 80 | version "3.0.1" 81 | resolved "https://registry.yarnpkg.com/uuid/-/uuid-3.0.1.tgz#6544bba2dfda8c1cf17e629a3a305e2bb1fee6c1" 82 | 83 | xml2js@0.4.17: 84 | version "0.4.17" 85 | resolved "https://registry.yarnpkg.com/xml2js/-/xml2js-0.4.17.tgz#17be93eaae3f3b779359c795b419705a8817e868" 86 | dependencies: 87 | sax ">=0.6.0" 88 | xmlbuilder "^4.1.0" 89 | 90 | xmlbuilder@4.2.1, xmlbuilder@^4.1.0: 91 | version "4.2.1" 92 | resolved "https://registry.yarnpkg.com/xmlbuilder/-/xmlbuilder-4.2.1.tgz#aa58a3041a066f90eaa16c2f5389ff19f3f461a5" 93 | dependencies: 94 | lodash "^4.0.0" 95 | --------------------------------------------------------------------------------