What are the security rules in Firestore for accessing a new document within a transaction?

In my Firestore transaction, I am creating a new document in the accounts collection and linking its ID to the user's accounts. The account object being sent includes the user ID within the members field.

db.runTransaction(transaction => {
    return transaction.get(db.collection('accounts').doc())
        .then(res => {
            const accountId = res.id;
            transaction.set(db.collection('accounts').doc(accountId), {name, numberOfEmployees, businessTypes, industry, members})
            transaction.set(db.collection('users').doc(uid), {accounts: {[accountId]: true}}, {merge: true})
            return accountId;
        }, error => error)
})

I am relying on the behavior of .collection('accounts').doc() without a specified path to create a new document. However, I am encountering the "Missing or insufficient permissions" error despite having set up rules:

service cloud.firestore {
  match /databases/{database}/documents {

    match /users/{userId} {
      allow read, write: if request.auth.uid == userId;
    }

    match /accounts/{accountId} {
        // allow read if user is a member or if the document does not exist
        allow read : if resource.data.members[request.auth.uid] == true || !exists(/databases/{database}/documents/accounts/$(accountId));

      // allow update, delete if user is a member
      allow update, delete: if resource.data.members[request.auth.uid] == true;

      // allow creation of any authenticated user
      allow create: if request.auth != null;
    }
  }
}

The issue seems to be with the read rule on /accounts/{accountId}. Adjustments are needed to grant access to documents that have not been created yet. What modification should be made to allow this?

Answer ā„–1

Utilize the getAfter() function within your security rules to access the document state at the conclusion of the transaction (prior to its finalization).

Instead of employing resource == null, which may appear confusing to rule readers, consider using:

allow read, update, delete: if request.auth != null && getAfter(/databases/$(database)/documents/accounts/$(accountId)).data.members[request.auth.uid] == true;

Answer ā„–2

Located the solution by adjusting the condition to:

allow read, update, delete: if request.auth != null && (resource.data.members[request.auth.uid] == true || resource == null);

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

Transferring information in React from a child component to its parent and then to another child

I'm currently developing my app using react.js and facing an issue with passing data between components. I have a Parent component (P) that needs to receive an array of objects from its child component (C1), then pass this data on to another child com ...

Restrict HTML Elements Based on Their Size

I have a text file with a substantial amount of content that I need to display in an HTML format. The challenge is that I only want to show a portion of the text on the screen, but I am unsure of the exact amount that needs to be displayed. What I do know ...

Position the div in the center and enhance the function to dynamically adjust when the user attempts to resize the window

var windowHeight = $(window).height(); var windowWidth = $(window).width(); var scrollTop = $(window).scrollTop(); var scrollLeft = $(window).scrollLeft(); jQuery.fn.center = function () { this.css("position","absolute"); this.css("top", Math.max( ...

Utilize CSS in your HTML using Express framework

I am attempting to link a css stylesheet to my basic html webpage. I am utilizing parse.com hosting for dynamic webpages that utilize express. There are numerous responses to this question, but none of them have proven successful in my case. I am trying ...

Preventing text from wrapping in a TypeScript-generated form: Tips and tricks

Iā€™m currently working on a ReactJS project and my objective is simple: I want all three <FormItem> components to be displayed in a single line without wrapping. However, I am facing the following output: https://i.stack.imgur.com/mxiIE.png Within ...

The eBay API is providing users with small thumbnail images with low resolution

Adding &outputSelector=GalleryInfo to the URL was supposed to give me a higher resolution thumbnail, but it doesn't seem to be working. I'm still new to JSON and the tutorial I'm following isn't very clear on the exact syntax needed ...

Is there a way to divide a single array into two separate arrays based on a specific element?

My goal is to create an interactive graph using plotly.js. I have an array named data that contains all the information needed for the graph. However, I want users to be able to select specific elements to display on the graph. To achieve this functionalit ...

Filtering arrays in JavaScript results in an array without any elements

// Performing data merging test const Array_1 = [{ class_1: 4, HeadTeacher: "Mrs Joe" }]; const Array_2 = [{ class_1: 10, HeadTeacher: "Loveth" }]; const Array_3 = [{ class_1: 1, HeadTeacher: "Itunu" }]; const Array_4 = [{ class_1: 1, HeadTeacher: "John" ...

When applying a cell formatter to change the color of a Tabulator cell, the text displayed is being

I am attempting to dynamically change the color of a tabulator cell based on its input. My initial approach was to simply try changing the cell's color. After running the following code, here is what I observed: function testFormatter(cell, formatt ...

JavaScript - the global and local variable dilemma

REVISED2: I'm encountering an issue with converting images to canvas using Pixastic in HTML5. How can I 'return' this converted image back to a global variable? Any suggestions? <img id="mainIllustration" alt="main illustration" src="Img ...

JavaScript: What is the best way to loop through specific properties of a JavaScript object?

I have a JavaScript object structured as follows: const columns = { firstLabel: 'Hello', secondLabel: 'world', thirdLabel: 'I', fourthLabel: 'Am', fifthLabel: 'Paul', }; My goal is to e ...

Menu toggle vanishes suddenly

Whenever I click the toggle button, I notice that the menu (which I have set to appear on toggle) only shows for a brief moment before disappearing. As a beginner in bootstrap, I am sure I might have made some obvious mistakes. Any assistance would be gr ...

Ensure that Colorbox remains centrally positioned even while scrolling

I have noticed a difference in behavior between thickbox and colorbox when it comes to scrolling. Thickbox always stays centered on the screen even when the user scrolls vertically, while colorbox fades out and leaves just a grayed background. Is there a w ...

Ways to automatically close the search box when the user clicks anywhere within the body

What I desire At the moment, the search box opens and closes when the font awesome search icon is clicked. However, I also want the option for the search box to close if the user clicks anywhere within the body. Screenshot [ My Custom Code <div ...

Refresh the flatlist to display new content without uploading items automatically

When I click the save button in my FlatList component within React Native, the data does not reload automatically or render in the FlatList. However, if I manually reload the app, the saved item appears. I've tried various methods to make the data re ...

Dynamically filling a second dropdown menu according to the selection made in the first dropdown using AJAX and PHP

Help! I'm feeling a bit overwhelmed. Even though this question has been answered multiple times, I still can't figure it out. There must be something so obvious that I am missing. I want the options in the second select input to be populated dyn ...

Is there a built-in constant in the Angular framework that automatically resolves a promise as soon as it

I'm facing a situation where I have code that checks a conditional statement to decide if an asynchronous call should be made. If the condition is not met, the call is skipped. However, I still need to perform some final action regardless of whether t ...

Sending data from JavaScript to Jade templatesIs this alright?

Utilizing node.js, express, jade, and socket.io, I have successfully executed JavaScript code on the jade side. However, I am encountering difficulty in generating HTML output from the script block. Based on your feedback, I have updated my question to in ...

What is the method for providing external parameters to a JOI extension?

Perhaps JOI may not be the ideal tool for this particular task, but I am interested in utilizing it if feasible. Essentially, I have a scenario where a user is sending a request to an API to store specific metric data. Certain metrics are restricted based ...

Having trouble with the downloadUrl function when trying to generate a Google map locator in Opencart?

Currently, I am working on the development of a website using opencart at Within the dealers.php file, there is a function named query() which searches postcodes in the database to retrieve store location results and outputs them in XML format. For exampl ...