Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I create a rule in firebase that will query a value in a push() array?

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()"
      }
    },
like image 737
Brandon Avatar asked Oct 30 '22 02:10

Brandon


1 Answers

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.

like image 84
neoJato Avatar answered Nov 13 '22 00:11

neoJato