Firebase is unable to generate a new document

Recently, my firebase project has been experiencing an issue where it is unable to create new documents after the last build. While it can save and update existing documents, the function for creating new ones seems to be failing.

The function responsible for creating new documents should generate a unique key based on a newly created UID as shown below:

const sendInformationHandler = () => {
        const customerEmailCurrent = customerEmail.current.value
        const customerPassword = "password"
        if (checkUserEmailExists(customerEmailCurrent)) {
                createUser(
                    {
                        email: customerEmailCurrent,
                        password: customerPassword
                    }
                ).then(function(user) {
                    firebase
                    .firestore()
                    .collection('sessions')
                    .doc(user.data.uid).set(
                        {...context.state}
                    ).then(() => {
                        console.log("DATA SAVED SUCCESSFULLY!")
                    }).then(() => {
                        dispatch({ type: refreshContextFromCache, payload: INITIAL_CONTEXT})
                    }).then(() => {
                        push('/');
                    })
                }).catch(err => console.log("AN ERROR OCCURRED", err))
            } else {
                console.log("EMAIL ALREADY EXISTS!!!!!!")
            }
    };

I have configured checkUserEmailExists to always return true. The createUser function is working fine to create new users in Firebase cloud functions. However, when this function is triggered, it redirects before encountering an error.

The error message indicates a permissions issue. It's strange because my Firebase API key remains unchanged, and I can still modify existing records without any problems.

My database rules are also intact and rely on tokens for authentication, which are still functioning correctly:

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read, write: if request.auth.token.admin == true;
      }
    match /{document=**} {
      allow create: if request.auth.token.coach == true;
      }
    match /sessions/{userId} {
      allow read, write: if request.auth.token.customer == true && request.auth.uid == userId;
      }
  }
}

Prior to deployment, I made sure to switch to the correct Firebase project using "firebase use" in the CLI and Google Cloud locally.

Here is a snippet of my firebaserc configuration:

{
  "targets": {
    "prod": {
      "hosting": {
        "prod": [
          "prod-project"
        ]
      }
    },
    "develop": {
      "hosting": {
        "prod": [
          "prod-project"
        ]
      }
    },
    "prod-project": {
      "hosting": {
        "prod": [
          "prod-project"
        ]
      }
    },
    "ammonite-testing": {
      "hosting": {
        "prod": [
          "prod-project"
        ]
      }
    }
  },
  "projects": {
    "prod": "prod-project",
    "default": "prod-project"
  }
}

Additionally, here is a snapshot of my firebase.json file:

{
  "functions": {
    "source": "functions"
  },
  "hosting": {
    "target": "prod",
    "public": "build",
    "ignore": [
      "firebase.json",
      "**/.*",
      "**/node_modules/**"
    ],
    "rewrites": [
      {
        "source": "**",
        "destination": "/index.html"
      }
    ]
  }
}

These configurations seem correct, so why am I facing issues with Firebase permissions now? Why does saving data work while creating new documents triggers errors, especially after the latest CI build?

Answer №1

In reference to Renaud Tarnec's explanation, it seems that there are conflicting rules in your setup. According to the Firestore documentation, when multiple rules apply to a document, the request is granted if at least one of them evaluates to true. Specifically, the rules governing documents in the sessions collection are as follows:

match /sessions/{userId} {
    allow read, write: if request.auth.token.admin == true or
                          request.auth.token.coach == true or
                          (request.auth.token.customer == true && request.auth.uid == userId)
}

The reason why the application was functioning correctly before but now encounters issues cannot be pinpointed by us. It is possible that changes in the code triggered these errors, causing some requests to meet the security criteria while others do not.

If you wish to diagnose this further, consider adding logging statements to both this function and the associated Firebase function to track which claims (admin, coach, userId, etc.) are being sent.

When crafting Firestore security rules, it is advisable to steer clear of overlapping rules and instead opt for granting access at the most detailed level feasible. By doing so, data protection is enhanced, ensuring that access restrictions align with expectations and minimizing the chances of unnoticed rule conflicts.

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

Achieving function calling from controller to view with ng-click

I'm facing an issue with two buttons on my page. <div class="btn-group" ng-init="showData = 1"> <button ng-model="showData" type="button" ng-class='{"btn btn-primary": showData == 1, "btn btn-white": showData != 1}' ng-click= ...

Potential Problem Encountered in Verifying Passwords with `bcryptjs` in Node.js and React

Encountering a problem with the bcryptjs library when managing passwords in my application. Registering users works smoothly, but logging in using the same password is causing errors. Despite double-checking the accuracy of the password, it still fails to ...

What is preventing the expected outcome of setting this as a background image in NextJS 13 with Tailwind CSS?

Can someone help me figure out how to achieve the desired effect for this component? import React from "react"; import Image from "next/image"; import heroBackground from "../public/hero-background.png"; const Hero = () => ...

Restricting the quantity of dynamic list items within a function

My current goal with the Code I'm working on involves achieving two specific outcomes, which has me debating whether to separate the questions: JS: function listPosts(data) { postlimit = var output='<ul data-role="listview" data-fil ...

XMLHttpRequest is unable to load due to the absence of an 'Access-Control-Allow-Origin' header on the requested resource

No matter how many different solutions I've attempted to implement from various sources, none seem to be working for me. Here's a snippet of code that I'm trying to execute within the setInterval method in the document.ready() function. f ...

Utilizing jQuery and AJAX to prevent a specific section of a webpage ( <div> ) from refreshing during website navigation

I run a website that features an array of songs along with an embedded .mp3 player at the bottom. Once you click on a song, the player kicks off playing the track. However, if you attempt to navigate within the site by clicking on, for instance, an album, ...

Having trouble getting the JSONP request to render properly, encountering persistent errors

Need assistance with JSONP Rendering to HTML. The request is present in the source code, but I keep encountering errors on the foreach line. Any help would be greatly appreciated. <meta name="viewport" content="width=device-width, initial-scale=1"&g ...

Shifting the pagination outside of the slider in ReactJS and SwiperJS seems to be tricky. Despite trying to adjust the margins and padding, the pagination

I've been struggling with this issue for a while now. I need to move the pagination outside of the slider, but using padding or margin doesn't seem to work. It always remains inside the slider, and if I try to position it outside, it gets hidden. ...

What is the best method to erase data from an AutoComplete Box when clicking?

I have incorporated the Material UI AutoComplete component which can be found here. Below is my code snippet: <Autocomplete open={showUniSuggs} onOpen={this.props.getUniversityOptions} onChange={(event, value) => this.props.handleUniversi ...

Encountering a JavaScript error in the backend of Joomla 3.2

I am facing an issue with buttons on my Joomla 3.2.3 sites in the backend. The save, edit (material, module, menu...) buttons are not working properly. These sites were deployed using Akeeba Kickstart. Interestingly, everything worked fine on the developme ...

Methods for incorporating JSON Data into ChartJS

Below is my app.js file: app.js var app = angular.module('myApp', []); app.controller('MainCtrl', function($scope, $http) { $http.get('http://happyshappy.13llama.com/wp- json/llama/v1/stats').then(function(response) ...

Interactive tooltips that utilize both the onmouseover and onclick events

I have 5 links with tooltip hovers on each one except the last link. The reason for this difference is because I am utilizing the tooltip to inform the user that their data has been copied after clicking the link. However, I still want a hover effect on th ...

Error Message: Unable to Load User Profile Pictures from Microsoft Graph

Currently, I am developing an application that makes requests for user profile photos from Microsoft Graph. The process seems to be working smoothly as the request returns a 200 status code and a significant amount of data is retrieved. However, when I att ...

Encountering a blank page issue with react-router-dom v6 Routes

I am attempting to route a page to the root, but it keeps showing up as a blank page regardless of which JavaScript file I use. It seems like React Router DOM has been updated and no longer uses Switch. I haven't used React since last year, so I' ...

Having trouble accessing the EJS image with express.static in Node JS

i am attempting to retrieve an image from the uploads path using EJS, here is my file route here is the code in 'dotemplate.js' <div class="col-xs-12"> <h2 style="text-align: center; font-size: 12pt" >ATTACHMENT</h2> & ...

having difficulty grasping the variable's scope within this code

Here we have a code snippet where the variable vid is initialized inside a function. The question arises on how this variable can be used outside the function, specifically in the context of vid.play(). How does the program know that vid was created usin ...

Material UI AppBar displaying custom colors instead of theme colors

Currently, I am utilizing Material UI version 4.7.0. In my project, I have established a customized theme (shown below) by utilizing createMuiTheme() method with personalized primary and secondary colors set. Within my AppBar component (also displayed be ...

Issue with executing a jQuery event within a JavaScript object due to application error

I am struggling to comprehend how to set listeners in my JavaScript object. For instance: var obj = function(){ this.test = function(){ console.log('test'); } $(document).on('click','#test',(function(){ ...

Change the color of a specific day on the Arshaw Calendar using CSS

Can anyone help me with changing the color of the box in the month view in the arshaw calendar? I've been attempting to do so using this script, but my lack of expertise in javascript is proving to be a hurdle. The goal is for this script to be called ...

Implementing Enter key functionality to add items to a Todo list using pure DOM manipulation

var listLis=document.getElementById('list'); const addbutton=document.querySelector('.fa-plus') const inputBar=document.querySelector('.show') function showInput(e){ inputBar.classList.toggle('show') } addbutt ...