Gerardo Ruiz
Gerardo Ruiz

Reputation: 393

How to protect a Firebase Node depending on sibling Node?

I need to implement some rules in Firebase to protect my data.

Let's say I have node a and node b. The structure is as follows:

{
    a:
    [
        a1: {uid: 123},
        a2: {uid: 321},
        a3: {uid: 567}
    ],
    b:
    [
        a1: {data: 'foo.bar'},
        a2: {data: 'foo.bar'},
        a3: {data: 'foo.bar'}
    ]
}

As in the example above, the child nodes of a are the keys of node b. How can I restrict the access to data of node b depending on the uid of node a?

For example. The user with uid 123 in the node a, his key is a1, so, in node b only can retrieve data from child node a1 (b -> a1).

Upvotes: 0

Views: 77

Answers (1)

Grimthorr
Grimthorr

Reputation: 6926

I think a rule system like this would match your requirement:

{
  "rules": {
    "b": {
      "$key": {
        ".read": "auth.uid == root.child('a').child($key).child('uid').val()",
        ".write": "auth !== null"
      }
    }
  }
}

In this example, $key is a $location variable that matches any key under the list of node b.

We can then use this $key variable to match the current user's auth.uid to the uid of the corresponding node under a, using root.child().

The result is that this will only grant read access to a child under b if the uid of the corresponding child with the same key under a matches the current user's uid.

Upvotes: 1

Related Questions