Vitaly Menchikovsky
Vitaly Menchikovsky

Reputation: 8884

Cant read all data with security rules

I am trying to read all events node as user that have admin node, and able to read only related event if not admin. The issue that I cant get all events with this security rule.

  "Event":{
      "$uid": {
            ".read": "auth.uid == $uid || root.child('Users').child(auth.uid).child('admin').val() == 'admin'",
            ".write": true
        }

where my requests looks like:

   var starCountRef = firebase.database().ref("Event/"); //trying to read all events as admin
    starCountRef.on("value", (snapshot) => {
      const data = snapshot.val();

Upvotes: 1

Views: 45

Answers (1)

Tarik Huber
Tarik Huber

Reputation: 7388

The problem we have here is that the RTDB rules work from top down. That means if one rule in the top denies the access it doesn't matter what the one down says. In your case giving access to the whole list to the admin would be no problem but then also to each owner of the event would be. Because those are probably no admins. And you can access the whole list only when you put the .read above the uid.

There is one way I could imagine to make it work. There are query-based rules. More about them here.

You could write your rules like this:

 "Event":{
      ".read": "query.equalTo == auth.uid || 
           root.child('Users').child(auth.uid).child('admin').val() == 'admin'" 
        }

You would then need to access the data with a query to get it:

db.ref("Event").orderByKey()
                 .equalTo(auth.currentUser.uid)
                 .on("value", cb) 

Upvotes: 1

Related Questions