Home > database >  Uncaught Error in snapshot listener: FirebaseError: [code=permission-denied]: Missing or insufficien
Uncaught Error in snapshot listener: FirebaseError: [code=permission-denied]: Missing or insufficien

Time:01-11

I have the following Firestore listener:

firestore
        .collection('conversations')
        .where('id', '==', 'someId')
        .onSnapshot(callback)

With the following rules set up for the collection:

match /conversations/{document} {
        allow read: if (request.auth.uid in resource.data.userIds) == true;
        allow write: if (request.auth.uid in resource.data.userIds) == true

When I plug in this listener in useEffect() I get the error: @firebase/firestore: Firestore (9.15.0): Uncaught Error in snapshot listener: FirebaseError: [code=permission-denied]: Missing or insufficient permissions.

How come since I am for sure logged in and also the userId of the user logged in is in the userIds array of conversation?

CodePudding user response:

Your security rules are set to allow document reads in the conversations collection where the UID of the authenticated user exists in userIds array, while your query tries to return documents from the same collection where the value of the id field is equal to someId value. Since the rules are set to allow an operation other than the one you perform, the Firebase server rejects that operation, hence the failure.

To create a query that should satisfy your rules, you have to use array-contains operator:

firestore
    .collection('conversations')
    .where('userIds', 'array-contains, uid)
    .onSnapshot(callback)

Where the uid is the UID of the authenticated user.

  • Related