1
votes

I got firebase database structure like this:

database
   - chat
        -user1
             -user2
                -chat1
                   -message : a
        -user2
             -user1
                -chat1
                   -message : a
             -user3
                -chat1
                   -message : a
         -user3
             -user2
                -chat1
                   -message : a

The question is, how do I prevent user (in case user1) to write chat message to user2 from user3.

example:

Im user1 with javascript command

firebase.database().ref("chat/user2/user3/chat2").set({
     message: "HAHA"
});

Command above said that me as user1 to write new chat for user2 from user3 with message "HAHA". I want to prevent this case with firebase rules. can someone help me how to write the rules and sign in method should I use?

Thank You.

2

2 Answers

1
votes

It looks like you have a structure as follows:

chats
    $recipientUid
        $senderUid
            $chatMessageId

Securing that only the sender can write would be:

{
  "rules": {
    "chat": {
      "$recipientUid": {
        "$senderUid": {
          ".write": "auth.uid == $senderUid"
        }
      }
    }
  }
}

It is more common to store the messages between specific users in a chat-room like structure though. See Best way to manage Chat channels in Firebase

0
votes

Have you try the data structure from firebase documentation? because in your case i think it's kinda impossible to do that, therefore you need to flattened your database structure. Even though you might be able to use wildcards, but it still tough to do since in one client there is only one uid, therefore you can't really write "chat message" in other user's node without knowing their uid at the frontend.

My advice, try to modify the structure by thinking "how chat participant can access their own chat database?" that you can simply use rules that each user can write to their own node in that "chat room" which others can read. CMIIW

regards,

R. M.