Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.4k views
in Technique[技术] by (71.8m points)

reactjs - Query filtered Firestore data with React - query works perfectly in rules playground

I am struggling with the a permission error when querying data in firestore. When querying for the data in the rules playground everything works perfectly. As soon as I try it in my React App I get the following error:

index.js:1 Uncaught Error in snapshot listener: FirebaseError: Missing or insufficient permissions.

Here you can see my query in React:

useEffect(() => {
    if (user.id && !user.therapist && user.therapistId) {
      const allowedIDs = getPatientTasksListState.map((item) => item.taskID);
      if (allowedIDs.length > 0) {
        const unsubscribe = db
          .collection("users")
          .doc(user.therapistId)
          .collection("tasks")
          .where("id", "in", allowedIDs)
          .onSnapshot((querySnapshot) => {
            const taskList: any[] = querySnapshot.docs.map((doc) => doc.data());
            setPatientTasksContentState(taskList);
          });
        return () => {
          unsubscribe();
        };
      }
    }
  }, [user, getPatientTasksListState, setPatientTasksContentState]);

Here are my firestore security rules regarding this query:

match /users/{userID}/tasks/{taskID} {
      allow read: if request.auth != null 
                  && userID == request.auth.uid
                  || (request.auth != null && (taskID in get(/databases/$(database)/documents/users/$(userID)/patients/$(request.auth.uid)).data.taskIDs))
      allow write: if userID == request.auth.uid
    }

Here is a screenshot of some test data in firestore regarding this issue:

Screenshot of firestore database data


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Changing taskID to resource.data.id in security rules solved it for me:

match /users/{userID}/tasks/{taskID} {
  allow read: if request.auth != null 
              && userID == request.auth.uid
              || (request.auth != null && (resource.data.id in get(/databases/$(database)/documents/users/$(userID)/patients/$(request.auth.uid)).data.taskIDs))
  allow write: if userID == request.auth.uid
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...