0
votes

How can I authenticate that only users with the data contents can write/remove the node? My data structure looks like this:

project-xxxxxxxx
   Messages
      Chat-Record-001
         User1: "B3xUEsPRZ1XhIAhDQo1DEyLZlSX2"
         User2: "PR70j0ou4JdDWf8S5X9h9BUevpo1"
         Message: "This is a test message!"
      Chat-Record-002
         User1: "RiGLv20W7UTFZSCAATOHsk9gDfg1"
         User2: "GG50j0ou4JdDWf8S5X9h9BUevpo1"
         Message: "This is a test message!"
      Chat-Record-003
         User1: "gBTtYUAKCIVZkYGY7gTUNidSIfv1"
         User2: "gmIOwzJwvSOOQc1ADMrHI6phGIv2"
         Message: "This is a test message!"
      Chat-Record-004
         User1: "B3xUEsPRZ1XhIAhDQo1DEyLZlSX2"
         User2: "gmIOwzJwvSOOQc1ADMrHI6phGIv2"
         Message: "This is a test message!"

How should I write the rules so that the user B3xUEsPRZ1XhIAhDQo1DEyLZlSX2 can only write to Chat-Record-001 and Chat-Record-004 while gmIOwzJwvSOOQc1ADMrHI6phGIv2 can only write to Chat-Record-003 and Chat-Record-004. The User1 and User2 strings are from createUserWithEmailAndPassword.

1

1 Answers

1
votes

Something like this should do the trick:

{
  "rules": {
    "Messages": {
      "$chatid": {
        ".write": "data.child('User1').val == auth.uid || data.child('User2').val == auth.uid"
      }
    }
  }
}

Note that this only allows them to update existing messages. If you also want the user to be able to write new messages, as long as their UID is in User1 or User2 it'd be:

".write": "newData.child('User1').val == auth.uid || newData.child('User2').val == auth.uid"