Firestore rule rejecting a request that was meant to be approved

Recently, I came across some TypeScript React code that fetches a firestore collection using react-firebase-hooks. Here's the snippet:

const [membersSnapshot, loading, error] = useCollectionData(
  query(
    collection(db, USERS_COLLECTION).withConverter(UserConverter.prototype),
    where(UserFields.FamilyId, "==", familyId)
  )
);

console.assert(error === undefined, error);

Initially, everything worked fine without any rules in place.

However, when I added a specific rule to the code, things started to go wrong. Here is the excerpt of the rule implementation:

function getUser() {
  return getUserData(request.auth.uid);
}
    
function getUserData(userId) {
  return get(/databases/$(database)/documents/users/$(userId)).data;
}

function isSignedIn() {
  return request.auth != null;
} 

function inSameFamily(userId) {
  return getUser().familyId == getUserData(userId).familyId;
}

match /users/{userId} {
  allow read: if isSignedIn() && request.auth.uid == userId || isSignedIn() && inSameFamily(userId); 
}

After implementing this rule, an assertion failed with the message "FirebaseError: Missing or insufficient permissions." This issue has left me puzzled and unsure of the root cause.

In an attempt to fix the problem, I modified the where condition as follows:

where(UserFields.Email, "==", userEmail)

Despite these changes, the expected outcome did not materialize, leading to failure even when trying to access the user data directly.

Answer №1

The issue arose when I mistakenly utilized the get() function instead of simply opting for the more straightforward choice, resource - which refers to the document that the user is attempting to access. It's perplexing why get failed to function as expected, but ultimately, switching to recource helped resolve the problem.

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

Tips on sending various properties to makeStyles() using TypeScript

After learning how to pass 1 prop to makeStyle() from a resource, I decided to try passing in 2 props for my project. However, I encountered an error stating cannot find name 'props'. Any assistance on this issue would be greatly appreciated! con ...

Choosing specific information in Typescript response

I am encountering an issue with my HTML where it displays undefined(undefined). I have checked the data in the debugger and I suspect that there may be an error in how I am using the select data. Here is a snippet of the code: <div *ngIf="publishIt ...

Unlock the secrets of linking objects with unique identifiers for a streamlined layout. Dive into the world of Angular 2

I'm looking for advice on how to effectively utilize a flat database structure in conjunction with other properties. For example, in my Firebase setup, each campaign contains multiple codes: campaigns -> userID -> campaignID -> properties ...

What are the best ways to work with LatLng objects?

When I run a request to retrieve data from a database, the response displayed in the console using JSON.Stringify() is as follows: sites : [{"siteName":"Site de Marseille", "siteAdress1":"rue du string", "siteAddress2":"string", "siteCodPost":"13010","sit ...

Leveraging non-React entities to seamlessly integrate components within a component hierarchy in React utilizing TypeScript

I am currently working on a React Typescript project where I am exploring the use of traditional polymorphism. Below is a simplified version of my project, where components are returned from vanilla Typescript objects rather than React components, allowing ...

Encountering difficulties accessing props while invoking a component in React

In my project, I've created a component called FilterSliders using Material UI. Within this component, I passed a prop named {classes.title} by destructuring the props with const { classes }: any = this.props;. However, when I try to access this prop ...

Is there a function in Zod similar to Yup's oneOf()?

If I wanted to restrict a property to specific values using Yup, it could be achieved with the code snippet below: prop: Yup.string().oneOf([5, 10, 15]) However, I haven't found a similar method in Zod. Nonetheless, I can still validate it by: const ...

Retrieve the outermost shell of the VUEjs wrapper test-utils

While working on a VueJS test, I encountered an issue where accessing the outermost layer of HTML seemed impossible. No matter what methods I tried, the outermost layer was always ignored. Is there a way to gain access to this outermost layer so that I c ...

What is the best way to transfer a property-handling function to a container?

One of the main classes in my codebase is the ParentComponent export class ParentComponent extends React.Component<IParentComponentProps, any> { constructor(props: IParentComponent Props) { super(props); this.state = { shouldResetFoc ...

Retrieve the observable value and store it in a variable within my Angular 13 component

Incorporating Angular 13, my service contains the following observable: private _user = new BehaviorSubject<ApplicationUser | null>(null); user$ = this._user.asObservable(); The ApplicationUser model is defined as: export interface ...

Issue with Material UI v5: "spacing" property not found on custom theme object

My current setup involves using version 5 of material ui, where I have customized a theme and applied it to all my components. However, when trying to add padding to a paper element in one of my components based on the theme, I encountered the following e ...

Utilizing a parent scope variable in a callback function

This question delves more into the concept of JavaScript Closures rather than Firebase. The issue arises in the code snippet below, where the Firebase callback fails to recognize the variable myArr from the outer scope. function show_fb() { var myAr ...

What is the best approach to validating GraphQL query variables while utilizing Mock Service Worker?

When simulating a graphql query with a mock service worker (MSW), we need to verify that the variables passed to the query contain specific values. This involves more than just type validation using typescript typings. In our setup, we utilize jest along ...

Issue: Unable to locate the name 'ContactField' in Ionic 2

While attempting to use Ionic2 to save a contact, an error occurs when running the app through the command line. The cordova-plugin-contacts has been properly installed. Below is the code snippet: import { Component } from '@angular/core'; impo ...

ServiceAccountKey cannot be located by Firebase deploy

I am in the process of integrating a serviceAccountKey into my Typescript cloud functions project. var serviceAccount = require("/Users/kareldebedts/myAppName/functions/serviceAccountKeyName.json"); admin.initializeApp({ storageBucket: "appName.appspot ...

Is it possible to compile using Angular sources while in Ivy's partial compilation mode?

Error: NG3001 Unsupported private class ObjectsComponent. The class is visible to consumers via MasterLibraryLibModule -> ObjectsComponent, but is not exported from the top-level library entrypoint. 11 export class ObjectsComponent implements OnInit { ...

Tips for detecting the end of a scroll view in a list view

I've encountered an issue with my scrollView that allows for infinite scrolling until the banner or container disappears. What I'm aiming for is to restrict scrolling once you reach the last section, like number 3, to prevent the name part from m ...

Tips for extracting URL parameter values in React applications

Here is a component that allows for searching: import { ChangeEvent, useCallback, useState } from 'react'; export function SearchComponent() { const [searchValue, setSearchValue] = useState<string>(''); const updateSearchValu ...

Leverage the power of zustand actions in your axios queries!

In my React application, I have implemented Zustand for creating a store: import { create } from 'zustand'; interface IAuth { username: string; isAuthentificated: boolean; updateAuth: (isAuth: boolean) => void; } export const useAuth = ...

Is there a way to merge two typed Joi schemas together?

I have two different interfaces, where the second one is an extension of the first: interface Core { id: string; } interface User extends Core { firstName: string; } To ensure validation, I utilize Joi schemas. For the Core interface, it's easy ...