Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.0k 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 Answer

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
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...