reactjs - 使用 React 查询过滤的 Firestore 数据 - 查询在规则游乐场中完美运行
问题描述
在 Firestore 中查询数据时,我正在努力解决权限错误。在规则游乐场中查询数据时,一切正常。一旦我在我的 React App 中尝试它,我就会收到以下错误:
index.js:1 快照侦听器中未捕获的错误:FirebaseError:缺少权限或权限不足。
在这里你可以看到我在 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]);
这是我关于此查询的 Firestore 安全规则:
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
}
这是firestore中有关此问题的一些测试数据的屏幕截图:
解决方案
在安全规则中将 taskID 更改为 resource.data.id 为我解决了这个问题:
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
}
推荐阅读
- mysql - 如何托管两个具有不同 mysql 版本的“phpmyadmin”?
- python - postgres使用python批量删除查询
- javascript - 为什么 JavaScript 和 HTML 不允许我使用“clear”这个词作为函数的名称?
- c++ - C++ 交换指针 - 不能通过明确定义类型来重现自动类型
- r - 重新排列使用 ggsurv 绘制 Kaplan Meier 曲线的图例顺序
- webpack - 无法构建 Next.js 应用程序并将其部署到 vercel:ModuleNotFoundError:找不到模块:错误:空依赖项(无请求)
- swift - 表格视图的自定义 headerView
- java - Camel 的 endChoice():有什么意义?(不是与 end() 的区别)
- unit-testing - 如何使用 Cmake 在 IOS 模拟器和 android 模拟器上运行 GoogleTest 单元测试?
- css - 背景封面和包含问题,图像无法正确显示