Optimizing the organization and maintenance of Firebase user data: A guide

I am learning about Firebase and after reading the documentation, there are still some aspects that I find confusing. I am working on creating an administrative panel on the client-side to handle CRUD operations for users. The application will not have a sign-up page; instead, the admin will be responsible for creating and activating users.

My understanding is that Firebase does not store user data in the "Firestore" app's collection. Even if I create a user collection, it will not automatically include fields like {email, displayName, password, phone, emailVerified, disabled}. This data is stored somewhere else and can only be accessed through Firebase-admin functions.

If this is the case, would it be best practice to create an HTTP function for admins to create users, assign roles, and manually manage unique fields like {email, displayName, phone}? If more properties need to be added to a user, should a profile collection be created and associated with the user after creation? All rules and validation need to be handled in the function. How can errors triggered by admin.auth().createUser(newUser) be effectively managed? Is there a project or boilerplate that demonstrates best practices for Firebase?

exports.createUser = functions.https.onCall(async (data, context) => {
    if (!context.auth) {
        createError('unauthenticated');
    }

    const roles = data.roles;
    if (!roleIsValid(roles) || !userValid(data)) {
        createError('dataInvalid');
    }

    const id= context.auth.uid;
    const caller = await admin.auth().getUser(id);
    if (!caller.customClaims.admin) {
        createError('notAdmin');
    }

    const newUser = {
        displayName: data.displayName,
        password: data.password,
        email: data.email,
        emailVerified: true,
        disabled: false
    }

   //todo: how to check all users if email, displayName, phone exists before creating user

    const user = await admin.auth().createUser(newUser);
    const userId = user.uid;

    const claims = {};
    roles.foreach(role => claims[role] = true);

    await admin.auth().setCustomUserClaims(userId, claims);
    await admin.firestore().collection("profile").doc(userId).set(data.profile);

    return {message: 'User successfully created.'};
});

Answer №1

In this discussion, I will outline the process of utilizing firebase's

auth.createUserWithEmailAndPassword()
method for user sign-up. When a user is created using Firebase auth, it automatically stores essential information such as email, providers, creation date, sign-in status, and User UID in the authentication system. However, we will also maintain a separate collection in Firestore to store additional user details, like a nickname specific to our application. This ensures that our app has access to comprehensive user information by consistently updating and retrieving data from the Firestore collection.

  1. When we initiate user creation with
    auth.createUserWithEmailAndPassword
    , we anticipate receiving an object containing basic user details once the promise is fulfilled.

A crucial function responsible for handling this process is defined below:

createUserProfileDocumentInFirestore(user, additionalData) {
       const snapshot = firestore.doc(`users/${user.id}`).get();
       if (!snapshot.exist) {
           // Store user collection with additional data
       }
       // Possibility of returning the updated user document for display in the app
   }
  1. Following step 1, the
    createUserProfileDocumentInFirestore
    function is called with the user obtained in step 1 along with any necessary additional information.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

AngularJS service $http is not retrieving the complete SELECT query results

Every time I try to retrieve data from this table, I only get the first entry even though there are actually three entries in there. The success alert response and the page it's directing to only show the first one, so I know it's not returning a ...

Harness the power of $compile within the Angular link function while also retrieving and utilizing the arguments of the

I am currently developing a custom directive in angular.js 1.x Here is how I call the directive: <mydirective dirarg={{value-1}}></mydirective> My goal is to define the directive by including code to alter the DOM within the directive's ...

Learn how to dynamically pass a value from a prop to a router-link in Vue.js

I created a custom button component and decided to switch from using <a> tags to <router-link>. However, I encountered an error because the router-link was rendering before the prop received its value. To address this, I added an if statement b ...

Error: An unidentified SyntaxError occurred with an unexpected token < within an anonymous function displayed on the console

In the process of developing an upload file application. The implementation involves AJAX and PHP. Everything functions smoothly on the localhost, but upon transferring it to the web server, a specific error is encountered: Uncaught SyntaxError: Unexpe ...

How to eliminate the "br" tags automatically inserted after each paragraph in TinyMCE version 6

I have been trying to work with TinyMCE version 6 and I am struggling to prevent the addition of <br> after each paragraph. Whenever I insert a line of text and press enter, a new paragraph is created but there is always a <br> added between t ...

Mastering advanced String templating using loops and control statements in Javascript

During runtime, I receive an array similar to the example below: var colors = ['red', 'green', 'blue']; I then need to create a JSON String that looks like this: { "color" : { "name" : "foo", "properties ...

Creating a responsive modal in Bootstrap 4

Everything seems to be in order, but my JavaScript doesn't seem to be functioning. I've implemented the code for a bootstrap 4 modal below: <div id="qmsManual" tabindex="-1" role="dialog" aria-labelledby="qmsManualModal" aria-hidden="true" c ...

The JavaScript function fails to give back the parameter values

After creating a function in the script tag within the head section that takes two parameters, a and b, to return the product of a multiplied by b, I encountered an issue. When calling the function with the values 3 and 4, nothing was displayed. To troubl ...

Encountering the "Cannot set headers after they are sent" error; it should be noted that render()/json() has only been called

I am encountering an issue while trying to send a response back to the client after inserting data into the database. Although I haven't called response.json() or response.render() twice in my code, I keep receiving the error message: Error: Can&apos ...

Why is it necessary to re-export both * and { default } in zustand.js?

As I delved into analyzing the codebase of zustand, I stumbled upon this snippet in index.ts: export * from './vanilla' export * from './react' export { default as createStore } from './vanilla' export { default } from '. ...

Guide on importing non-English content into Firestore using JSON files?

While I understand how to transfer data from JSON to RTDB and then to Cloud Firestore using node.js, I am facing a unique issue. My database is in Gujarati, an Indian language, but when I import it into Firebase RTBD, the text gets converted to question m ...

Troubleshooting MongoDB and Node.js: Issue with updating variables when inserting documents in a loop

As a newcomer to MongoDB, I'm facing a puzzling issue that has left me confused. In my dataset, I have an array of Employee objects structured like this: { "Name" : "Jack Jackson", "Title" : "Senior Derp Engineer", "Specialties" : [ "Kicki ...

Embedding images using a blob or base64 format does not function properly on iOS devices

I'm facing an issue with setting the src of an img tag to display an image. The code snippet below works fine on android, mac, and windows, but it is not functioning correctly on iOS: let base64Image = pageModel.image; this.$currentPageImage.src = `da ...

Testing React components with Jasmine

I need some guidance on how to properly integrate the Jasmine test runner into my React app without using Karma. Currently, I am deploying my test cases to a TV and running the standalone spec runner on the set. To do this, I had to inline and transpile th ...

Tips for removing a class with ng-class when a value is empty or evaluates to nothing

I'm facing an issue with a class I've created called .lines-hover. My goal is to remove this class when the values in the td elements are empty. For reference, take a look at this example: If you observe closely, on some of the lines, such as M ...

Python for Asynchronous HTTP Requests

I am currently working on a Python script to extract the value of the href attribute from an anchor element on a web page. The challenge is that the div element containing the anchor element's content is loaded through AJAX jQuery calls when the web p ...

Can a file object be transmitted using this method?

I'm new to jquery and I am attempting to upload a File object obtained from my HTML: <label for="photo" class="col-xs-2">Photo</label> <input id="photo" name="fileName" type="file" class="col-xs-4"/> This is the snippet of my J ...

Encountering error while attempting POST request in POSTMAN - "Unable to modify in restricted editor."

I'm facing a bit of a dilemma here. I can't seem to figure out how to make my editor in Postman stop being read-only. Can anyone lend a hand? Whenever I try to send a Post Request, my editor just won't cooperate and stays in Read-Only mode. ...

Tips for running a node-schedule task right away and at regular intervals of 30 minutes

I've developed a node.js program and I'm looking to set up a scheduling system for it using the node-schedule npm package so that it runs every 30 minutes. I have used the following code snippet to schedule it: var nodeSchedule = require(' ...

Making a synchronous call to a web API using JQuery

Understanding JQuery promises and deferred objects has been a bit of a challenge for me, so please bear with me. I should also mention that my application is built using React, Typescript, and ES6. Let's imagine we have an array of objects: [{ Objec ...