Weizen
Weizen

Reputation: 263

Firebase database rules parents shadowing children

I've got a problem, and i tried everything, but I couldn't find a solution. I've got a firebase database like this. Chats:

-chats
--0
---title=""
---lastmsg=""
---timestamp=""
--1
---title=""
---lastmsg=""
---timestamp=""

And then:

-members
--0
---uid0="true"
---uid1="true"
--1
---uid2="true"
---uid3="true"

Now, i have this java code to process the list.

            FirebaseDatabase database = FirebaseDatabase.getInstance();
            DatabaseReference myRef = database.getReference("chats");
             myRef.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
            // This method is called once with the initial value and again
            // whenever data at this location is updated.

            Iterable<DataSnapshot> children = dataSnapshot.getChildren();

            for (DataSnapshot child : children) {
                String titolo = (String) child.child("titolo").getValue();
                String ultimomsg = (String) child.child("ultimomsg").getValue();
                Long timestamp = (Long) child.child("timestamp").getValue();
                Log.w(TAG, "Title is: "+ titolo);
                CHATITEMS.add(new DummyItem(child.getKey(), titolo, ultimomsg, timestamp));
            }
            RecyclerView recyclerView = (RecyclerView) view;
            recyclerView.setAdapter(new MyPersonRecyclerViewAdapter(CHATITEMS, mListener));
        }

Now, i want the user to be able to read the chats nodes only if the userid it's on the node member/chatnumber/userid. I tried in several ways to set a rule without success. Can anyone point me in the right direction? Thank you

Upvotes: 0

Views: 158

Answers (1)

Pat Needham
Pat Needham

Reputation: 5918

The Firebase user security docs provide a good instructional starting point to help understand how the different rules should be structured to secure data at specified paths. In your case, you want /chats/$chat_id path readable based on whether logged-in user's uid is present at /members/$chat_id/$user_id. To accomplish this, your security rules should be like:

{
  "rules": {
    "chat": {
      "$chat_id": {
        ".read": "root.child('members/' + $chat_id + '/' + auth.uid).exists()",
        ".write": false
      }
    }
  }
}

You might want the .write rule to be false, in case you have a Cloud function write to that database path via the Admin SDK, so you can update to the appropriate values depending on when new chat messages are sent.

Upvotes: 1

Related Questions