ios_Dev_Harsh
ios_Dev_Harsh

Reputation: 51

Firebase rules to access specific child's value

The childByAutoId would be useful if you want to save in a node multiple children of the same type, that way each child will have its own unique identifier.

List:{
KJHBJJHB:{
  name:List-1,
  owner:John Doe,
  user_id:<Fire base generated User_id>
},
KhBHJBJjJ:{
  name:List-2,
  owner:Jane Lannister,
  user_id:<Fire base generated User_id>
},
KhBHJZJjZ:{
  name:List-3,
  owner:John Doe,
  user_id:<Fire base generated User_id>
}
}

I am trying to access the List with the help of the following code:

let ref = FIRDatabase.database().reference(withPath: "/List")

The current user logged into the app is John Doe. When the user accesses the list, I want all the List child whose owner is John Doe(i.e. List-1 & List-3) and ignore the other child values.

Do I have to do this in my application or can this be achieved via Firebase Security rules?

My current rule definition is:

"List":{
 ".read": "root.child('List/'+root.child('List').val()+'/user_id').val() === auth.uid" }

But this rule is not giving me any success. Any idea how to achieve the desired result?

Upvotes: 1

Views: 1100

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 598847

You're trying to use security rules to filter the list. This is not possible and one of the common pitfalls for developers coming to Firebase from a SQL background. We commonly refer to it as "rules are not filters" and you can learn more about it in:

The solution is almost always the same: keep a separate list of the keys of posts that each user has access to.

UserLists:{
  JohnUid: {
    KJHBJJHB: true,
    KhBHJZJjZ: true
  },
  JaneUid: {
    KhBHJBJjJ: true
  }
}

This type of list is often referred to as an index, since it contains references to the actual post. You can also find more about this structure in the Firebase documentation on structuring data.

Upvotes: 1

Related Questions