├── .gitignore ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── Gruntfile.js ├── ISSUE_TEMPLATE.md ├── LICENSE ├── PULL_REQUEST_TEMPLATE.md ├── README.md ├── package.json ├── plugin.xml ├── scripts ├── android │ └── beforePluginInstall.js └── lib │ └── utilities.js ├── src ├── android │ ├── .gitignore │ └── uk │ │ └── co │ │ └── reallysmall │ │ └── cordova │ │ └── plugin │ │ └── firebase │ │ └── ui │ │ └── auth │ │ └── FirebaseUIAuthPlugin.java └── ios │ ├── FirebaseUIAuthPlugin.h │ └── FirebaseUIAuthPlugin.m ├── types └── index.d.ts └── www ├── browser └── firebaseUIAuthPlugin.js └── firebaseUIAuthPlugin.js /.gitignore: -------------------------------------------------------------------------------- 1 | .git.safe 2 | /node_modules 3 | /test-reports/jshint.xml 4 | .vscode 5 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation. 6 | 7 | ## Our Standards 8 | 9 | Examples of behavior that contributes to creating a positive environment include: 10 | 11 | * Using welcoming and inclusive language 12 | * Being respectful of differing viewpoints and experiences 13 | * Gracefully accepting constructive criticism 14 | * Focusing on what is best for the community 15 | * Showing empathy towards other community members 16 | 17 | Examples of unacceptable behavior by participants include: 18 | 19 | * The use of sexualized language or imagery and unwelcome sexual attention or advances 20 | * Trolling, insulting/derogatory comments, and personal or political attacks 21 | * Public or private harassment 22 | * Publishing others' private information, such as a physical or electronic address, without explicit permission 23 | * Other conduct which could reasonably be considered inappropriate in a professional setting 24 | 25 | ## Our Responsibilities 26 | 27 | Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. 28 | 29 | Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. 30 | 31 | ## Scope 32 | 33 | This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. 34 | 35 | ## Enforcement 36 | 37 | Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at richard.windley@gmail.com. The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. 38 | 39 | Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership. 40 | 41 | ## Attribution 42 | 43 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version] 44 | 45 | [homepage]: http://contributor-covenant.org 46 | [version]: http://contributor-covenant.org/version/1/4/ 47 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing 2 | We want to make contributing to this project as easy and transparent as possible, whether it's: 3 | 4 | - Reporting a bug 5 | - Discussing the current state of the code 6 | - Submitting a fix 7 | - Proposing new features 8 | 9 | ## We Develop with Github 10 | We use github to host code, to track issues and feature requests, as well as accept pull requests. 11 | 12 | ## We Use [Github Flow](https://guides.github.com/introduction/flow/index.html), So All Code Changes Happen Through Pull Requests 13 | Pull requests are the best way to propose changes to the codebase (we use [Github Flow](https://guides.github.com/introduction/flow/index.html)). We actively welcome your pull requests: 14 | 15 | 1. Fork the repo and create your branch from `master`. 16 | 2. If you've added code that should be tested, add tests. 17 | 3. If you've changed APIs, update the documentation. 18 | 4. Ensure the test suite passes. 19 | 5. Make sure your code lints. 20 | 6. Issue that pull request! 21 | 22 | ## Any contributions you make will be under the licence specified in the LICENSE file 23 | In short, when you submit code changes, your submissions are understood to be under the same License that covers the project. Feel free to contact the maintainers if that's a concern. 24 | 25 | ## Report bugs using Github's [issues](https://github.com/ReallySmallSoftware/cordova-plugin-firebaseui-auth/issues) 26 | We use GitHub issues to track public bugs. Report a bug by [opening a new issue](https://github.com/ReallySmallSoftware/cordova-plugin-firebaseui-auth/issues/new); it's that easy! 27 | 28 | ## Write bug reports with detail, background, and sample code where appropriate 29 | Make sure at the very least you provide the information in the [issue template](https://github.com/ReallySmallSoftware/cordova-plugin-firebaseui-auth/blob/master/ISSUE_TEMPLATE.md) 30 | 31 | ## Use a Consistent Coding Style 32 | The coding style should match what is present in the code currently. Do not reformat entire files. 33 | 34 | ## References 35 | This document was adapted from the open-source contribution guidelines for [Facebook's Draft](https://github.com/facebook/draft-js/blob/a9316a723f9e918afde44dea68b5f9f39b7d9b00/CONTRIBUTING.md) 36 | -------------------------------------------------------------------------------- /Gruntfile.js: -------------------------------------------------------------------------------- 1 | module.exports = function(grunt) { 2 | 3 | // Project configuration. 4 | grunt.initConfig({ 5 | jshint: { 6 | options: { 7 | reporter: require("jshint-junit-reporter"), 8 | reporterOutput: "test-reports/jshint.xml", 9 | curly: true, 10 | eqeqeq: true, 11 | immed: true, 12 | latedef: true, 13 | newcap: true, 14 | noarg: true, 15 | sub: true, 16 | undef: true, 17 | boss: true, 18 | eqnull: true, 19 | node: true, 20 | es5: false, 21 | globals: { 22 | jasmine: false, 23 | describe: false, 24 | beforeEach: false, 25 | afterEach: false, 26 | expect: false, 27 | it: false, 28 | spyOn: false, 29 | $: false, 30 | cordova: false, 31 | launchnavigator: false, 32 | window: false, 33 | document: false, 34 | ons: false, 35 | navigator: false, 36 | google: false, 37 | FCMPlugin: false, 38 | device: false, 39 | plugins: false, 40 | addFixture: false, 41 | truncateSql: false 42 | } 43 | }, 44 | all: ['Gruntfile.js', 'www/**/*.js'] 45 | } 46 | }); 47 | 48 | grunt.loadNpmTasks('grunt-contrib-jshint'); 49 | }; 50 | -------------------------------------------------------------------------------- /ISSUE_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | ## Expected Behavior 2 | 3 | 4 | ## Actual Behavior 5 | 6 | 7 | ## Steps to Reproduce the Problem 8 | 9 | 10 | ## Specifications 11 | 12 | - Plugin version: 13 | - Framework: 14 | - Framework version: 15 | - Operating system: 16 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /PULL_REQUEST_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | Fixes # 2 | 3 | ## Proposed Changes 4 | 5 | - 6 | - 7 | - 8 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # cordova-plugin-firebaseui-auth 2 | A FirebaseUI Auth plugin to enable easy authentication using a number of different providers. 3 | 4 | # What is FirebaseUI? 5 | From the documentation (https://opensource.google.com/projects/firebaseui): 6 | 7 | > A UI library for Firebase, including binding for the realtime database, authentication and storage. 8 | 9 | # Supported platforms 10 | This plugin supports the following platforms: 11 | 12 | - Android 13 | - iOS 14 | - Browser 15 | 16 | # Support providers 17 | The following providers are currently supported: 18 | 19 | - Google 20 | - Facebook 21 | - Email 22 | 23 | Follow the instructions for each of the platforms and providers you wish you use in order to add firebase to your app: 24 | 25 | - https://firebase.google.com/docs/android/setup?authuser=0#manually_add_firebase 26 | - https://firebase.google.com/docs/ios/setup?authuser=0#manually_add_firebase 27 | - https://developers.facebook.com/ 28 | 29 | # Installation 30 | 31 | ``` 32 | cordova plugin add cordova-plugin-firebaseui-auth --variable ANDROID_FIREBASE_CORE_VERSION=16.0.0 33 | --variable ANDROID_FIREBASE_AUTH_VERSION=16.0.1 34 | --variable ANDROID_PLAY_SERVICES_AUTH_VERSION=15.0.1 35 | --variable ANDROID_FIREBASEUI_VERSION=3.3.1 36 | --variable ANDROID_FACEBOOK_SDK_VERSION=4.31.0 37 | --variable FACEBOOK_APPLICATION_ID=12345678 38 | --variable FACEBOOK_DISPLAY_NAME="My application" 39 | --variable REVERSED_CLIENT_ID="com.googleusercontent.apps.9999999999-xxxxxxxxxxxxxxxxxxxxxxxxxx" 40 | --variable COLOR_PRIMARY="#ffffff" 41 | --variable COLOR_DARK_PRIMARY="#555555" 42 | --variable COLOR_LIGHT_PRIMARY="#aaaaaa" 43 | --variable COLOR_ACCENT="#7C4DFF" 44 | --variable COLOR_SECONDARY="#FFC107" 45 | --variable COLOR_CONTROL="#ffffff" 46 | --variable COLOR_BACKGROUND="#000000" 47 | ``` 48 | 49 | or 50 | 51 | ``` 52 | phonegap plugin add cordova-plugin-firebaseui-auth --variable ANDROID_FIREBASE_CORE_VERSION=16.0.0 53 | --variable ANDROID_PLAY_SERVICES_AUTH_VERSION=16.0.1 54 | --variable ANDROID_FIREBASE_AUTH_VERSION=15.1.0 55 | --variable ANDROID_FIREBASEUI_VERSION=3.3.1 56 | --variable ANDROID_FACEBOOK_SDK_VERSION=4.31.0 57 | --variable FACEBOOK_APPLICATION_ID=12345678 58 | --variable FACEBOOK_DISPLAY_NAME="My application" 59 | --variable REVERSED_CLIENT_ID="com.googleusercontent.apps.9999999999-xxxxxxxxxxxxxxxxxxxxxxxxxx" 60 | --variable COLOR_PRIMARY="#ffffff" 61 | --variable COLOR_DARK_PRIMARY="#555555" 62 | --variable COLOR_LIGHT_PRIMARY="#aaaaaa" 63 | --variable COLOR_ACCENT="#7C4DFF" 64 | --variable COLOR_SECONDARY="#FFC107" 65 | --variable COLOR_CONTROL="#ffffff" 66 | --variable COLOR_BACKGROUND="#000000" 67 | ``` 68 | 69 | Any variables that are not supplied will use default values. For credential based variables (FACEBOOK_APPLICATION_ID, REVERSED_CLIENT_ID and REVERSED_CLIENT_ID) this will result in the provider not working until you supply real values. 70 | 71 | Not all variables are relevant to all providers: 72 | 73 | - ANDROID_FIREBASE_CORE_VERSION: the version of Firebase Core to use 74 | - ANDROID_FIREBASE_AUTH_VERSION: the version of Firebase Authentication to use 75 | - ANDROID_PLAY_SERVICES_AUTH_VERSION: the version of Play Services Account Login to use 76 | - ANDROID_FIREBASEUI_VERSION: the version of Firebase UI to use 77 | - ANDROID_FACEBOOK_SDK_VERSION: the version of the Facebook SDK to use 78 | - FACEBOOK_APPLICATION_ID: Facebook only - the application id if your application 79 | - FACEBOOK_DISPLAY_NAME: Facebook only - the display name of your application - only used by iOS 80 | - REVERSED_CLIENT_ID: Google only - the reversed client Id which can be found in your GoogleService-Info.plist file - only used by iOS 81 | - COLOR_PRIMARY: Used to style the UI - only used by Android 82 | - COLOR_DARK_PRIMARY: Used to style the UI - only used by Android 83 | - COLOR_LIGHT_PRIMARY: Used to style the UI - only used by Android 84 | - COLOR_ACCENT: Used to style the UI - only used by Android 85 | - COLOR_SECONDARY: Used to style the UI - only used by Android 86 | - COLOR_CONTROL: Used to style the UI - only used by Android 87 | - COLOR_BACKGROUND: Used to style the UI - only used by Android 88 | 89 | ## Firebase configuration 90 | ### Android 91 | You must ensure that `google-services.json` is put in the correct location. This can be achieved using the following in your `config.xml`: 92 | 93 | ``` 94 | 95 | 96 | 97 | ``` 98 | 99 | #### MainActivity 100 | In order for FirebaseUI to work on Android the default Cordova MainActivity needs to be replaced with a class that inherits from a FragmentActivity. 101 | 102 | This plugin therefore depends on the `cordova-plugin-android-fragmentactivity` plugin to enable this. 103 | 104 | ### iOS 105 | iOS requires `GoogleService-Info.plist` is put in the correct location. Similarly this can be done as follws: 106 | ``` 107 | 108 | 109 | 110 | ``` 111 | 112 | #### Keychain Sharing Capability 113 | If using multiple Firebase plugins it may be necessary to enable this. 114 | 115 | ## Dependencies 116 | ### Promises 117 | This plugin uses Promises. If you want to use this with Android 4.4 then you will need to include a Promise polyfill. 118 | 119 | # Getting started 120 | This guide will assume familiarity with Firebase and FirebaseUI. 121 | 122 | Create a new FirebaseAuthUI instance: 123 | 124 | ``` 125 | FirebaseUIAuth.initialise({ 126 | "providers": ["GOOGLE", "FACEBOOK", "EMAIL"], 127 | "tosUrl" : "http://www.myapp.co.uk/terms.html", 128 | "privacyPolicyUrl" : "http://www.myapp.co.uk/privacy.html", 129 | "theme" : "themeName", 130 | "logo" : "logoName", 131 | "uiElement" : "mywebelement", 132 | "anonymous" : true|false, 133 | "smartLockEnabled" : true|false, 134 | "smartLockHints" : true|false, 135 | "iOSDisable" : true | false 136 | }).then(function(firebaseUIAuth) { 137 | myfirebaseUIAuthInstance = firebaseUIAuth; 138 | }); 139 | ``` 140 | 141 | This is initialised as a Promise to allow the Browser implementation to dynamically add a reference to the FirestoreUI Javascript SDK. 142 | 143 | Not all of the above options will function on all platforms: 144 | 145 | - providers: a list of authentication providers to use 146 | - tosUrl: a terms of services URL when signing up via email 147 | - privacyPolicyUrl: a privacy policy URL - Android only 148 | - theme: a theme identifier for styling - Android only 149 | - logo: a logo to display - Android only 150 | - uiElement: a jQuery selector for web login - Web only 151 | - anonymous : if true log in an anonymous user if other attempts fail (default false) 152 | - smartLockEnabled : enable SmartLock to store credentials - Android only (default true) 153 | - smartLockHints : enable SmartLock hints - Android only (default false) 154 | - iOSDisable : Turns off Google and Facebook providers on iOS 10 and earlier as there seems to be an issue on older iOS versions 155 | 156 | ## Browser configuration 157 | In order for the above initialisation to work on a browser you need to include some extra configuration in the form of the `browser` section show below: 158 | 159 | ``` 160 | FirebaseUIAuth.initialise({ 161 | "providers": ["GOOGLE", "FACEBOOK", "EMAIL", "ANONYMOUS"], 162 | "tosUrl" : "http://www.myapp.co.uk/terms.html", 163 | "privacyPolicyUrl" : "http://www.myapp.co.uk/privacy.html", 164 | "theme" : "themeName", 165 | "logo" : "logoName", 166 | "uiElement" : "mywebelement", 167 | "anonymous" : true|false, 168 | "smartLockEnabled" : true|false, 169 | "smartLockHints" : true|false, 170 | "browser" : { 171 | apiKey: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', 172 | authDomain: 'xxxxxxxxxxxxxx.firebaseapp.com', 173 | projectId: 'xxxxxxxxxxxxx', 174 | } 175 | }).then(function(firebaseUIAuth) { 176 | myfirebaseUIAuthInstance = firebaseUIAuth; 177 | }); 178 | ``` 179 | 180 | # Methods 181 | ## signInAnonymously() 182 | Call this to sign in anonymously. 183 | 184 | ## signIn() 185 | Call this to start the sign in process based on the above configuration. This can raise the following events: 186 | 187 | ### signinsuccess 188 | The user has signed in successfully. The following data is returned: 189 | 190 | ``` 191 | { 192 | name: 'user display name', 193 | email: 'user email', 194 | emailVerified: true | false, 195 | photoUrl: 'url of user image if available', 196 | id: , 197 | newUser: true | false 198 | } 199 | ``` 200 | 201 | ### signinfailure 202 | Sign in failed for some reason. The following is returned: 203 | 204 | ``` 205 | { 206 | code: , 207 | message: 'failure message' 208 | } 209 | ``` 210 | 211 | ## signinaborted 212 | Sign in has been aborted by the user, by closing the sign in window. 213 | 214 | ## signOut() 215 | Sign the current user out of the application. This can raise the following events: 216 | 217 | ### signoutsuccess 218 | The user has signed out successfully. 219 | 220 | ### signoutfailure 221 | Sign out failed for some reason. 222 | 223 | ## getToken() 224 | Get an access token, returning a Promise. 225 | 226 | ## getCurrentUser() 227 | Get the currently signed in user. 228 | 229 | ## deleteUser() 230 | Delete the current user. This can raise the following events: 231 | 232 | ### deleteusersuccess 233 | The user was deleted successfully. 234 | 235 | ### deleteuserfailure 236 | The user was not deleted. 237 | 238 | ## sendEmailVerification() 239 | Sends a verification email for the current user. This can raise the following events: 240 | 241 | ### emailverificationsent 242 | The email verification was sent. 243 | 244 | ### emailverificationnotsent 245 | The email verification was not sent. 246 | 247 | ## reloadUser 248 | Reloads user details. Useful after a verification link has been used. A signinsuccess event will be raised. 249 | 250 | # What platform configuration is carried out? 251 | For iOS and Android a number of platform files are added or updated based on the supplied configuration. 252 | 253 | ## Android 254 | 255 | `res/values/strings.xml` 256 | This has the following added: 257 | 258 | - facebook_application_id 259 | - facebook_login_protocol_scheme 260 | 261 | `res/values/color.xml` 262 | This is either created or updated with the colour definitions supplied. 263 | 264 | `res/values/styles.xml` 265 | This is either created or updated with a style that uses the above colour definitions. 266 | 267 | ## iOS 268 | 269 | `*-Info.plist` 270 | 271 | The following keys are added: 272 | 273 | ``` 274 | CFBundleURLTypes 275 | 276 | 277 | CFBundleTypeRole 278 | Editor 279 | CFBundleURLName 280 | REVERSED_CLIENT_ID 281 | CFBundleURLSchemes 282 | 283 | $REVERSED_CLIENT_ID 284 | 285 | CFBundleTypeRole 286 | Editor 287 | CFBundleURLName 288 | 289 | CFBundleURLSchemes 290 | 291 | fb$FACEBOOK_APPLICATION_ID 292 | 293 | 294 | 295 | FacebookAppID 296 | $FACEBOOK_APPLICATION_ID 297 | FacebookDisplayName 298 | $FACEBOOK_DISPLAY_NAME 299 | LSApplicationQueriesSchemes 300 | 301 | fbapi 302 | fb-messenger-api 303 | fbauth2 304 | fbshareextensions 305 | 306 | ``` 307 | 308 | # Browser security 309 | In order to ensure the browser implementation works, it will be necessary to configure the Content-Security-Policy meta tag with something similar to the following: 310 | 311 | ``` 312 | 324 | ``` 325 | ## Typescript 326 | Support is now included for typescript. Use the following to reference the typescript definitions: 327 | 328 | ``` 329 | /// 330 | 331 | FirebaseUIAuth.initialise(options) 332 | .then((firebaseUIAuth: FirebaseUIAuth.FirebaseUIAuth) => { 333 | firebaseUIAuth.signIn(); 334 | }); 335 | ``` 336 | 337 | You may also need to add an external to webpack.config.ls: 338 | 339 | ``` 340 | externals: { 341 | 'cordova/exec': "cordova/exec" 342 | }, 343 | ``` 344 | 345 | # History 346 | ## 3.0.0 347 | - Add support for Apple sign in 348 | - Update Android dependencies 349 | - Update web dependencies 350 | 351 | ## 2.0.0 352 | - Remove firebase core and update dependencies 353 | - Refine types 354 | 355 | ## 1.5.0 356 | - Add types 357 | 358 | ## 1.4.0 359 | - Update Facebook dependency version for Android 360 | 361 | ## 1.3.0 362 | - Disable Google auth for earlier than iOS 11 - seems to be an issue with FirebaseUI 363 | 364 | ## 1.2.0 365 | - Add getCurrentUser() 366 | - Fix callback bug on iOS if login failed 367 | 368 | ## 1.1.0 369 | - Update Firebase dependencies 370 | - Fix podspec for cordova-ios 5 371 | 372 | ## 1.0.2 373 | - Major Android dependency update to 4.2.1 374 | - Breaking change around meaning of 'anonymous' configuration option 375 | - Add support for ANONYMOUS provider (on Android) 376 | - Attempted to handle merging of anonymous users 377 | - Allowed iOS pods to use latest 378 | - Android logo disabled due to possible bug in FirebaseUI 379 | 380 | ## 0.0.10 381 | - Update JS Firebase dependencies 382 | 383 | ## 0.0.9 384 | - Added missing documentation for deleteUser() method 385 | - Added sendEmailVerification() method 386 | - Added reloadUser() method 387 | - Added property newUser to user details. Only true when user us first created. 388 | 389 | ## 0.0.8 390 | - Update Android dependency versions 391 | - Update iOS dependency versions 392 | - Update plugin dependencies 393 | - WARNING: The Android update may require you to update com.google.gms:google-services to 4.0.0, com.android.tools.build:gradle to 3.1.2 and gradle to 4.4.4 (look in platforms/android/cordova/lib/builders/GradleBuilder.js) 394 | 395 | ## 0.0.7 396 | - Fix stupid cordova-android 7 detection 397 | 398 | ## 0.0.6 399 | - Improve logging 400 | 401 | ## 0.0.5 402 | - Change logo to be drawable rather than mipmap for Android 403 | - Remove leaked (and now deleted) client id 404 | 405 | ## 0.0.4 406 | - Experimental support for cordova-android 7 407 | - Increased dependency versions 408 | 409 | ## 0.0.3 410 | - Remove Java 7 dependency 411 | 412 | ## 0.0.2 413 | - Update README 414 | - Add grunt to run jshint 415 | - Fix some grunt warnings 416 | 417 | ## 0.0.1 418 | - Initial release 419 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "cordova-plugin-firebaseui-auth", 3 | "version": "3.0.0", 4 | "description": "Adds support for Firebase UI authentication.", 5 | "types": "./types/index.d.ts", 6 | "repository": { 7 | "type": "git", 8 | "url": "https://github.com/ReallySmallSoftware/cordova-plugin-firebaseui-auth-multi.git" 9 | }, 10 | "engines": { 11 | "cordovaDependencies": { 12 | "0.0.7": { 13 | "cordova": ">=7.0.0", 14 | "cordova-android": ">=5.0.0", 15 | "cordova-ios": ">=4.0.0" 16 | } 17 | } 18 | }, 19 | "keywords": [ 20 | "ecosystem:cordova", 21 | "cordova-android", 22 | "cordova-ios", 23 | "cordova-browser", 24 | "firebase", 25 | "authentication", 26 | "auth" 27 | ], 28 | "author": "Richard Windley", 29 | "license": "MIT", 30 | "bugs": { 31 | "url": "https://github.com/ReallySmallSoftware/cordova-plugin-firebaseui-auth/issues" 32 | }, 33 | "homepage": "https://github.com/ReallySmallSoftware/cordova-plugin-firebaseui-auth", 34 | "dependencies": {}, 35 | "devDependencies": { 36 | "grunt": "^1.0.2", 37 | "grunt-contrib-jshint": "^1.1.0", 38 | "jshint-junit-reporter": "^0.2.3", 39 | "libxmljs": "^0.18.4" 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /plugin.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | Firebase UI Authentication 4 | Adds support for Firebase Authentication to your Cordova/PhoneGap apps. 5 | Apache 2.0 6 | firebase,cordova,authentication 7 | Richard Windley 8 | https://github.com/ReallySmallSoftware/cordova-plugin-firebaseui-auth.git 9 | https://github.com/ReallySmallSoftware/cordova-plugin-firebaseui-auth/issues 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | CFBundleTypeRole 46 | Editor 47 | CFBundleURLName 48 | REVERSED_CLIENT_ID 49 | CFBundleURLSchemes 50 | 51 | $REVERSED_CLIENT_ID 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | Default 60 | 61 | 62 | 63 | 64 | Default 65 | 66 | 67 | 68 | 69 | 70 | 71 | CFBundleTypeRole 72 | Editor 73 | CFBundleURLName 74 | 75 | CFBundleURLSchemes 76 | 77 | fb$FACEBOOK_APPLICATION_ID 78 | 79 | 80 | 81 | 82 | 83 | 84 | $FACEBOOK_APPLICATION_ID 85 | 86 | 87 | 88 | $FACEBOOK_DISPLAY_NAME 89 | 90 | 91 | 92 | 93 | fbapi 94 | fb-messenger-api 95 | fbauth2 96 | fbshareextensions 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | 122 | 123 | 124 | 125 | 126 | 127 | 128 | 129 | 130 | 131 | 132 | 133 | 134 | 135 | 136 | 137 | 138 | 139 | 140 | 141 | 142 | 143 | 144 | 145 | 146 | 147 | 148 | 149 | 150 | 151 | $FACEBOOK_APPLICATION_ID 152 | fb$FACEBOOK_APPLICATION_ID 153 | 154 | 155 | 156 | $COLOR_PRIMARY 157 | $COLOR_DARK_PRIMARY 158 | $COLOR_LIGHT_PRIMARY 159 | $COLOR_ACCENT 160 | $COLOR_SECONDARY 161 | $COLOR_CONTROL 162 | $COLOR_BACKGROUND 163 | 164 | 165 | 166 | 184 | 185 | 191 | 192 | 195 | 196 | 202 | 203 | 204 | 205 | $FACEBOOK_APPLICATION_ID 206 | fb$FACEBOOK_APPLICATION_ID 207 | 208 | 209 | 210 | $COLOR_PRIMARY 211 | $COLOR_DARK_PRIMARY 212 | $COLOR_LIGHT_PRIMARY 213 | $COLOR_ACCENT 214 | $COLOR_SECONDARY 215 | $COLOR_CONTROL 216 | $COLOR_BACKGROUND 217 | 218 | 219 | 220 | 238 | 239 | 245 | 246 | 249 | 250 | 256 | 257 | 258 | 259 | -------------------------------------------------------------------------------- /scripts/android/beforePluginInstall.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | 3 | 'use strict'; 4 | 5 | const fs = require('fs'); 6 | const _ = require('lodash'); 7 | const utilities = require("../lib/utilities"); 8 | 9 | module.exports = function(context) { 10 | 11 | var androidResPath = utilities.getAndroidResPath(context); 12 | 13 | if (androidResPath !== null) { 14 | 15 | const stylesPath = androidResPath + '/res/values/styles.xml'; 16 | const colorPath = androidResPath + '/res/values/color.xml'; 17 | 18 | function fileExistsWithContent(filename) { 19 | if (!fs.existsSync(filename)) { 20 | console.log(filename + " does not exist."); 21 | return false; 22 | } 23 | const stats = fs.statSync(filename); 24 | const fileSizeInBytes = stats.size; 25 | 26 | if (fileSizeInBytes == 0) { 27 | console.log(filename + " is empty."); 28 | } 29 | 30 | return true; 31 | } 32 | 33 | if (!fileExistsWithContent(stylesPath)) { 34 | fs.writeFileSync(stylesPath, ""); 35 | console.log("Added styles definition."); 36 | } 37 | 38 | if (!fileExistsWithContent(colorPath)) { 39 | fs.writeFileSync(colorPath, ""); 40 | console.log("Added colours."); 41 | } 42 | } 43 | }; 44 | -------------------------------------------------------------------------------- /scripts/lib/utilities.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | 3 | 'use strict'; 4 | 5 | const fs = require('fs'); 6 | 7 | module.exports = { 8 | 9 | getAndroidResPath: function(context) { 10 | 11 | var platforms = context.opts.cordova.platforms; 12 | 13 | if (platforms.indexOf("android") === -1) { 14 | return null; 15 | } 16 | 17 | var androidPath = context.opts.projectRoot + '/platforms/android/app/src/main'; 18 | 19 | if (!fs.existsSync(androidPath)) { 20 | androidPath = context.opts.projectRoot + '/platforms/android'; 21 | 22 | if (!fs.existsSync(androidPath)) { 23 | console.log("Unable to detect type of cordova-android application structure"); 24 | throw new Error("Unable to detect type of cordova-android application structure"); 25 | } else { 26 | console.log("Detected pre cordova-android 7 application structure"); 27 | } 28 | } else { 29 | console.log("Detected cordova-android 7 application structure"); 30 | } 31 | 32 | return androidPath; 33 | }, 34 | 35 | getAndroidManifestPath: function(context) { 36 | return this.getAndroidResPath(context); 37 | }, 38 | 39 | getAndroidSourcePath: function(context) { 40 | var platforms = context.opts.cordova.platforms; 41 | 42 | if (platforms.indexOf("android") === -1) { 43 | return null; 44 | } 45 | 46 | var androidPath = context.opts.projectRoot + '/platforms/android/app/src/main/java'; 47 | 48 | if (!fs.existsSync(androidPath)) { 49 | androidPath = context.opts.projectRoot + '/platforms/android/src'; 50 | 51 | if (!fs.existsSync(androidPath)) { 52 | console.log("Unable to detect type of cordova-android application structure"); 53 | throw new Error("Unable to detect type of cordova-android application structure"); 54 | } else { 55 | console.log("Detected pre cordova-android 7 application structure"); 56 | } 57 | } else { 58 | console.log("Detected cordova-android 7 application structure"); 59 | } 60 | 61 | return androidPath; 62 | } 63 | }; 64 | -------------------------------------------------------------------------------- /src/android/.gitignore: -------------------------------------------------------------------------------- 1 | !*.jar -------------------------------------------------------------------------------- /src/android/uk/co/reallysmall/cordova/plugin/firebase/ui/auth/FirebaseUIAuthPlugin.java: -------------------------------------------------------------------------------- 1 | package uk.co.reallysmall.cordova.plugin.firebase.ui.auth; 2 | 3 | import android.content.Intent; 4 | import androidx.annotation.NonNull; 5 | import androidx.fragment.app.FragmentActivity; 6 | import android.util.Log; 7 | 8 | import com.firebase.ui.auth.AuthUI; 9 | import com.firebase.ui.auth.ErrorCodes; 10 | import com.firebase.ui.auth.IdpResponse; 11 | import com.google.android.gms.tasks.OnCompleteListener; 12 | import com.google.android.gms.tasks.OnFailureListener; 13 | import com.google.android.gms.tasks.OnSuccessListener; 14 | import com.google.android.gms.tasks.Task; 15 | import com.google.firebase.auth.AuthCredential; 16 | import com.google.firebase.auth.AuthResult; 17 | import com.google.firebase.auth.FirebaseAuth; 18 | import com.google.firebase.auth.FirebaseUser; 19 | import com.google.firebase.auth.GetTokenResult; 20 | 21 | import org.apache.cordova.CallbackContext; 22 | import org.apache.cordova.CordovaPlugin; 23 | import org.apache.cordova.PluginResult; 24 | import org.json.JSONArray; 25 | import org.json.JSONException; 26 | import org.json.JSONObject; 27 | 28 | import java.util.ArrayList; 29 | import java.util.Arrays; 30 | import java.util.List; 31 | 32 | import static android.app.Activity.RESULT_OK; 33 | 34 | public class FirebaseUIAuthPlugin extends CordovaPlugin implements OnCompleteListener { 35 | private static final int RC_SIGN_IN = 123; 36 | private final String TAG = "FirebaseUIAuthPlugin"; 37 | List providers = Arrays.asList( 38 | new AuthUI.IdpConfig.EmailBuilder().build()); 39 | private CallbackContext callbackContext; 40 | private FirebaseAuth firebaseAuth; 41 | private JSONObject options; 42 | private boolean anonymous; 43 | 44 | @Override 45 | protected void pluginInitialize() { 46 | } 47 | 48 | @Override 49 | public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException { 50 | 51 | Log.d(TAG, "action : " + action); 52 | 53 | if ("initialise".equals(action)) { 54 | return initialise(args, callbackContext); 55 | } else if ("signIn".equals(action)) { 56 | return signIn(callbackContext); 57 | } else if ("signInAnonymously".equals(action)) { 58 | return signInAnonymously(callbackContext); 59 | } else if ("signOut".equals(action)) { 60 | return signOut(callbackContext); 61 | } else if ("deleteUser".equals(action)) { 62 | return deleteUser(callbackContext); 63 | } else if ("getToken".equals(action)) { 64 | return getToken(callbackContext); 65 | } else if ("getCurrentUser".equals(action)) { 66 | return getCurrentUser(callbackContext); 67 | } else if ("sendEmailVerification".equals(action)) { 68 | return sendEmailVerification(callbackContext); 69 | } else if ("reloadUser".equals(action)) { 70 | return reloadUser(callbackContext); 71 | } else { 72 | Log.w(TAG, "Unknown action : " + action); 73 | return false; 74 | } 75 | } 76 | 77 | private boolean reloadUser(CallbackContext callbackContext) { 78 | FirebaseUser user = firebaseAuth.getCurrentUser(); 79 | 80 | if (user != null) { 81 | user.reload().addOnSuccessListener(new OnSuccessListener() { 82 | 83 | @Override 84 | public void onSuccess(Void aVoid) { 85 | FirebaseUser user = firebaseAuth.getCurrentUser(); 86 | raiseEventForUser(user); 87 | } 88 | }); 89 | } 90 | 91 | return true; 92 | } 93 | 94 | private boolean signInAnonymously(CallbackContext callbackContext) { 95 | 96 | signInAnonymous(firebaseAuth); 97 | 98 | return true; 99 | } 100 | 101 | private boolean sendEmailVerification(final CallbackContext callbackContext) { 102 | 103 | FirebaseUser user = firebaseAuth.getCurrentUser(); 104 | 105 | if (user != null && !anonymous) { 106 | 107 | user.sendEmailVerification().addOnCompleteListener(new OnCompleteListener() { 108 | @Override 109 | public void onComplete(@NonNull Task task) { 110 | if (task.isSuccessful()) { 111 | raiseEvent(callbackContext, "emailverificationsent", null); 112 | } else { 113 | raiseEvent(callbackContext, "emailverificationnotsent", null); 114 | } 115 | } 116 | }); 117 | } 118 | 119 | return true; 120 | } 121 | 122 | private boolean initialise(JSONArray args, final CallbackContext callbackContext) { 123 | 124 | Log.d(TAG, "initialise"); 125 | 126 | options = new JSONObject(); 127 | 128 | anonymous = false; 129 | 130 | try { 131 | options = args.getJSONObject(0); 132 | createProviderList(); 133 | if (options.has("anonymous") && options.getBoolean("anonymous")) { 134 | anonymous = true; 135 | } 136 | } catch (JSONException ex) { 137 | Log.e(TAG, "initialise: error getting options: " + ex.getMessage()); 138 | } 139 | 140 | this.callbackContext = callbackContext; 141 | 142 | firebaseAuth = FirebaseAuth.getInstance(); 143 | 144 | return true; 145 | } 146 | 147 | private void signInAnonymous(final FirebaseAuth firebaseAuth) { 148 | 149 | FirebaseUser user = firebaseAuth.getCurrentUser(); 150 | 151 | if (user == null && anonymous) { 152 | firebaseAuth.signInAnonymously().addOnCompleteListener(new OnCompleteListener() { 153 | @Override 154 | public void onComplete(@NonNull Task task) { 155 | if (task.isSuccessful()) { 156 | Log.d(TAG, "signInAnonymously:success"); 157 | FirebaseUser user = firebaseAuth.getCurrentUser(); 158 | raiseEventForUser(user); 159 | } else { 160 | Log.w(TAG, "signInAnonymously:failure", task.getException()); 161 | raiseErrorEvent("signinfailure", 1, "Anonymous sign in failed"); 162 | } 163 | } 164 | }); 165 | } 166 | } 167 | 168 | private void createProviderList() throws JSONException { 169 | 170 | if (options.has("providers")) { 171 | 172 | Log.d(TAG, "createProviderList: parsing providers"); 173 | 174 | providers = new ArrayList(); 175 | 176 | JSONArray providerList = options.getJSONArray("providers"); 177 | 178 | int length = providerList.length(); 179 | 180 | for (int i = 0; i < length; i++) { 181 | Log.d(TAG, "createProviderList: parsing provider " + providerList.getString(i)); 182 | 183 | if ("EMAIL".equals(providerList.getString(i))) { 184 | providers.add(new AuthUI.IdpConfig.EmailBuilder().build()); 185 | } 186 | if ("FACEBOOK".equals(providerList.getString(i))) { 187 | providers.add(new AuthUI.IdpConfig.FacebookBuilder().build()); 188 | } 189 | if ("GOOGLE".equals(providerList.getString(i))) { 190 | providers.add(new AuthUI.IdpConfig.GoogleBuilder().build()); 191 | } 192 | if ("PHONE".equals(providerList.getString(i))) { 193 | providers.add(new AuthUI.IdpConfig.PhoneBuilder().build()); 194 | } 195 | if ("TWITTER".equals(providerList.getString(i))) { 196 | providers.add(new AuthUI.IdpConfig.TwitterBuilder().build()); 197 | } 198 | if ("GITHUB".equals(providerList.getString(i))) { 199 | providers.add(new AuthUI.IdpConfig.GitHubBuilder().build()); 200 | } 201 | if ("ANONYMOUS".equals(providerList.getString(i))) { 202 | providers.add(new AuthUI.IdpConfig.AnonymousBuilder().build()); 203 | } 204 | if ("apple.com".equals(providerList.getString(i))) { 205 | providers.add(new AuthUI.IdpConfig.AppleBuilder().build()); 206 | } 207 | } 208 | } 209 | } 210 | 211 | private boolean signIn(CallbackContext callbackContext) { 212 | 213 | Log.d(TAG, "signIn"); 214 | 215 | this.callbackContext = callbackContext; 216 | 217 | FirebaseUser user = firebaseAuth.getCurrentUser(); 218 | 219 | if (user != null && !user.isAnonymous()) { 220 | Log.d(TAG, "signIn: already have user"); 221 | raiseEventForUser(user); 222 | } else { 223 | Log.d(TAG, "signIn: sign in"); 224 | 225 | cordova.setActivityResultCallback(this); 226 | 227 | cordova.getActivity().startActivityForResult( 228 | this.buildCustomInstance() 229 | .enableAnonymousUsersAutoUpgrade() 230 | .setAvailableProviders(providers) 231 | .build(), 232 | RC_SIGN_IN); 233 | } 234 | 235 | return true; 236 | } 237 | 238 | private AuthUI.SignInIntentBuilder buildCustomInstance() { 239 | AuthUI.SignInIntentBuilder instance = AuthUI.getInstance().createSignInIntentBuilder(); 240 | 241 | Log.d(TAG, "buildCustomInstance"); 242 | 243 | boolean smartLockEnabled = false; 244 | boolean smartLockHints = false; 245 | 246 | try { 247 | if (options.has("logo")) { 248 | int id = getIdentifier(options.getString("logo"), "drawable"); 249 | // instance = instance.setLogo(id); 250 | } 251 | if (options.has("theme")) { 252 | int id = getIdentifier(options.getString("theme"), "style"); 253 | instance = instance.setTheme(id); 254 | } else { 255 | int id = getIdentifier("FirebaseUILogonTheme", "style"); 256 | instance = instance.setTheme(id); 257 | } 258 | if (options.has("tosUrl") && options.has("privacyPolicyUrl")) { 259 | instance = instance.setTosAndPrivacyPolicyUrls(options.getString("tosUrl"),options.getString("privacyPolicyUrl")); 260 | } else { 261 | if (options.has("tosUrl")) { 262 | instance = instance.setTosUrl(options.getString("tosUrl")); 263 | } 264 | if (options.has("privacyPolicyUrl")) { 265 | instance = instance.setPrivacyPolicyUrl(options.getString("privacyPolicyUrl")); 266 | } 267 | } 268 | if (options.has("smartLockEnabled")) { 269 | smartLockEnabled = options.getBoolean("smartLockEnabled"); 270 | } 271 | if (options.has("smartLockHints")) { 272 | smartLockHints = options.getBoolean("smartLockHints"); 273 | } 274 | instance = instance.setIsSmartLockEnabled(smartLockEnabled, smartLockHints); 275 | } catch (JSONException ex) { 276 | Log.e(TAG, "Error in buildCustomInstance ", ex); 277 | } 278 | 279 | return instance; 280 | } 281 | 282 | private int getIdentifier(String name, String type) { 283 | return cordova.getActivity().getApplicationContext().getResources().getIdentifier(name, 284 | type, 285 | cordova.getActivity().getApplicationContext().getPackageName()); 286 | } 287 | 288 | @Override 289 | public void onActivityResult(int requestCode, int resultCode, Intent data) { 290 | super.onActivityResult(requestCode, resultCode, data); 291 | 292 | Log.d(TAG, "onActivityResult"); 293 | Log.d(TAG, "onActivityResult:requestCode:" + requestCode); 294 | 295 | if (requestCode == RC_SIGN_IN) { 296 | Log.d(TAG, "onActivityResult:resultCode:" + resultCode); 297 | 298 | IdpResponse response = IdpResponse.fromResultIntent(data); 299 | 300 | if (resultCode == RESULT_OK) { 301 | 302 | FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser(); 303 | raiseEventForUser(user); 304 | } else { 305 | if (response == null) { 306 | signInAnonymous(firebaseAuth); 307 | raiseEvent(callbackContext, "signinaborted", null); 308 | return; 309 | } 310 | 311 | if (response.getError().getErrorCode() == ErrorCodes.ANONYMOUS_UPGRADE_MERGE_CONFLICT) { 312 | handleAnonymousUpgradeMergeConflict(response); 313 | } else { 314 | 315 | if (response.getError().getErrorCode() == ErrorCodes.NO_NETWORK) { 316 | raiseErrorEvent("signinfailure", response.getError().getErrorCode(), "No network so unable to sign in."); 317 | 318 | return; 319 | } 320 | 321 | Log.e(TAG, "Sign-in error: ", response.getError()); 322 | raiseErrorEvent("signinfailure", response.getError().getErrorCode(), "There was a problem signing in."); 323 | } 324 | } 325 | } 326 | } 327 | 328 | private void handleAnonymousUpgradeMergeConflict(IdpResponse response) { 329 | AuthCredential nonAnonymousCredential = response.getCredentialForLinking(); 330 | 331 | FirebaseAuth.getInstance().signInWithCredential(nonAnonymousCredential) 332 | .addOnSuccessListener(new OnSuccessListener() { 333 | @Override 334 | public void onSuccess(AuthResult result) { 335 | FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser(); 336 | raiseEventForUser(user); 337 | } 338 | }); 339 | } 340 | 341 | private boolean signOut(CallbackContext callbackContext) { 342 | 343 | Log.d(TAG, "signOut"); 344 | 345 | AuthUI.getInstance().signOut(cordova.getActivity()).addOnCompleteListener(new OnCompleteListener() { 346 | @Override 347 | public void onComplete(@NonNull Task task) { 348 | if (task.isSuccessful()) { 349 | 350 | Log.d(TAG, "signOut: success"); 351 | 352 | raiseEvent(callbackContext, "signoutsuccess", null); 353 | signInAnonymous(firebaseAuth); 354 | } 355 | } 356 | }).addOnFailureListener(new OnFailureListener() { 357 | @Override 358 | public void onFailure(@NonNull Exception e) { 359 | Log.w(TAG, "signOut: failure", e); 360 | raiseErrorEvent("signoutfailure", 1, "There was a problem signing out."); 361 | } 362 | }); 363 | 364 | return true; 365 | } 366 | 367 | private boolean deleteUser(final CallbackContext callbackContext) { 368 | 369 | Log.d(TAG, "deleteUser"); 370 | 371 | FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser(); 372 | 373 | final FirebaseUIAuthPlugin plugin = this; 374 | 375 | if (user != null) { 376 | user.delete().addOnCompleteListener(new OnCompleteListener() { 377 | @Override 378 | public void onComplete(@NonNull Task task) { 379 | if (task.isSuccessful()) { 380 | 381 | Log.d(TAG, "deleteUser: success"); 382 | 383 | AuthUI.getInstance().delete( cordova.getActivity()); 384 | raiseEvent(callbackContext, "deleteusersuccess", null); 385 | 386 | plugin.signInAnonymous(firebaseAuth); 387 | } 388 | } 389 | }).addOnFailureListener(new OnFailureListener() { 390 | @Override 391 | public void onFailure(@NonNull Exception e) { 392 | Log.w(TAG, "deleteUser: failure", e); 393 | raiseErrorEvent("deleteuserfailure", 1, "This operation requires you to have recently authenticated. Please log out and back in and try again."); 394 | } 395 | }); 396 | } 397 | 398 | return true; 399 | } 400 | 401 | 402 | private boolean getToken(final CallbackContext callbackContext) { 403 | 404 | Log.d(TAG, "getToken"); 405 | 406 | FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser(); 407 | 408 | if (user != null) { 409 | user.getIdToken(false).addOnCompleteListener(new OnCompleteListener() { 410 | @Override 411 | public void onComplete(@NonNull Task task) { 412 | 413 | callbackContext.success(task.getResult().getToken()); 414 | } 415 | }); 416 | } else { 417 | callbackContext.error("no_user_found"); 418 | } 419 | 420 | return true; 421 | } 422 | 423 | private boolean getCurrentUser(final CallbackContext callbackContext) { 424 | 425 | Log.d(TAG, "getToken"); 426 | 427 | FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser(); 428 | 429 | if (user != null) { 430 | callbackContext.success(this.formatUser(user)); 431 | } else { 432 | callbackContext.success(this.formatEmptyUser()); 433 | } 434 | 435 | return true; 436 | } 437 | 438 | private void raiseErrorEvent(String event, int code, String message) { 439 | JSONObject data = new JSONObject(); 440 | try { 441 | data.put("code", code); 442 | data.put("message", message); 443 | } catch (JSONException e) { 444 | Log.e(TAG, "Error in raiseErrorEvent ", e); 445 | } 446 | raiseEvent(callbackContext, event, data); 447 | } 448 | 449 | private void raiseEventForUser(FirebaseUser user) { 450 | final JSONObject resultData = new JSONObject(); 451 | 452 | Log.d(TAG, "raiseEventForUser"); 453 | 454 | raiseEvent(callbackContext, "signinsuccess", this.formatUser(user)); 455 | 456 | Log.d(TAG, "raiseEventForUser: raised"); 457 | } 458 | 459 | private JSONObject formatUser(FirebaseUser user) { 460 | final JSONObject resultData = new JSONObject(); 461 | 462 | Log.d(TAG, "formatUser"); 463 | 464 | try { 465 | 466 | anonymous = false; 467 | 468 | resultData.put("name", user.getDisplayName()); 469 | resultData.put("email", user.getEmail()); 470 | resultData.put("emailVerified", user.isEmailVerified()); 471 | resultData.put("id", user.getUid()); 472 | if (user.getMetadata().getCreationTimestamp() == user.getMetadata().getLastSignInTimestamp()) { 473 | resultData.put("newUser", true); 474 | } else { 475 | resultData.put("newUser", false); 476 | } 477 | if (user.getPhotoUrl() != null) { 478 | resultData.put("photoUrl", user.getPhotoUrl().toString()); 479 | } 480 | } catch (JSONException e) { 481 | Log.e(TAG, "Error in formatUser ", e); 482 | } 483 | 484 | return resultData; 485 | } 486 | 487 | private JSONObject formatEmptyUser() { 488 | final JSONObject resultData = new JSONObject(); 489 | 490 | Log.d(TAG, "formatEmptyUser"); 491 | 492 | try { 493 | 494 | resultData.put("name", null); 495 | resultData.put("email", null); 496 | resultData.put("emailVerified", false); 497 | resultData.put("id", null); 498 | resultData.put("newUser", false); 499 | 500 | } catch (JSONException e) { 501 | Log.e(TAG, "Error in formatEmptyUser ", e); 502 | } 503 | 504 | return resultData; 505 | } 506 | 507 | private void raiseEvent(CallbackContext callbackContext, String type, Object data) { 508 | 509 | Log.d(TAG, "raiseEvent: " + type); 510 | 511 | JSONObject event = new JSONObject(); 512 | try { 513 | event.put("type", type); 514 | if (data != null) { 515 | event.put("data", data); 516 | } 517 | } catch (JSONException e) { 518 | Log.e(TAG, "Error in raiseEvent ", e); 519 | } 520 | 521 | PluginResult result = new PluginResult(PluginResult.Status.OK, event); 522 | result.setKeepCallback(true); 523 | callbackContext.sendPluginResult(result); 524 | } 525 | 526 | @Override 527 | public void onComplete(@NonNull Task task) { 528 | Log.d(TAG, "onComplete"); 529 | 530 | if (!task.isSuccessful()) { 531 | Exception err = task.getException(); 532 | JSONObject data = new JSONObject(); 533 | try { 534 | data.put("code", err.getClass().getSimpleName()); 535 | data.put("message", err.getMessage()); 536 | } catch (JSONException e) { 537 | Log.e(TAG, "Error in onComplete ", e); 538 | } 539 | raiseEvent(callbackContext, "signinfailure", data); 540 | } 541 | } 542 | } 543 | -------------------------------------------------------------------------------- /src/ios/FirebaseUIAuthPlugin.h: -------------------------------------------------------------------------------- 1 | #import 2 | #import 3 | @import Firebase; 4 | @import FirebaseUI; 5 | 6 | @interface FirebaseUIAuthPlugin : CDVPlugin < FUIAuthDelegate > 7 | 8 | - (void)initialise:(CDVInvokedUrlCommand *)command; 9 | - (void)signIn:(CDVInvokedUrlCommand *)command; 10 | - (void)signInAnonymously:(CDVInvokedUrlCommand *)command; 11 | - (void)signOut:(CDVInvokedUrlCommand *)command; 12 | - (void)getToken:(CDVInvokedUrlCommand *)command; 13 | - (void)deleteUser:(CDVInvokedUrlCommand *)command; 14 | - (void)sendEmailVerification:(CDVInvokedUrlCommand *)command; 15 | - (void)reloadUser:(CDVInvokedUrlCommand *)command; 16 | - (void)getCurrentUser:(CDVInvokedUrlCommand *)command; 17 | 18 | @property(strong,nonatomic) FUIAuth *authUI; 19 | @property(strong,nonatomic) NSMutableArray> *providers; 20 | @property(strong,nonatomic) NSString *signInCallbackId; 21 | @property(nonatomic) Boolean anonymous; 22 | 23 | @end 24 | -------------------------------------------------------------------------------- /src/ios/FirebaseUIAuthPlugin.m: -------------------------------------------------------------------------------- 1 | #import "FirebaseUIAuthPlugin.h" 2 | @import Firebase; 3 | @import FirebaseUI; 4 | 5 | @implementation FirebaseUIAuthPlugin 6 | 7 | - (void)pluginInitialize { 8 | if(![FIRApp defaultApp]) { 9 | [FIRApp configure]; 10 | } 11 | 12 | self.authUI = [FUIAuth defaultAuthUI]; 13 | self.authUI.delegate = self; 14 | self.anonymous = false; 15 | } 16 | 17 | - (void)initialise:(CDVInvokedUrlCommand *)command { 18 | 19 | NSDictionary *options = [command argumentAtIndex:0 withDefault:@{} andClass:[NSDictionary class]]; 20 | 21 | @try { 22 | self.signInCallbackId = command.callbackId; 23 | 24 | [self createProviderList:options]; 25 | 26 | NSString *tosUrl = [options valueForKey:@"tosUrl"]; 27 | 28 | if (tosUrl != nil) { 29 | NSURL *url = [NSURL URLWithString:tosUrl]; 30 | [self.authUI setTOSURL:url]; 31 | } 32 | 33 | NSNumber *anonymous = [options valueForKey:@"anonymous"]; 34 | 35 | if ([anonymous isEqualToNumber:[NSNumber numberWithBool:YES]]) { 36 | self.anonymous = true; 37 | } 38 | } 39 | @catch (NSException *exception) { 40 | NSLog(@"Initialise error %@", [exception reason]); 41 | @throw exception; 42 | } 43 | } 44 | 45 | - (void)createProviderList:(NSDictionary *)options { 46 | 47 | self.providers = [[NSMutableArray> alloc] init]; 48 | 49 | NSArray *providers = [options valueForKey:@"providers"]; 50 | 51 | NSNumber *iOSDisable = [options valueForKey:@"iOSDisable"]; 52 | 53 | if (providers != nil) { 54 | 55 | for (NSString *provider in providers) { 56 | 57 | Boolean google = ![iOSDisable isEqualToNumber:[NSNumber numberWithBool:YES]]; 58 | 59 | if (@available(iOS 11.0, *)) { 60 | google = true; 61 | } 62 | 63 | if (google) { 64 | if ([provider isEqualToString:@"GOOGLE"]) { 65 | [self.providers addObject:[[FUIGoogleAuth alloc] init]]; 66 | } 67 | 68 | if ([provider isEqualToString:@"FACEBOOK"]) { 69 | [self.providers addObject:[[FUIFacebookAuth alloc] init]]; 70 | } 71 | } 72 | 73 | if (@available(iOS 13.0, *)) { 74 | if ([provider isEqualToString:@"apple.com"]) { 75 | [self.providers addObject:[FUIOAuth appleAuthProvider]]; 76 | } 77 | } 78 | 79 | if ([provider isEqualToString:@"EMAIL"]) { 80 | [self.providers addObject:[[FUIEmailAuth alloc] init]]; 81 | } 82 | } 83 | 84 | self.authUI.providers = self.providers; 85 | } 86 | } 87 | 88 | - (void)signInAnonymous { 89 | 90 | if (!self.anonymous) { 91 | return; 92 | } 93 | 94 | FIRUser *user = [[FIRAuth auth] currentUser]; 95 | 96 | if (user == nil) { 97 | 98 | [[FIRAuth auth] signInAnonymouslyWithCompletion:^(FIRAuthDataResult * _Nullable authResult, NSError * _Nullable error) { 99 | if ([authResult user] != nil) { 100 | [self raiseEventForUser:[authResult user]]; 101 | } else if (error != nil) { 102 | NSDictionary *data = nil; 103 | 104 | if (error.localizedFailureReason != nil && error.localizedDescription != nil) { 105 | data = @{ 106 | @"code" : [error localizedFailureReason], 107 | @"message" : [error localizedDescription] 108 | }; 109 | } else { 110 | 111 | data = @{ 112 | @"code" : @-1, 113 | @"message" : @"Unknown failure reason" 114 | }; 115 | } 116 | 117 | [self raiseEvent:@"signinfailure" withData:data]; 118 | } 119 | }]; 120 | } 121 | } 122 | 123 | - (void)getToken:(CDVInvokedUrlCommand *)command { 124 | 125 | @try { 126 | FIRUser *user = [[FIRAuth auth] currentUser]; 127 | 128 | if (user != nil) { 129 | [user getIDTokenWithCompletion:^(NSString * _Nullable token, NSError * _Nullable error) { 130 | if (error == nil) { 131 | CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:token]; 132 | 133 | [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; 134 | } 135 | }]; 136 | } else { 137 | CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"no_user_found"]; 138 | 139 | [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; 140 | } 141 | } 142 | @catch (NSException *exception) { 143 | NSLog(@"getToken error %@", [exception reason]); 144 | @throw exception; 145 | } 146 | } 147 | 148 | - (void)getCurrentUser:(CDVInvokedUrlCommand *)command { 149 | 150 | @try { 151 | FIRUser *user = [[FIRAuth auth] currentUser]; 152 | 153 | if (user != nil) { 154 | 155 | CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:[self formatUser:user]]; 156 | 157 | [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; 158 | 159 | } else { 160 | CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:[self formatEmptyUser]]; 161 | 162 | [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; 163 | } 164 | } 165 | @catch (NSException *exception) { 166 | NSLog(@"getCurrentUser error %@", [exception reason]); 167 | @throw exception; 168 | } 169 | } 170 | 171 | - (void)signIn:(CDVInvokedUrlCommand *)command { 172 | 173 | self.signInCallbackId = command.callbackId; 174 | 175 | @try { 176 | FIRUser *user = [[FIRAuth auth] currentUser]; 177 | 178 | if (user != nil && ![user isAnonymous]) { 179 | [self raiseEventForUser:user]; 180 | } else { 181 | UINavigationController *authViewController = [self.authUI authViewController]; 182 | [self.viewController presentViewController:authViewController animated:YES completion:nil]; 183 | } 184 | } 185 | @catch (NSException *exception) { 186 | NSLog(@"SignIn error %@", [exception reason]); 187 | @throw exception; 188 | } 189 | } 190 | 191 | - (void)authUI:(FUIAuth *)authUI didSignInWithAuthDataResult:(nullable FIRAuthDataResult *)authDataResult 192 | error:(nullable NSError *)error { 193 | 194 | NSDictionary *data = nil; 195 | 196 | if (error == nil) { 197 | [self raiseEventForUser:authDataResult.user]; 198 | } else { 199 | 200 | if (error.code == FUIAuthErrorCodeUserCancelledSignIn) { 201 | 202 | [self signInAnonymous]; 203 | [self raiseEvent:@"signinaborted" withData:data]; 204 | 205 | return; 206 | } 207 | 208 | if (error.code == FUIAuthErrorCodeMergeConflict) { 209 | FIRAuthCredential *authCredential = [error.userInfo valueForKey:FUIAuthCredentialKey]; 210 | 211 | if (authCredential != nil) { 212 | [[FIRAuth auth] signInWithCredential:authCredential completion:^(FIRAuthDataResult * _Nullable authResult, NSError * _Nullable error) { 213 | if ([authResult user] != nil) { 214 | [self raiseEventForUser:[authResult user]]; 215 | } else if (error != nil) { 216 | NSDictionary *data = nil; 217 | 218 | if (error.localizedFailureReason != nil && error.localizedDescription != nil) { 219 | data = @{ 220 | @"code" : [error localizedFailureReason], 221 | @"message" : [error localizedDescription] 222 | }; 223 | } else { 224 | 225 | data = @{ 226 | @"code" : @-1, 227 | @"message" : @"Unknown failure reason" 228 | }; 229 | } 230 | 231 | [self raiseEvent:@"signinfailure" withData:data]; 232 | } 233 | }]; 234 | 235 | } 236 | } else { 237 | if (error.localizedFailureReason != nil && error.localizedDescription != nil) { 238 | data = @{ 239 | @"code" : [error localizedFailureReason], 240 | @"message" : [error localizedDescription] 241 | }; 242 | } else { 243 | 244 | data = @{ 245 | @"code" : @1, 246 | @"message" : @"Unknown failure reason" 247 | }; 248 | } 249 | 250 | [self raiseEvent:@"signinfailure" withData:data]; 251 | } 252 | } 253 | } 254 | 255 | - (void)signInAnonymously:(CDVInvokedUrlCommand *)command { 256 | @try { 257 | [self signInAnonymous]; 258 | } 259 | @catch (NSException *exception) { 260 | NSLog(@"SignOut error %@", [exception reason]); 261 | @throw exception; 262 | } 263 | } 264 | 265 | - (BOOL)application:(UIApplication *)app 266 | openURL:(NSURL *)url 267 | options:(NSDictionary *)options { 268 | NSString *sourceApplication = options[UIApplicationOpenURLOptionsSourceApplicationKey]; 269 | return [self.authUI handleOpenURL:url sourceApplication:sourceApplication]; 270 | } 271 | 272 | - (void)signOut:(CDVInvokedUrlCommand *)command { 273 | 274 | @try { 275 | 276 | self.signInCallbackId = command.callbackId; 277 | 278 | if ([self.authUI signOutWithError:nil]) { 279 | [self raiseEvent:@"signoutsuccess" withData:nil]; 280 | [self signInAnonymous]; 281 | } else { 282 | [self raiseEvent:@"signoutfailure" withData:nil]; 283 | } 284 | } 285 | @catch (NSException *exception) { 286 | NSLog(@"SignOut error %@", [exception reason]); 287 | @throw exception; 288 | } 289 | } 290 | 291 | - (void)deleteUser:(CDVInvokedUrlCommand *)command { 292 | 293 | @try { 294 | 295 | self.signInCallbackId = command.callbackId; 296 | 297 | FIRUser *user = [[FIRAuth auth] currentUser]; 298 | 299 | [user deleteWithCompletion:^(NSError * _Nullable error) { 300 | if (error) { 301 | 302 | NSDictionary *data = @{ 303 | @"code" : @1, 304 | @"message" : @"This operation requires recent authentication. Please log out and back in and try again." 305 | }; 306 | 307 | [self raiseEvent:@"deleteuserfailure" withData:data]; 308 | } else { 309 | [self raiseEvent:@"deleteusersuccess" withData:nil]; 310 | [self signInAnonymous]; 311 | } 312 | }]; 313 | } 314 | @catch (NSException *exception) { 315 | NSLog(@"SignOut error %@", [exception reason]); 316 | @throw exception; 317 | } 318 | } 319 | 320 | - (void)sendEmailVerification:(CDVInvokedUrlCommand *)command { 321 | 322 | @try { 323 | 324 | self.signInCallbackId = command.callbackId; 325 | 326 | FIRUser *user = [[FIRAuth auth] currentUser]; 327 | 328 | [user sendEmailVerificationWithCompletion:^(NSError * _Nullable error) { 329 | if (error) { 330 | [self raiseEvent:@"emailverificationnotsent" withData:nil]; 331 | } else { 332 | [self raiseEvent:@"emailverificationsent" withData:nil]; 333 | [self signInAnonymous]; 334 | } 335 | }]; 336 | } 337 | @catch (NSException *exception) { 338 | NSLog(@"SignOut error %@", [exception reason]); 339 | @throw exception; 340 | } 341 | } 342 | 343 | - (void)reloadUser:(CDVInvokedUrlCommand *)command { 344 | 345 | @try { 346 | 347 | self.signInCallbackId = command.callbackId; 348 | 349 | FIRUser *user = [[FIRAuth auth] currentUser]; 350 | 351 | [user reloadWithCompletion:^(NSError * _Nullable error) { 352 | FIRUser *user = [[FIRAuth auth] currentUser]; 353 | 354 | [self raiseEventForUser:user]; 355 | }]; 356 | } 357 | @catch (NSException *exception) { 358 | NSLog(@"SignOut error %@", [exception reason]); 359 | @throw exception; 360 | } 361 | } 362 | 363 | - (void)raiseEventForUser:(FIRUser *)user { 364 | 365 | NSDictionary *result = [self formatUser:user]; 366 | 367 | [self raiseEvent:@"signinsuccess" withData:result]; 368 | } 369 | 370 | - (NSDictionary *)formatUser:(FIRUser *)user { 371 | 372 | NSDictionary *result; 373 | 374 | NSNumber *isEmailVerified; 375 | 376 | NSNumber *newUser; 377 | 378 | self.anonymous = [user isAnonymous]; 379 | 380 | if ([user isEmailVerified]) { 381 | isEmailVerified = @YES; 382 | } else { 383 | isEmailVerified = @NO; 384 | } 385 | 386 | FIRUserMetadata *metadata = [user metadata]; 387 | 388 | NSDate *lastSignInDate = [metadata lastSignInDate]; 389 | NSDate *creationDate = [metadata creationDate]; 390 | 391 | if (!self.anonymous && [lastSignInDate compare:creationDate] == NSOrderedSame) { 392 | newUser = @YES; 393 | } else { 394 | newUser = @NO; 395 | } 396 | 397 | if ([user photoURL] != nil) { 398 | result = @{@"email" : [self emptyIfNull:[user email]], 399 | @"emailVerified" : isEmailVerified, 400 | @"name" : [self emptyIfNull:[user displayName]], 401 | @"id" : [self emptyIfNull:[user uid]], 402 | @"photoUrl" : [[user photoURL] absoluteString], 403 | @"newUser" : newUser 404 | }; 405 | } else { 406 | result = @{@"email" : [self emptyIfNull:[user email]], 407 | @"emailVerified" : isEmailVerified, 408 | @"name" : [self emptyIfNull:[user displayName]], 409 | @"id" : [self emptyIfNull:[user uid]], 410 | @"newUser" : newUser 411 | }; 412 | } 413 | 414 | return result; 415 | } 416 | 417 | - (NSDictionary *)formatEmptyUser { 418 | 419 | NSDictionary *result; 420 | 421 | result = @{@"email" : (id)[NSNull null], 422 | @"emailVerified" : @NO, 423 | @"name" : (id)[NSNull null], 424 | @"id" : (id)[NSNull null], 425 | @"newUser" : @NO 426 | }; 427 | 428 | return result; 429 | } 430 | 431 | - (NSString *)emptyIfNull:(NSString *)value { 432 | if (value == nil) { 433 | return (id)[NSNull null]; 434 | } 435 | 436 | return value; 437 | } 438 | 439 | - (void)raiseEvent:(NSString *)type withData:(NSDictionary *)data { 440 | NSDictionary *result; 441 | 442 | if (data != nil) { 443 | result = @{ 444 | @"type" : type, 445 | @"data" : data 446 | }; 447 | } else { 448 | result = @{ 449 | @"type" : type 450 | }; 451 | } 452 | 453 | CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:result]; 454 | [pluginResult setKeepCallbackAsBool:YES]; 455 | 456 | [self.commandDelegate sendPluginResult:pluginResult callbackId:self.signInCallbackId]; 457 | } 458 | 459 | @end 460 | -------------------------------------------------------------------------------- /types/index.d.ts: -------------------------------------------------------------------------------- 1 | declare namespace FirebaseUIAuth { 2 | 3 | export interface FirebaseUIAuthUserDetail { 4 | name: string | null; 5 | email: string | null; 6 | emailVerified: boolean; 7 | id: string | null; 8 | photoUrl: string | null; 9 | newUser: boolean; 10 | } 11 | 12 | export interface FirebaseUIAuthUser { 13 | detail: FirebaseUIAuthUserDetail; 14 | } 15 | 16 | export type FirebaseUIAuthOptionsProviders = "EMAIL" | "FACEBOOK" | "GOOGLE" | "PHONE" | "TWITTER" | "GITHUB" | "ANONYMOUS" | "apple.com"; 17 | 18 | export interface FirebaseUIAuthOptions { 19 | anonymous?: boolean; 20 | providers?: FirebaseUIAuthOptionsProviders[]; 21 | logo?: string; 22 | theme?: string; 23 | tosUrl?: string; 24 | privacyPolicyUrl?: string; 25 | smartLockEnabled?: boolean; 26 | smartLockHints?: boolean; 27 | uiElement?: string; 28 | browser?: any; 29 | } 30 | 31 | export function initialise(options: FirebaseUIAuthOptions): Promise; 32 | export interface FirebaseUIAuth { 33 | 34 | getToken(): Promise; 35 | getCurrentUser(): Promise; 36 | signIn(): void; 37 | signInAnonymously(): void; 38 | signOut(): void; 39 | delete(): void; 40 | sendEmailVerification(): void; 41 | reloadUser(): void; 42 | } 43 | } -------------------------------------------------------------------------------- /www/browser/firebaseUIAuthPlugin.js: -------------------------------------------------------------------------------- 1 | /*global firebase, alert:false, firebaseui: false, Promise: false, CustomEvent: false */ 2 | /*jshint esversion: 6 */ 3 | const PLUGIN_NAME = 'FirebaseUIAuth'; 4 | 5 | var loadJS = function (url, loaded, implementationCode, location) { 6 | 7 | if (!loaded) { 8 | var scriptTag = document.createElement('script'); 9 | scriptTag.src = url; 10 | 11 | scriptTag.onload = implementationCode; 12 | scriptTag.onreadystatechange = implementationCode; 13 | 14 | location.appendChild(scriptTag); 15 | } else { 16 | implementationCode(); 17 | } 18 | }; 19 | 20 | var loadCSS = function (url, loaded, implementationCode, location) { 21 | if (!loaded) { 22 | var linkTag = document.createElement('link'); 23 | linkTag.href = url; 24 | linkTag.type = "text/css"; 25 | linkTag.rel = "stylesheet"; 26 | 27 | linkTag.onload = implementationCode; 28 | linkTag.onreadystatechange = implementationCode; 29 | 30 | location.appendChild(linkTag); 31 | } else { 32 | implementationCode(); 33 | } 34 | }; 35 | 36 | function FirebaseUIAuth(options, resolve) { 37 | 38 | var self = this; 39 | 40 | var initialise = function () { 41 | if (firebase.apps.length === 0) { 42 | firebase.initializeApp(options.browser); 43 | } 44 | 45 | firebase.auth().onAuthStateChanged(function (user) { 46 | self.signInSuccess(user); 47 | }); 48 | 49 | self.anonymous = options.anonymous ? true : false; 50 | 51 | var providers = self.buildProviders(options.providers); 52 | self.buildUIConfig(options, providers); 53 | 54 | self.uiElement = options.uiElement; 55 | 56 | resolve(self); 57 | }; 58 | 59 | var firebaseLoaded = "firebase" in window; 60 | var firebaseAuthLoaded = false; 61 | var firebaseUILoaded = false; 62 | if (firebaseLoaded) { 63 | firebaseAuthLoaded = "auth" in firebase; 64 | 65 | if (firebaseAuthLoaded) { 66 | firebaseUILoaded = "AuthUI" in firebase.auth; 67 | } 68 | } 69 | 70 | loadJS('https://www.gstatic.com/firebasejs/7.14.0/firebase-app.js', firebaseLoaded, function () { 71 | loadJS('https://www.gstatic.com/firebasejs/7.14.0/firebase-auth.js', firebaseAuthLoaded, function () { 72 | loadJS('https://www.gstatic.com/firebasejs/ui/4.5.0/firebase-ui-auth.js', firebaseUILoaded, function () { 73 | loadCSS('https://www.gstatic.com/firebasejs/ui/4.5.0/firebase-ui-auth.css', firebaseUILoaded, initialise, document.body); 74 | }, document.body); 75 | }, document.body); 76 | }, document.body); 77 | 78 | this.buildProviders = function (optionProviders) { 79 | 80 | var providers = []; 81 | var i; 82 | 83 | for (i = 0; i < optionProviders.length; i++) { 84 | if (optionProviders[i] === "GOOGLE") { 85 | providers.push(firebase.auth.GoogleAuthProvider.PROVIDER_ID); 86 | } else if (optionProviders[i] === "FACEBOOK") { 87 | providers.push(firebase.auth.FacebookAuthProvider.PROVIDER_ID); 88 | } else if (optionProviders[i] === "EMAIL") { 89 | providers.push(firebase.auth.EmailAuthProvider.PROVIDER_ID); 90 | } else if (optionProviders[i] === "apple.com") { 91 | providers.push("apple.com"); 92 | } 93 | } 94 | 95 | return providers; 96 | }; 97 | 98 | this.buildUIConfig = function (options, providers) { 99 | this.uiConfig = { 100 | callbacks: { 101 | uiShown: function () { } 102 | }, 103 | signInOptions: providers 104 | }; 105 | 106 | if (options.tosUrl !== undefined) { 107 | this.uiConfig.tosUrl = options.tosUrl; 108 | } 109 | }; 110 | 111 | this.signInAnonymously = function () { 112 | if (this.anonymous === true) { 113 | firebase.auth().signInAnonymously().catch(function (error) { 114 | alert(error.code + ":" + error.message); 115 | }); 116 | } 117 | }; 118 | 119 | this.signInSuccess = function (user) { 120 | 121 | if (user) { 122 | document.getElementById(this.uiElement).style.display = 'none'; 123 | this.raiseEventForUser(user); 124 | } else { 125 | var customEvent = new CustomEvent("signoutsuccess", {}); 126 | window.dispatchEvent(customEvent); 127 | } 128 | 129 | return false; 130 | }; 131 | 132 | this.reloadUser = function () { 133 | 134 | var self = this; 135 | 136 | firebase.auth().currentUser.reload().then(function () { 137 | self.raiseEventForUser(firebase.auth().currentUser); 138 | }); 139 | }; 140 | 141 | this.raiseEventForUser = function (user) { 142 | var customEvent = new CustomEvent("signinsuccess", this._formatUser(user)); 143 | window.dispatchEvent(customEvent); 144 | }; 145 | 146 | this._formatUser = function (user) { 147 | var newUser = false; 148 | 149 | if (user.metadata.creationTime === user.metadata.lastSignInTime) { 150 | newUser = true; 151 | } 152 | 153 | var detail = { 154 | "detail": { 155 | "name": user.displayName, 156 | "email": user.email, 157 | "emailVerified": user.emailVerified, 158 | "id": user.uid, 159 | "newUser": newUser 160 | } 161 | }; 162 | 163 | if (user.photoURL !== undefined) { 164 | detail.detail.photoUrl = user.photoURL; 165 | } 166 | 167 | return detail; 168 | }; 169 | 170 | 171 | this._formatEmptyUser = function (user) { 172 | 173 | var detail = { 174 | "detail": { 175 | "name": null, 176 | "email": null, 177 | "emailVerified": false, 178 | "id": null, 179 | "newUser": false 180 | } 181 | }; 182 | 183 | return detail; 184 | }; 185 | 186 | this.getToken = function () { 187 | var currentUser = firebase.auth().currentUser; 188 | return currentUser.getIdToken(); 189 | }; 190 | 191 | this.getCurrentUser = function () { 192 | var currentUser = firebase.auth().currentUser; 193 | var formattedUser; 194 | if (currentUser !== null) { 195 | formattedUser = this._formatUser(currentUser); 196 | } else { 197 | formattedUser = this._formatEmptyUser(); 198 | } 199 | 200 | return new Promise(function (resolve, reject) { 201 | resolve(formattedUser); 202 | }) 203 | }; 204 | 205 | this.signIn = function () { 206 | 207 | var currentUser = firebase.auth().currentUser; 208 | 209 | if (currentUser !== null && !currentUser.isAnonymous) { 210 | this.raiseEventForUser(currentUser); 211 | } else { 212 | var ui = firebaseui.auth.AuthUI.getInstance(); 213 | 214 | if (ui === null) { 215 | ui = new firebaseui.auth.AuthUI(firebase.auth()); 216 | } 217 | 218 | var element = document.getElementById(this.uiElement); 219 | 220 | element.style.display = "block"; 221 | element.style.position = "fixed"; 222 | element.style.top = "0"; 223 | element.style.paddingTop = "80px"; 224 | element.style.left = "0"; 225 | element.style.right = "0"; 226 | element.style.bottom = "0"; 227 | element.style.zIndex = "10000"; 228 | element.style.backgroundColor = "white"; 229 | 230 | ui.start('#' + this.uiElement, this.uiConfig); 231 | } 232 | }; 233 | 234 | this.sendEmailVerification = function () { 235 | 236 | var currentUser = firebase.auth().currentUser; 237 | var customEvent; 238 | 239 | currentUser.sendEmailVerification().then(function () { 240 | customEvent = new CustomEvent("emailverificationsent", {}); 241 | window.dispatchEvent(customEvent); 242 | }, function (error) { 243 | customEvent = new CustomEvent("emailverificationnotsent", {}); 244 | window.dispatchEvent(customEvent); 245 | }); 246 | }; 247 | 248 | this.signOut = function () { 249 | firebase.auth().signOut(); 250 | var customEvent = new CustomEvent("signoutsuccess", {}); 251 | window.dispatchEvent(customEvent); 252 | this.signInAnonymously(); 253 | }; 254 | 255 | this.delete = function () { 256 | var ui = firebaseui.auth.AuthUI.getInstance(); 257 | 258 | if (ui === null) { 259 | ui = new firebaseui.auth.AuthUI(firebase.auth()); 260 | } 261 | 262 | var currentUser = firebase.auth().currentUser; 0 263 | currentUser.delete().then(function () { 264 | ui.delete(); 265 | 266 | var customEvent = new CustomEvent("deleteusersuccess", {}); 267 | window.dispatchEvent(customEvent); 268 | self.signInAnonymously(); 269 | 270 | }).catch(function (err) { 271 | var customEvent = new CustomEvent("deleteuserfailure", { 272 | detail: { 273 | message: err.message 274 | } 275 | }); 276 | window.dispatchEvent(customEvent); 277 | }); 278 | }; 279 | } 280 | 281 | module.exports = { 282 | initialise: function (options) { 283 | return new Promise(function (resolve, reject) { 284 | var db = new FirebaseUIAuth(options, resolve); 285 | }); 286 | } 287 | }; 288 | -------------------------------------------------------------------------------- /www/firebaseUIAuthPlugin.js: -------------------------------------------------------------------------------- 1 | /*global dispatchEvent: false, Promise: false, CustomEvent: false */ 2 | /*jshint esversion: 6 */ 3 | var exec = require('cordova/exec'); 4 | const PLUGIN_NAME = 'FirebaseUIAuth'; 5 | 6 | function FirebaseUIAuth(options) { 7 | 8 | function dispatchEvent(event) { 9 | window.dispatchEvent(new CustomEvent(event.type, { 10 | detail: event.data 11 | })); 12 | } 13 | 14 | options = options || {}; 15 | exec(dispatchEvent, null, PLUGIN_NAME, 'initialise', [options]); 16 | 17 | this.getToken = function() { 18 | return new Promise(function(resolve, reject) { 19 | exec(resolve, reject, PLUGIN_NAME, 'getToken', []); 20 | }); 21 | }; 22 | 23 | this.getCurrentUser = function() { 24 | return new Promise(function(resolve, reject) { 25 | exec(resolve, reject, PLUGIN_NAME, 'getCurrentUser', []); 26 | }); 27 | }; 28 | 29 | this.signIn = function() { 30 | return exec(dispatchEvent, null, PLUGIN_NAME, 'signIn', []); 31 | }; 32 | 33 | this.signInAnonymously = function() { 34 | return exec(dispatchEvent, null, PLUGIN_NAME, 'signInAnonymously', []); 35 | }; 36 | 37 | this.signOut = function() { 38 | return exec(dispatchEvent, null, PLUGIN_NAME, 'signOut', []); 39 | }; 40 | 41 | this.delete = function() { 42 | return exec(dispatchEvent, null, PLUGIN_NAME, 'deleteUser', []); 43 | }; 44 | 45 | this.sendEmailVerification = function() { 46 | return exec(dispatchEvent, null, PLUGIN_NAME, 'sendEmailVerification', []); 47 | }; 48 | 49 | this.reloadUser = function() { 50 | return exec(dispatchEvent, null, PLUGIN_NAME, 'reloadUser', []); 51 | }; 52 | } 53 | 54 | module.exports = { 55 | initialise: function(options) { 56 | return new Promise(function(resolve, reject) { 57 | resolve(new FirebaseUIAuth(options)); 58 | }); 59 | } 60 | }; 61 | --------------------------------------------------------------------------------