Firestore security rules are failing to enforce restrictions on a particular field

Guidelines:

match /transactions/{transaction} {
  allow read: if request.auth.uid == resource.data.user_id;
}

Data Source:

https://i.sstatic.net/MNLGP.jpg

Database File:

 this.transCollection = afs.collection<Transaction>('transactions',ref => ref.where('cust_id', '==', this.cust_id).orderBy('created','desc'));
     this.transactions = this.transCollection.snapshotChanges().pipe(
       map(actions => actions.map(a => {
         const data = a.payload.doc.data() as Transaction;

         const id = a.payload.doc.id;
         return { id, data };
       }))
     );

Error: core.js:1673 ERROR Error: Missing or insufficient permissions.

Answer №1

Security measures do not automatically filter data; instead, they only permit queries that are guaranteed to match documents within the allowed parameters. If there is any possibility of a query producing results outside the specified permissions, it will be rejected by the security rules.

Your current query filters based on cust_id, but the rules dictate allowances/disallowances based on user_id. This discrepancy means your query is attempting to access documents that exceed your authorization. Because the query could potentially retrieve a document with an incorrect user_id, it is rejected according to the rules. For more information, please refer to https://firebase.google.com/docs/firestore/security/rules-query

In order to address this issue, consider adjusting your rules to accommodate filtering by cust_id as well:

allow read: if request.auth.uid == resource.data.cust_id;

By implementing these revised rules, you align the conditions set by the query and consequently allow for successful reads/listening operations.

Answer №2

After finding the solution, it was discovered that there is nothing wrong with the condition. However, before applying any field-based conditions to the user ID, requests from authenticated users need to be allowed first. Then, you can check if the user ID matches the current user ID:

// Allow a read if request user id is same as resourse user_id
    allow read: if request.auth.uid == resource.data.user_id;

Rules:

match /transactions/{transaction} {
  allow read: if request.auth.uid == resource.data.user_id;
}

ts file:

//Add user_id in where condition 
this.transCollection = afs.collection<Transaction>('transactions',ref => ref.where('user_id', '==', this.user_id).where('cust_id', '==', this.cust_id).orderBy('created','desc'));
     this.transactions = this.transCollection.snapshotChanges().pipe(
       map(actions => actions.map(a => {
         const data = a.payload.doc.data() as Transaction;

         const id = a.payload.doc.id;
         return { id, data };
       }))
     );

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

Struggling to update a scope variable when utilizing Firebase's Facebook authentication with AngularJS

Hey there... I'm currently exploring AngularJS and attempting to implement Facebook's connect feature using Firebird. Almost everything is running smoothly - the connection to my Facebook account is successful, and the information is retrieved w ...

What is the best way to integrate Firebase storage into a React app on the client side?

Struggling to save a file to cloud storage from my React app. I used create-react-app to set up a new React project. Following the correct instructions, I obtained a storage reference using this.storage = firebase.storage();. However, no matter how I confi ...

Conceal the Angular Material toolbar (top navigation bar) automatically when scrolling downwards

In my Angular application, the main navigation consists of a standard toolbar positioned at the top of the page. My goal is to have this navigation bar smoothly scroll up with the user as they scroll down, and then reappear when they scroll back up. I at ...

Creating a universal wrapper function to serve as a logging tool?

Currently, I am working on a generic JS function that can wrap any other function. The purpose of this wrapper is to execute the wrapped function, log the input and output events, and then return the output for "transparent" logging. However, as I attempt ...

Updating multiple child nodes simultaneously in Firebase on an Android device

https://i.sstatic.net/irBQZ.png I am looking to dynamically update time slots based on certain conditions. For example, if a user books a bike for a specific time range, let's say from 09:00 AM to 12:00 PM, then I want to mark the availability of tha ...

Exploring the mechanics behind optional chaining, known as the Elvis operator, in TypeScript. How does this feature operate within the

Can someone explain the concept of optional chaining (Elvis operator) in TypeScript and how it can be used effectively? public static getName(user: IUser){ if(user.firstName != null && user.firstName != ""){ return user.firstName; } ...

The data type 'unknown' cannot be directly converted to a 'number' type in TypeScript

After developing a type for my click handle functions that should return a value with the same type as its parameter, I encountered the following code: type OnClickHandle = <T extends unknown = undefined>(p: T extends infer U ? U : T) => ...

What could be causing the issue preventing me from updating an npm library to the latest version and keeping me stuck with an older version?

Currently, I am using Node v14.16.1 and npm 7.9.0 I'm trying to update the Firebase-tools library by running either sudo npm upgrade firebase-tools -g or sudo npm install -g firebase-tools to ensure that I have the latest version of firebase-tools. ...

Accessing JSON file content from Firebase storage

I'm currently working on extracting the data from a JSON file stored in my Firebase in order to utilize it for searching within my Google action. So far, I have managed to retrieve the file, but I'm unsure of which method to employ next. I am loo ...

Typescript: Potential null object error when defining a method

I recently encountered an error message stating "Object is possibly null" while working on the changePageSize method in book-store.component.html. It seems like I need to initialize the object within the class, but I'm not familiar with how to do that ...

Troubleshooting Cloud Functions: Fixing functions.logger.log not Functioning

Whenever a user updates the chat/{id} documents, this function is triggered. const functions = require("firebase-functions"); exports.onChangedChat = functions.firestore .document('chat/{id}') .onWrite((change, context) => { fun ...

What is the solution for fixing the Typescript error in formik onSubmit?

I encountered an error while using the onSubmit prop of Formik: The type '(values: { email: string; password: string; }) => { type: string; payload: { email: string | null; password: string | null; }; }' is not compatible with the type &apos ...

Adding a second interface to a Prop in Typescript React: a step-by-step guide

import { ReactNode, DetailedHTMLProps, FormHTMLAttributes } from "react"; import { FieldValues, SubmitHandler, useForm, UseFormReturn, } from "react-hook-form"; // I am looking to incorporate the DetailedHTMLProps<FormHTMLAt ...

Retrieving the value of an object using an array of keys

Consider the following object: const obj = { A:{ a1:'vala1', a2:'vala2' }, B:{ b1: 'valb1', b2: 'valb2' }, C:{ c1:{ c11:'valc11' }, c2:'valc2' } } We also have an array: const ...

What is the method for confirming whether an emit has been defined?

I have a button that can handle both short and long press events. Before transitioning to emitters, I relied on function callbacks due to my background in React Native. The typings I used were: export type UsePressableEmits = | { (e: "press& ...

Exploring the functionality of window.matchmedia in React while incorporating Typescript

Recently, I have been working on implementing a dark mode toggle switch in React Typescript. In the past, I successfully built one using plain JavaScript along with useState and window.matchmedia('(prefers-color-scheme dark)').matches. However, w ...

Issue encountered when trying to access colors within MUI theme in Typescript

I have a unique color scheme set for my material ui theme, which I define as follows: createTheme({ palette: { primary: { main: '#193C7D', dark: '#112853', light: '#2C4DBC', '900': &apo ...

Issues are arising with Angular Form where the FormControl is not being properly set up for the first field in my form

After grappling with this issue for several weeks, I am still unable to pinpoint the cause. (Angular version: 16.1.4) The form component is populated using a BehaviorSubject, and although the console prints out the correct values for both the form and dat ...

Is it possible to import both type and value on the same line when isolatedModules=true?

Did you know with Typescript, you can do type-only imports? import type { Foo } from "./types" If the file exports both types and values, you can use two separate import statements like this: import type { Foo } from "./types"; import ...

Encountering a problem while bringing in screens: 'The file screens/xxx cannot be located within the project or any of these folders.'

I am currently working on an iOS application using React Native technology. During the process of importing a specific screen, I encountered an error message. Can anyone provide guidance on how to resolve this issue? Error: Unable to resolve module scree ...