【问题标题】:Firebase security rules throwing error for Firestore .where() snapshotFirebase 安全规则为 Firestore .where() 快照引发错误
【发布时间】:2019-08-26 18:32:45
【问题描述】:

得到错误:

onSnapshot 中未捕获的错误:FirebaseError:缺少权限或权限不足。

这里是被调用的函数:

let unsubscribeUserThings
export function getUserThings(user, state) {
    unsubscribeUserThings = firebaseDB.collection("things").where("user", "==", user)
        .onSnapshot(function(querySnapshot) {
            var things = {}
            querySnapshot.forEach(function(doc) {
                things[doc.id] = doc.data()
            })

            state.setState({
                things: things
            })
        })

}
export function stopListeningToUserThings() {
    // Stop listening to changes
    unsubscribeUserThings()
}

Firebase 安全规则是:

service cloud.firestore {
  match /databases/{database}/documents {

    // FUNCTIONS

      // True if the signed in user is the thing's user
      function isThingUser() {
        return request.auth != null && request.auth.uid != null && resource.data.user == request.auth.uid
      }

      // True if the signed in user is the thing's owner
      function isThingOwner() {
        return request.auth != null && request.auth.uid != null && resource.data.owner == request.auth.uid
      }

    // RULES

      // Things
      match /things/{thingID} {
        allow create: if true
        allow read, update: if isThingUser() || isThingOwner()
      }
  }
}

奇怪的是它仍然正确显示所有内容,只是触发了这个错误。为什么会这样?我会忽略它吗?

【问题讨论】:

  • 一个查询不能同时给出结果并产生权限错误。它必须是其中之一。我能想到的唯一会同时产生结果和错误的情况是,当数据发生变化时 after 给出了第一组结果,但 before 侦听器是取消订阅,这会改变原始查询的有效性。
  • 谢谢你,@DougStevenson——你的回答为我指明了正确的方向!请参阅下面的解决方案

标签: javascript firebase google-cloud-firestore firebase-security


【解决方案1】:

Firebase 规则一切正常——它最终被另一个 onSnapshot 调用拉取,以监听“事物”文档的子集合,即子集合“部件”。添加了一个嵌套匹配语句以授予它读取 /things/{thingID}/parts/{partID} 的权限,现在一切正常!

service cloud.firestore {
  match /databases/{database}/documents {

    // FUNCTIONS

      // True if the signed in user is the thing's user
      function isThingUser() {
        return request.auth != null && request.auth.uid != null && resource.data.user == request.auth.uid
      }

      // True if the signed in user is the thing's owner
      function isThingOwner() {
        return request.auth != null && request.auth.uid != null && resource.data.owner == request.auth.uid
      }

  // RULES

    // Things
    match /things/{thingID} {
      allow create: if true
      allow read, update: if isThingUser() || isThingOwner()

      match /parts/{partID} {
        allow read, write: if true
      }
    }
  }
}

【讨论】:

    猜你喜欢
    • 2021-04-09
    • 1970-01-01
    • 2018-01-25
    • 1970-01-01
    • 1970-01-01
    • 2020-07-03
    • 2020-11-27
    • 2020-08-24
    • 1970-01-01
    相关资源
    最近更新 更多