Ad

Allowing Users To Read Sub Collection If User ID Is In Doccument

Been playing with firebase rules for a while now and I am unable to get my desired result

Database:

db

and then the sub-collection "chats" contains all of the messages

What I would like is so that user "3" can't come in and join the chat and that firebase rules would only allow the two users in that have their UID in the document to proceed to the "chats" subcollection restrict access based on UID's

previous attempt

    service cloud.firestore {
  match /databases/{database}/documents {

    match /Messages/{MessageId} {
        allow write, read: if isOwner(userId);
    }

    function isOwner(userId) {
        return request.auth.uid == resource.data.uid;
    }
  }
}

as you can see im pretty lost if you could point me in the right direction that would be great!

Ad

Answer

I think you're looking for

service cloud.firestore {
  match /databases/{database}/documents {

    match /Messages/{MessageId} {
        allow write, read: if isOwner();
        match /chats/{id} {
            allow write, read: if isParticipant();
        }
        function isParticipant() {
            return isOwner() ||
                get(/databases/$(database)/documents/Messages/$(MessageId)).data[2]
                    == request.auth.uid
        }
    }

    function isOwner() {
        return request.auth.uid == resource.data.uid;
    }
  }
}

This allows the read/write access to a message, if current user is either the owner, or the other participant in this chat.

Ad
source: stackoverflow.com
Ad