1

When using .read with a true rule on the Users node, I give access to some authenticated user read every user listed on that tree. I need just some of then.

I need some rule that works like a filter. So on getting User/ path, this authenticated user will get an users array of only those that have permission path like this $uid > permission > auth.uid = true.

{
  "rules": {
    "Users" : {
      ".read": true,
      "$uid" : {
        ".read" : "(auth != null && auth.uid === $uid) || root.child('Users/'+ $uid+'/permission/'+ auth.uid).val() == true",
        ".write" : false
      }
    },
  }
}
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
calebeaires
  • 1,972
  • 1
  • 22
  • 34

1 Answers1

3

You can't use rules as filters, they are atomic to the specific branch you are trying to read/write.

Your outer read rule is giving access to the whole /Users branch. Removing it and having the userId that you want to read you will get the behavior you are expecting. So, unfortunately this will work only when reading with ref.child("Users").child(targetUserId).once....

{
  "rules": {
    "Users" : {
      "$uid" : {
        ".read" : "(auth != null && auth.uid === $uid) || root.child('Users/'+ $uid+'/permission/'+ auth.uid).val() == true",
        ".write" : false
      }
    }
  }
}

If you want to have, in one single call, the list of user ids that the authenticated user has access to I recommend you to actually save the accessible users inside /User/userId instead of having the ones that can read. And your rules will slightly change.

 {
      "rules": {
        "Users" : {
          "$uid" : {
            ".read" : "(auth != null && auth.uid === $uid) || root.child('Users/'+ auth.uid +'/accessibleUsers/'+ $uid).val() == true",
            ".write" : false
          }
        }
      }
    }

Additionally, this can get complex when scaling so, depending on what you plan for you application, you should be thinking of having this accessible users list in a separate branch (outside of Users).

adolfosrs
  • 9,286
  • 5
  • 39
  • 67
  • I get it. I was on the way this [article](https://www.airpair.com/firebase/posts/structuring-your-firebase-data) says to, so I have faced this problem. I will try your approach. – calebeaires Aug 01 '16 at 14:01