[英]Nuxt + Firebase FirebaseError: Missing or insufficient permissions
仅当文档具有使用 firebase 登录的当前用户的用户 ID 时,我才尝试读取文档集合。 这是我的数据库规则:
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /todos/{todoId} {
allow read: if isLoggedIn() && request.auth.uid == resource.data.userId;
allow create: if isLoggedIn() && request.auth.uid == request.resource.data.userId;
allow update, delete: if isLoggedIn() && request.auth.uid == resource.data.userId;
}
function isLoggedIn() {
return request.auth != null;
}
}
}
创建文档不是问题,而是阅读它们。 这是我的 function 检索数据:
getData () {
this.$fire.firestore.collection('todos').get()
.then((doc) => {
if (doc.exists) {
console.log('Document data:', doc.data())
} else {
// doc.data() will be undefined in this case
console.log('No such document!')
}
}).catch((error) => {
console.log('Error getting document:', error)
})
}
似乎 resource.data.id 规则没有指向 todo userId,因此我得到FirebaseError: Missing or enough permissions 。 这是我当前的数据库结构:
关于为什么该规则没有按预期工作的任何想法?
我已经解决了这个问题,从firestore获取数据的方法不完整,解决方案在firebase文档中。
进行数据检索的正确方法是使用where约束:
getData () {
this.$fire.firestore.collection('todos').where('userId', '==', this.user.uid).get()
.then((docs) => {
if (docs) {
// console.log('Document data:', docs.data())
docs.forEach((doc) => {
console.log(doc.data())
})
} else {
// doc.data() will be undefined in this case
console.log('No such document!')
}
}).catch((error) => {
console.log('Error getting document:', error)
})
}
Firebase 安全规则不过滤数据。 相反,它们只是确保您执行的任何操作都符合您设置的规则。
因此,您的这条规则说用户只能阅读具有自己 UID 的文档:
allow read: if isLoggedIn() && request.auth.uid == resource.data.userId;
但随后您的代码继续并尝试读取所有文档:
this.$fire.firestore.collection('todos').get()
由于您的规则不允许读取所有文档,因此该操作被拒绝。
要允许该操作,请确保您的读取操作符合您的规则,并且仅请求 UID 匹配的文档:
let uid = ...
this.$fire.firestore.collection('todos').where(userId, "==", uid).get()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.