Victor Molina
Victor Molina

Reputation: 2641

Firebase Uncaught Error in onSnapshot: [FirebaseError: Missing or insufficient permissions.]

I have a firestore listener on my app (onSnapshot), and when I created it I get the error

Uncaught Error in onSnapshot: [FirebaseError: Missing or insufficient permissions.]

useEffect(() => {
    const { firebase } = props;

    // Realtime database listene
    const unsuscribe = firebase
      .getDatabase()
      .collection("posts")
      .doc(firebase.getCurrentUser().uid)
      .collection("userPosts")
      .onSnapshot((snapshot) => {
        let changes = snapshot.docChanges();
        changes.forEach((change) => {
          if (change.type === "added") {
            console.log(change.doc.data());
            // TODO - Add the new post to the posts list
          }
        });
      });

    return () => {
      // Detach the listening agent
      unsuscribe();
    };
  }, []);

I have been checking my permissions but it seems to be good:

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    function isSignedIn() {
      return request.auth.uid != null;
    }
    
    function isSameUser(userId) {
        return request.auth.uid == userId;
    }
   
    match /posts/{userId}/userPosts {
       allow read: if true;
       allow write, update, delete: if isSignedIn() && isSameUser(userId);
    }
  }
}

As you can see, the document (in /posts/{userId}/userPosts) that represents a user post will only be created if the user is signed in and if is the same user... Any ideas about what is wrong here?

Thank you.

Upvotes: 0

Views: 1620

Answers (1)

Victor Molina
Victor Molina

Reputation: 2641

Okey I have the solution. I write it here because it might be useful for someone in the future.

Just do:

match /posts/{userId}/userPosts/{document=**} {
   allow read: if true;
   allow write, update, delete: if isSignedIn() && isSameUser(userId);
}

and will work fine.

Upvotes: 1

Related Questions