Dinh Quang Tuan
Dinh Quang Tuan

Reputation: 574

Firebase realtime rule access parent based on child value

There are many posts about firebase realtime rule but I still cannot solve my problems.

This is my data. There may be multiple "GId" or multiple "User" or multiple "caregiver".

enter image description here

I want to grant access to "GId" if a specific value exists in "caregiver". My following rule does not work.

{
  "rules": {
    "GId": {
      "$GId": {
        ".write": "data.child('User').child('caregiver').child('-N0Uy6K55bQlkPuuoioA').exists() ",
        ".read": "data.child('User').child('caregiver').child('-N0Uy6K55bQlkPuuoioA').exists()",
      }
    }
  }
}

But if I change the rule to grant access to "GId" if a specific value exists in "User", it works. Could you please show me what is wrong with my first rule?

Is it possible to grant other "GId" access to only some "User" in another "GId"?

{
  "rules": {
    "GId": {
      "$GId": {
        ".write": "data.child('User').child('6e42092aa73f47f48657fe7f3a9610c5').exists() ",
        ".read": "data.child('User').child('6e42092aa73f47f48657fe7f3a9610c5').exists() ",
      }
    }
  }
}

Upvotes: 0

Views: 54

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 598728

When you run a query on a path in the Realtime Database checks for the value you specify at a specific, known path under each direct child node of the path where the query runs.

In your second set of rules, you specify the full path of the child whose existence you care about, so the rule can find the node at User/6e42092aa73f47f48657fe7f3a9610c5 under the $GId. In the first set of rules however the 6e42092aa73f47f48657fe7f3a9610c5 is not in the path you look at, and there is no node at User/caregiver/-N0Uy6K55bQlkPuuoioA directly under $GId.

To make the rules work you will need to flatten your data structure, and possibly set up an inverse index so that you can look up whether access is allowed given the information that you do know. I'd also recommend reconsidering the nesting of multiple data types in a single branch in your data structure, as it's a common antipattern and Firebase recommends keeping the data flat.

Also see:

Upvotes: 1

Related Questions