├── LICENSE ├── README.md └── firestore-user-document ├── CHANGELOG.md ├── POSTINSTALL.md ├── PREINSTALL.md ├── README.md ├── extension.yaml ├── functions ├── .gitignore ├── .mocharc.json ├── integration-tests │ ├── .gitignore │ ├── extensions │ │ └── firestore-user-document.env │ ├── firebase.json │ └── integration-test.spec.ts ├── package-lock.json ├── package.json ├── src │ ├── config.ts │ └── index.ts ├── tsconfig.dev.json └── tsconfig.json └── icon.png /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 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Firebase Extensions by Rowy Team 💜 2 | 3 | This is a collection of Firebase Extensions built by the [Rowy](https://www.rowy.io/?ref=firebase-extensions) team, designed to help you build your app faster. 4 | 5 | ## 📝 Firestore User Document 6 | 7 | The Firestore User Document extension allows you to automatically create a document in a Firestore collection of your choice whenever a new user is created in Firebase Authentication. You can also specify the user fields that you want to populate the document with, such as email, display name, image URL, etc. 8 | 9 | Optionally, this extension can be configured to delete the user's document when the user is deleted from Firebase Authentication. Furthermore, the extension can be set to backfill existing users and create documents for all of them. 10 | 11 | [👀 Documentation](https://github.com/rowyio/firebase-extensions/tree/main/firestore-user-document) 12 | 13 | [![install-extension](https://user-images.githubusercontent.com/35961879/201528504-4e99bfc7-8691-4151-b63d-0511097d7c18.png)](https://console.firebase.google.com/project/_/extensions/install?ref=rowy/firestore-user-document) 14 | 15 | ## 🙏 Acknowledgements 16 | 17 | [Sandrina](https://sandrina.framer.website) for the awesome extension icon. 18 | -------------------------------------------------------------------------------- /firestore-user-document/CHANGELOG.md: -------------------------------------------------------------------------------- 1 | ## Version 0.0.7 2 | 3 | - Fix bugs 4 | 5 | ## Version 0.0.6 6 | 7 | - Fix bugs 8 | 9 | ## Version 0.0.5 10 | 11 | - Fix bugs in the `backfillExistingUsers` function and add more logging. 12 | 13 | ## Version 0.0.4 14 | 15 | - Fix bugs in the `backfillExistingUsers` function and add more logging. 16 | 17 | ## Version 0.0.3 18 | 19 | - Add the tags field to the `extension.yaml` file. 20 | 21 | ## Version 0.0.2 22 | 23 | - Refine the POSTINSTALL.md documentation. 24 | - Add the extension icon to the repository. 25 | 26 | ## Version 0.0.1 27 | 28 | - Initial Version 29 | -------------------------------------------------------------------------------- /firestore-user-document/POSTINSTALL.md: -------------------------------------------------------------------------------- 1 | ### See it in action 2 | 3 | You can test out this extension right away: 4 | 5 | 1. Go to the [Cloud Firestore tab](https://console.firebase.google.com/project/${param:PROJECT_ID}/database/firestore/data) 6 | 2. Visit the Firestore collection that was created where your Firebase Authenticated users docs will be created 7 | 3. Create a new Firebase Auth user in your app, and your see that document created on this collection 8 | 9 | ### (Optional) Next step, manage the Firestore collections on Rowy Admin Panel 10 | 11 | You can now manage the Firebase Auth users collection on [Rowy](https://www.rowy.io?ref=extension) to get an instant admin panel for free. You can also invite your team members with granular access control to Rowy to build any operational process such as managing user's subscriptions, deactivation/deletion accounts or building signup email flows etc. 12 | 13 | 📺 Watch the [step-by-step guided video](https://www.rowy.io/authextension) on how to view and manage your user document collection (or any Firestore data) on Rowy's spreadsheet UI. 14 | 15 | ### Monitoring 16 | 17 | As a best practice, you can [monitor the activity](https://firebase.google.com/docs/extensions/manage-installed-extensions#monitor) of your installed extension, including checks on its health, usage, and logs. 18 | -------------------------------------------------------------------------------- /firestore-user-document/PREINSTALL.md: -------------------------------------------------------------------------------- 1 | Use this extension to create a document in a Firestore collection of your choice whenever a new user is created in Firebase Authentication. You can also specify the user fields that you want to include in the document, such as email, display name, image URL, etc. 2 | 3 | Optionally, this extension can be configured to delete the user's document anytime a user is deleted from Firebase Authentication and keep the collection in sync. Also, the extension can be set to backfill all the existing Firebase Authenticated users's information by creating a document for them in the collection the first time. 4 | 5 | #### Additional setup 6 | 7 | Before installing this extension, make sure that you've 8 | [set up a Cloud Firestore database](https://firebase.google.com/docs/firestore/quickstart) 9 | in your Firebase project. 10 | 11 | You can also optionally have a Rowy account setup after installing this extension - to manage the Firebase Authenticated users Firestore collection and any other Firestore collection on a collaborative spreadsheet-like CMS UI. You can do so on the [Rowy](https://www.rowy.io/?ref=extension) site. 12 | 13 | #### Billing 14 | 15 | This extension uses other Firebase or Google Cloud Platform services which may have associated charges: 16 | 17 | - Cloud Functions 18 | 19 | When you use Firebase Extensions, you're only charged for the underlying resources that you use. A paid-tier billing plan is only required if the extension uses a service that requires a paid-tier plan, for example calling to a Google Cloud Platform API or making outbound network requests to non-Google services. All Firebase services offer a free tier of usage. [Learn more about Firebase billing.](https://firebase.google.com/pricing) 20 | -------------------------------------------------------------------------------- /firestore-user-document/README.md: -------------------------------------------------------------------------------- 1 | # Firestore User Document 2 | 3 | **Author**: Rowy (**[https://rowy.io](https://www.rowy.io)**) 4 | 5 | **Description**: Create a document in a Firestore collection whenever a new user is created with Firesbase Authentication. 6 | 7 | **Details**: Use this extension to create a document in a Firestore collection of your choice whenever a new user is created in Firebase Authentication. You can also specify the user fields that you want to include in the document, such as email, display name, image URL, etc. 8 | 9 | Optionally, this extension can be configured to delete the user's document when the user is deleted from Firebase Authentication. Additionally, the extension can be set to backfill existing Firebase Authenticated users in the collection and create documents for all of them. 10 | 11 | ## 🧩 Installation 12 | 13 | To install the extension, follow the steps on the [Install a Firebase Extension](https://firebase.google.com/docs/extensions/install-extensions) page. In summary, do one of the following: 14 | 15 | - **Install from the Firebase console:** Click the button below: 16 | 17 | [![install-extension](https://user-images.githubusercontent.com/35961879/201528504-4e99bfc7-8691-4151-b63d-0511097d7c18.png)](https://console.firebase.google.com/project/_/extensions/install?ref=rowy/firestore-user-document) 18 | 19 | - **Install from the Firebase CLI:** Run the following command: 20 | 21 | ``` 22 | firebase ext:install rowy/firestore-user-document --project=YOUR_PROJECT_ID 23 | ``` 24 | 25 | ## 🛠️ Configuration Parameters 26 | 27 | | Name | Description | 28 | | ------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | 29 | | Users collection path | The path to the Firestore collection where user documents will be created. | 30 | | Fields to populate | Select the fields from the user record that you want to populate in the Firestore document. If you select a field that does not exist in the user record, it will be ignored. | 31 | | Delete document on user delete | If you enable this option, the extension will automatically delete the Firestore user document when the user is deleted from Firebase Authentication. | 32 | | Backfill existing users | If you enable this option, the extension will create Firestore user documents for all existing users right after installation is complete. | 33 | | Cloud Functions location | Where do you want to deploy the functions created for this extension? For help selecting a location, refer to the [location selection guide](https://firebase.google.com/docs/functions/locations). | 34 | -------------------------------------------------------------------------------- /firestore-user-document/extension.yaml: -------------------------------------------------------------------------------- 1 | name: firestore-user-document 2 | version: 0.0.7 3 | specVersion: v1beta 4 | displayName: Firestore User Document 5 | 6 | description: >- 7 | Creates a document in a specified Firestore collection whenever a new user is 8 | created in Firebase Authentication. The document is populated with fields that 9 | you select from the user record. You can also choose to delete the user's 10 | document when the user is deleted from Firebase Authentication. 11 | 12 | icon: icon.png 13 | 14 | tags: [utilities] 15 | 16 | license: Apache-2.0 17 | sourceUrl: https://github.com/rowyio/firebase-extensions/tree/main/firestore-user-document 18 | 19 | author: 20 | authorName: Rowy 21 | email: hello@rowy.io 22 | url: https://rowy.io 23 | 24 | contributors: 25 | - authorName: Yaman Katby 26 | email: me@yamankatby.com 27 | url: https://github.com/yamankatby 28 | 29 | - authorName: Sandrina 30 | url: https://sandrina.framer.website 31 | 32 | billingRequired: false 33 | 34 | roles: 35 | - role: datastore.user 36 | reason: Allows the extension to create the user document in Firestore. 37 | - role: firebaseauth.viewer 38 | reason: >- 39 | Allows the extension to read the list of existing users in Firebase 40 | 41 | resources: 42 | - name: createUserDocument 43 | type: firebaseextensions.v1beta.function 44 | description: >- 45 | A function that is triggered when a new user is created in Firebase 46 | Authentication. It creates a user document in a specified Firestore 47 | collection and populates it with the selected fields from the user record. 48 | properties: 49 | location: ${LOCATION} 50 | eventTrigger: 51 | eventType: providers/firebase.auth/eventTypes/user.create 52 | resource: projects/${PROJECT_ID} 53 | runtime: "nodejs16" 54 | 55 | - name: deleteUserDocument 56 | type: firebaseextensions.v1beta.function 57 | description: >- 58 | A function that is triggered when a user is deleted from Firebase 59 | Authentication. If the instance is configured to do so, it deletes the 60 | user document from the specified Firestore collection. 61 | properties: 62 | location: ${LOCATION} 63 | eventTrigger: 64 | eventType: providers/firebase.auth/eventTypes/user.delete 65 | resource: projects/${PROJECT_ID} 66 | runtime: "nodejs16" 67 | 68 | - name: backfillExistingUsers 69 | type: firebaseextensions.v1beta.function 70 | description: >- 71 | A function that is triggered right after the extension installation is 72 | complete. If the instance is configured to do so, it creates user documents 73 | in the specified Firestore collection for all existing users. 74 | properties: 75 | location: ${param:LOCATION} 76 | taskQueueTrigger: {} 77 | 78 | params: 79 | - param: USERS_COLLECTION_PATH 80 | label: Users collection path 81 | description: >- 82 | The path to the Firestore collection where user documents will be created. 83 | type: string 84 | default: users 85 | example: users 86 | required: true 87 | 88 | - param: FIELDS_TO_POPULATE 89 | label: Fields to populate 90 | description: >- 91 | Select the fields from the user record that you want to populate in the 92 | Firestore document. If you select a field that does not exist in the user 93 | record, it will be ignored. 94 | type: multiSelect 95 | options: 96 | - label: uid 97 | value: uid 98 | - label: email 99 | value: email 100 | - label: emailVerified 101 | value: emailVerified 102 | - label: displayName 103 | value: displayName 104 | - label: photoURL 105 | value: photoURL 106 | - label: phoneNumber 107 | value: phoneNumber 108 | - label: disabled 109 | value: disabled 110 | - label: creationTime 111 | value: creationTime 112 | default: email,displayName,photoURL 113 | required: true 114 | 115 | - param: DELETE_DOCUMENT_ON_USER_DELETE 116 | label: Delete document on user delete 117 | description: >- 118 | If you enable this option, the extension will automatically delete the 119 | Firestore user document when the user is deleted from Firebase 120 | Authentication. 121 | type: select 122 | options: 123 | - label: Yes 124 | value: true 125 | - label: No 126 | value: false 127 | default: true 128 | required: true 129 | 130 | - param: BACKFILL_EXISTING_USERS 131 | label: Backfill existing users 132 | description: >- 133 | If you enable this option, the extension will create Firestore user 134 | documents for all existing users right after installation is complete. 135 | type: select 136 | options: 137 | - label: Yes 138 | value: true 139 | - label: No 140 | value: false 141 | default: true 142 | required: true 143 | 144 | - param: LOCATION 145 | label: Cloud Functions location 146 | description: >- 147 | Where do you want to deploy the functions created for this extension? 148 | For help selecting a location, refer to the [location selection 149 | guide](https://firebase.google.com/docs/functions/locations). 150 | type: select 151 | options: 152 | - label: Iowa (us-central1) 153 | value: us-central1 154 | - label: South Carolina (us-east1) 155 | value: us-east1 156 | - label: Northern Virginia (us-east4) 157 | value: us-east4 158 | - label: Los Angeles (us-west2) 159 | value: us-west2 160 | - label: Salt Lake City (us-west3) 161 | value: us-west3 162 | - label: Las Vegas (us-west4) 163 | value: us-west4 164 | - label: Warsaw (europe-central2) 165 | value: europe-central2 166 | - label: Belgium (europe-west1) 167 | value: europe-west1 168 | - label: London (europe-west2) 169 | value: europe-west2 170 | - label: Frankfurt (europe-west3) 171 | value: europe-west3 172 | - label: Zurich (europe-west6) 173 | value: europe-west6 174 | - label: Hong Kong (asia-east2) 175 | value: asia-east2 176 | - label: Tokyo (asia-northeast1) 177 | value: asia-northeast1 178 | - label: Osaka (asia-northeast2) 179 | value: asia-northeast2 180 | - label: Seoul (asia-northeast3) 181 | value: asia-northeast3 182 | - label: Mumbai (asia-south1) 183 | value: asia-south1 184 | - label: Jakarta (asia-southeast2) 185 | value: asia-southeast2 186 | - label: Montreal (northamerica-northeast1) 187 | value: northamerica-northeast1 188 | - label: Sao Paulo (southamerica-east1) 189 | value: southamerica-east1 190 | - label: Sydney (australia-southeast1) 191 | value: australia-southeast1 192 | required: true 193 | immutable: true 194 | 195 | lifecycleEvents: 196 | onInstall: 197 | function: backfillExistingUsers 198 | processingMessage: Creating Firestore documents for existing users... 199 | -------------------------------------------------------------------------------- /firestore-user-document/functions/.gitignore: -------------------------------------------------------------------------------- 1 | ## Compiled JavaScript files 2 | **/*.js 3 | **/*.js.map 4 | 5 | # Typescript v1 declaration files 6 | typings/ 7 | 8 | node_modules/ 9 | -------------------------------------------------------------------------------- /firestore-user-document/functions/.mocharc.json: -------------------------------------------------------------------------------- 1 | { 2 | "require": "ts-node/register", 3 | "extensions": ["ts", "tsx"], 4 | "spec": [ 5 | "integration-tests/**/*.spec.*" 6 | ], 7 | "watch-files": [ 8 | "src" 9 | ] 10 | } -------------------------------------------------------------------------------- /firestore-user-document/functions/integration-tests/.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | npm-debug.log* 5 | yarn-debug.log* 6 | yarn-error.log* 7 | firebase-debug.log* 8 | firebase-debug.*.log* 9 | 10 | # Firebase cache 11 | .firebase/ 12 | 13 | # Firebase config 14 | 15 | # Uncomment this if you'd like others to create their own Firebase project. 16 | # For a team working on the same Firebase project(s), it is recommended to leave 17 | # it commented so all members can deploy to the same project(s) in .firebaserc. 18 | # .firebaserc 19 | 20 | # Runtime data 21 | pids 22 | *.pid 23 | *.seed 24 | *.pid.lock 25 | 26 | # Directory for instrumented libs generated by jscoverage/JSCover 27 | lib-cov 28 | 29 | # Coverage directory used by tools like istanbul 30 | coverage 31 | 32 | # nyc test coverage 33 | .nyc_output 34 | 35 | # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) 36 | .grunt 37 | 38 | # Bower dependency directory (https://bower.io/) 39 | bower_components 40 | 41 | # node-waf configuration 42 | .lock-wscript 43 | 44 | # Compiled binary addons (http://nodejs.org/api/addons.html) 45 | build/Release 46 | 47 | # Dependency directories 48 | node_modules/ 49 | 50 | # Optional npm cache directory 51 | .npm 52 | 53 | # Optional eslint cache 54 | .eslintcache 55 | 56 | # Optional REPL history 57 | .node_repl_history 58 | 59 | # Output of 'npm pack' 60 | *.tgz 61 | 62 | # Yarn Integrity file 63 | .yarn-integrity 64 | 65 | # dotenv environment variables file 66 | .env 67 | -------------------------------------------------------------------------------- /firestore-user-document/functions/integration-tests/extensions/firestore-user-document.env: -------------------------------------------------------------------------------- 1 | BACKFILL_EXISTING_USERS=true 2 | DELETE_DOCUMENT_ON_USER_DELETE=true 3 | FIELDS_TO_POPULATE=email,displayName,photoURL 4 | LOCATION=us-central1 5 | USERS_COLLECTION_PATH=users -------------------------------------------------------------------------------- /firestore-user-document/functions/integration-tests/firebase.json: -------------------------------------------------------------------------------- 1 | { 2 | "emulators": { 3 | "auth": { 4 | "port": 9099 5 | }, 6 | "firestore": { 7 | "port": 8080 8 | }, 9 | "functions": { 10 | "port": 5001 11 | }, 12 | "ui": { 13 | "enabled": true 14 | }, 15 | "singleProjectMode": true 16 | }, 17 | "extensions": { 18 | "firestore-user-document": "../.." 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /firestore-user-document/functions/integration-tests/integration-test.spec.ts: -------------------------------------------------------------------------------- 1 | import axios from "axios"; 2 | import { expect } from "chai"; 3 | 4 | describe("greet-the-world", () => { 5 | it("should respond with the configured greeting", async () => { 6 | const expected = "Hello World from greet-the-world"; 7 | 8 | const httpFunctionUri = "http://localhost:5001/demo-test/us-central1/ext-greet-the-world-greetTheWorld/"; 9 | const res = await axios.get(httpFunctionUri); 10 | 11 | return expect(res.data).to.eql(expected); 12 | }).timeout(10000); 13 | }); 14 | -------------------------------------------------------------------------------- /firestore-user-document/functions/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "firestore-user-document", 3 | "scripts": { 4 | "lint": "eslint \"src/**/*\"", 5 | "lint:fix": "eslint \"src/**/*\" --fix", 6 | "build": "tsc", 7 | "build:watch": "tsc --watch", 8 | "mocha": "mocha '**/*.spec.ts'", 9 | "test": "(cd integration-tests && firebase emulators:exec 'npm run mocha' -P demo-test)", 10 | "emulators": "cd ./integration-tests && firebase emulators:start", 11 | "generate-readme": "firebase ext:info .. --markdown > ../README.md" 12 | }, 13 | "main": "lib/index.js", 14 | "dependencies": { 15 | "firebase-admin": "^11.5.0", 16 | "firebase-functions": "^4.2.1", 17 | "typescript": "^4.9.0" 18 | }, 19 | "devDependencies": { 20 | "@types/chai": "^4.3.4", 21 | "@types/mocha": "^10.0.1", 22 | "@typescript-eslint/eslint-plugin": "^5.12.0", 23 | "@typescript-eslint/parser": "^5.12.0", 24 | "axios": "^1.3.2", 25 | "chai": "^4.3.7", 26 | "eslint": "^8.15.1", 27 | "eslint-config-google": "^0.14.0", 28 | "eslint-plugin-import": "^2.26.0", 29 | "mocha": "^10.2.0", 30 | "ts-node": "^10.4.0" 31 | }, 32 | "private": true 33 | } 34 | -------------------------------------------------------------------------------- /firestore-user-document/functions/src/config.ts: -------------------------------------------------------------------------------- 1 | interface IConfig { 2 | usersCollectionPath: string; 3 | fieldsToPopulate: string[]; 4 | deleteDocumentOnUserDelete: boolean; 5 | backfillExistingUsers: boolean; 6 | location: string; 7 | } 8 | 9 | const config: IConfig = { 10 | usersCollectionPath: process.env.USERS_COLLECTION_PATH!, 11 | fieldsToPopulate: process.env.FIELDS_TO_POPULATE!.split(","), 12 | deleteDocumentOnUserDelete: 13 | process.env.DELETE_DOCUMENT_ON_USER_DELETE === "true", 14 | backfillExistingUsers: process.env.BACKFILL_EXISTING_USERS === "true", 15 | location: process.env.FUNCTIONS_LOCATION!, 16 | }; 17 | 18 | export default config; 19 | -------------------------------------------------------------------------------- /firestore-user-document/functions/src/index.ts: -------------------------------------------------------------------------------- 1 | import { initializeApp } from "firebase-admin/app"; 2 | import { UserRecord, getAuth } from "firebase-admin/auth"; 3 | import { getExtensions } from "firebase-admin/extensions"; 4 | import { getFirestore } from "firebase-admin/firestore"; 5 | import { getFunctions } from "firebase-admin/functions"; 6 | import * as functions from "firebase-functions"; 7 | 8 | import config from "./config"; 9 | 10 | initializeApp(); 11 | 12 | const auth = getAuth(); 13 | const db = getFirestore(); 14 | 15 | const usersCollection = db.collection(config.usersCollectionPath); 16 | 17 | const getUserDocumentData = (user: UserRecord) => { 18 | const doc: any = {}; 19 | 20 | for (const field of config.fieldsToPopulate) { 21 | const fieldValue = user[field as keyof UserRecord]; 22 | if (fieldValue) { 23 | doc[field] = fieldValue; 24 | } 25 | } 26 | 27 | return doc; 28 | }; 29 | 30 | export const createUserDocument = functions.auth 31 | .user() 32 | .onCreate(async (user) => { 33 | const userDocumentRef = usersCollection.doc(user.uid); 34 | 35 | const data = getUserDocumentData(user); 36 | 37 | return userDocumentRef.set(data); 38 | }); 39 | 40 | export const deleteUserDocument = functions.auth 41 | .user() 42 | .onDelete(async (user) => { 43 | if (!config.deleteDocumentOnUserDelete) { 44 | return; 45 | } 46 | return usersCollection.doc(user.uid).delete(); 47 | }); 48 | 49 | const BATCH_SIZE = 100; 50 | 51 | export const backfillExistingUsers = functions.tasks 52 | .taskQueue() 53 | .onDispatch(async (data) => { 54 | const runtime = getExtensions().runtime(); 55 | 56 | if (!config.backfillExistingUsers) { 57 | return runtime.setProcessingState( 58 | "PROCESSING_COMPLETE", 59 | "Documents for existing users weren't created because the parameter " + 60 | '"Backfill existing users" was set to "No". If you want to create ' + 61 | "documents for existing users, reconfigure this instance." 62 | ); 63 | } 64 | 65 | if (data.pageToken) { 66 | console.log( 67 | "Continue backfilling existing users process. Processing batch " + 68 | `starting at page token: ${data.pageToken}` 69 | ); 70 | } else { 71 | console.log( 72 | "Starting the backfill process. Checking for existing users to " + 73 | "create documents for." 74 | ); 75 | } 76 | 77 | try { 78 | const { users, pageToken } = await auth.listUsers( 79 | BATCH_SIZE, 80 | data.pageToken 81 | ); 82 | 83 | const batch = db.batch(); 84 | 85 | for (const user of users) { 86 | const userDocumentRef = usersCollection.doc(user.uid); 87 | const data = getUserDocumentData(user); 88 | batch.set(userDocumentRef, data, { merge: true }); 89 | } 90 | 91 | await batch.commit(); 92 | 93 | const createdDocumentsCount = 94 | (Number(data.createdDocumentsCount) || 0) + users.length; 95 | 96 | if (pageToken) { 97 | const queue = getFunctions().taskQueue( 98 | `locations/${config.location}/functions/backfillExistingUsers`, 99 | process.env.EXT_INSTANCE_ID 100 | ); 101 | await queue.enqueue({ 102 | pageToken, 103 | createdDocumentsCount, 104 | }); 105 | } else { 106 | console.log( 107 | `The backfill process is complete. Created ${createdDocumentsCount} ` + 108 | "documents for existing users." 109 | ); 110 | return runtime.setProcessingState( 111 | "PROCESSING_COMPLETE", 112 | `Created ${createdDocumentsCount} documents for existing users.` 113 | ); 114 | } 115 | } catch (e) { 116 | console.error("Error while backfilling existing users", e); 117 | return runtime.setProcessingState( 118 | "PROCESSING_FAILED", 119 | "Error while backfilling existing users" 120 | ); 121 | } 122 | }); 123 | -------------------------------------------------------------------------------- /firestore-user-document/functions/tsconfig.dev.json: -------------------------------------------------------------------------------- 1 | { 2 | "include": [ 3 | ".eslintrc.js" 4 | ] 5 | } 6 | -------------------------------------------------------------------------------- /firestore-user-document/functions/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "module": "commonjs", 4 | "noImplicitReturns": true, 5 | "noUnusedLocals": true, 6 | "outDir": "lib", 7 | "sourceMap": true, 8 | "strict": true, 9 | "target": "es2017", 10 | "skipLibCheck": true 11 | }, 12 | "compileOnSave": true, 13 | "include": [ 14 | "src" 15 | ] 16 | } 17 | -------------------------------------------------------------------------------- /firestore-user-document/icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rowyio/firebase-extensions/f3a473e250d0221b3f7bfac6f41f74cadb52ee52/firestore-user-document/icon.png --------------------------------------------------------------------------------