5

I only want the user to be able to load the group if they have the group in their list, how would I write a rule for that?

Or is there a way to write a rule to look for a value in a firebase push array?

Database Schema

For example I'd like to write a rule to maybe look like this. This rule isn't valid, but aiming to explain my point with it.

"groups":{
  "$group_id":{
    ".read":"root.child('users').child(auth.uid).child('groups').hasChildValue().val() == $group_id"
  }
},

I only want the user to be able to load the group if they have the group in their list, how would I write a rule for that?


Update, how I fixed it. - Restructuring the data to be flat. Get rid of using push() to add values. - Flat data made it easy to reference the keys.

Fixed Structure

"groups":{
        // root/users/auth.uid/groups/$group_id
        "$group_id":{
          // only read if the user has the group_id
          ".read":"root.child('users').child(auth.uid).child('groups').child($group_id).exists()",
          // only write if logged in and it's new || if the user has group id
          ".write":"(auth != null && !data.exists() && newData.exists()) || root.child('users').child(auth.uid).child('groups').child($group_id).exists()"
      }
    },
Brandon
  • 2,034
  • 20
  • 25
  • ".read":"root.child('users').child(auth.uid).child('groups').hasChild($group_id)", - this works if the group_id is the push auto_id, but doesn't get me what I want. – Brandon Jun 04 '16 at 18:23
  • Maybe the .forEach could work. I'm not sure what the return value of the forEach is if you return false in the function. Otherwise you might want to change your model. I think your data looks like this : https://www.firebase.com/docs/web/guide/structuring-data.html#section-indices – meriouma Jun 04 '16 at 19:48
  • There isn't a .forEach available for rules, unless I'm missing something. I'm looking at adding another relationship so I can make it bidirectional, so I can reference it without having to drill the push array. – Brandon Jun 04 '16 at 20:42
  • Yeah you're right, I mixed it up with DataSnapshot. I think your only option is to change your data model.. – meriouma Jun 04 '16 at 22:50
  • Yeah, you're right, I had to change the structure. Works like a charm now. – Brandon Jun 05 '16 at 06:23

1 Answers1

2

It almost seems like you are trying to 'filter' the group data, which is not what the Firebase rules are for. See link for reference:
https://firebase.google.com/docs/database/security/securing-data#rules_are_not_filters

For what it sounds like you are trying to achieve (restrict read access to groups) you'll need to adjust your data model to the way your app needs to access it. Let me know if this is what you are looking for and I can update my answer.

neoJato
  • 121
  • 1
  • 5