darkash
darkash

Reputation: 161

validating read access to specified authenticated user

I'm planning to create a realtime database for a chatting apps with private message channel, is there any specific rules that we can check the authenticated user has access to this room?

my database structure is mostly like this:

{
  "channel": {
       "unique_room_id": {
            "participants": {
                 "uid1": 1537259273000,
                 "uid2": 1537259273000
            }
            "message": {
                 ....
            }
       }
   }
}

Is it possible to use hasChild like how it is used on .write rule or we need to manually validate the reference which means it's not really possible to add more participants to the room?

If possible I want to avoid the latter, thanks in advance

Note:

I'm also open to any alternative structures, and maybe some explanation why it is recommended

Upvotes: 0

Views: 35

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 599876

It's always easiest to use top-level lists instead of nesting multiple entity types in a single list. So remodel your data to:

{
    "participants": {
        "unique_room_id": {
            "uid1": 1537259273000,
            "uid2": 1537259273000
        }
    }
    "messages": {
        "unique_room_id": {
             ....
        }
    }
}

Now you can ensure that only participants in a room can read its messages with:

{
  "rules": {
    "messages": {
      "$roomid": {
        ".read": "root.child('participants').child($roomid).child(auth.uid).exists()"
      }
    }
  }
}

Upvotes: 1

Related Questions