Search code examples
firebase-realtime-databasefirebase-authenticationfirebase-security

Is it possible to make a Firebase Realtime database node accessible to only 2 specific users?


I'm making a chat app using Firebase.

Since I've no Cloud Functions subscription, I'm using a model of 'chat rooms', where if you enter, you can chat with other people.

A chat room in my model will have only two people.

In database, it means only these two users can have access to this chat room.

This is my Firebase rtdb security file

"chat": {
  "$chatroomid": {
    ".read": "auth != null",
    ".write": "auth != null"
  }
}

This allows only authenticated users to access stuff inside a chat room.

But if you're authenticated and somehow know the chat room id, you can join as a third person.

I want to prevent that.

I know it cannot be done using Firebase features directly. Is there a hack I can apply?


Solution

  • To allow securing access, you'll need to have a place in your database where you store the UIDs that have access to a given room ID. Say that you have this in

    "room_members": {
      "chatroom1": {
        "uidOfUser1": true,
        "uidOfUser2": true
      },
      "chatroom2": {
        "uidOfUser2": true,
        "uidOfUser3": true
      }
    }
    

    With the above structure, you can secure access to the rooms themselves with:

    "chat": {
      "$chatroomid": {
        ".read": "auth != null && 
                  root.child('room_members').child(chatroomid).child(auth.uid).exists()",
        ...
      }
    }
    

    Also see: Best way to manage Chat channels in Firebase for more on modeling this.