正在获取“ FirebaseError:缺少权限或权限不足”。用户具有正确的权限时,由于onsnapshot错误而产生的错误

时间:2019-05-09 18:41:38

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

我正在尝试创建文档参考,设置快照快照监听器,保存文档,然后上传文件,该文件将触发云功能,该功能将对我正在听的文档进行更新。但是onSnapshot给出的权限错误为“ FirebaseError:缺少权限或权限不足”。快照运行一次后(我猜为初始状态)。

我尝试在firebase控制台中运行访问和写入数据的模拟,并且可以正常运行

const db = window.firebase.firestore()
const newBaseRef = db.collection('base').doc()

newBaseRef.onSnapshot(doc => {
  console.log('Current data: ', doc.data())
}, function (error) {
  throw error // THIS ALWAYS GETS HIT
})

newBaseRef.set({
  uid: window.firebase.auth().currentUser.uid,
  createdAt: window.firebase.firestore.FieldValue.serverTimestamp()
})

这是我的安全规则

service cloud.firestore {
  match /databases/{database}/documents {
    match /printset/{document=**} {
      allow read, update, delete: if request.auth.uid == resource.data.uid
      allow create: if request.auth.uid != null;
    }

    match /file/{document=**} {
      allow read, update, delete: if request.auth.uid == resource.data.uid
      allow create: if request.auth.uid != null;
    }

    match /base/{document=**} {
      allow read, update, delete: if request.auth.uid == resource.data.uid
      allow create: if request.auth.uid != null;
    }
  }
}

我不希望错误回调运行

2 个答案:

答案 0 :(得分:0)

使用33 0 0 0 0 0 0 0 *q=112 132 178 223 255 127 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 49 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

/base/{baseId}用于匹配/base/{document=**} base

例如subcollections

要注意的另一件事是正在/base/{someBaseId}/someCollection/{someCollectionId}上调用权限错误

答案 1 :(得分:0)

newBaseRef.set()返回Promise

因此,当调用newBaseRef.onSnapshot()时,newBaseRef.data().uid尚未设置。

请参阅:

您应在newBaseRef.onSnapshot()之后致电Promise.resolve()

const db = window.firebase.firestore()
const newBaseRef = db.collection('base').doc()


newBaseRef.set({
  uid: window.firebase.auth().currentUser.uid,
  createdAt: window.firebase.firestore.FieldValue.serverTimestamp()
}).then(() => {
  newBaseRef.onSnapshot(doc => {
    console.log('Current data: ', doc.data())
  }, function (error) {
    throw error // THIS ALWAYS GETS HIT
  })
})

还有更多

如果只想插入,则应使用newBaseRef.add({})

如果要插入或DeleteInsert(替换所有数据),则应使用newBaseRef.set({})

如果要插入更新或更新,则应使用newBaseRef.set({}, {merge, true})

如果只想更新,则应使用newBaseRef.update({})

如果要插入更新或更新,则将安全规则更改为以下设置。

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

    match /printset/{document=**} {
      allow read, update, delete: if request.auth.uid == resource.data.uid
      allow create: if request.auth.uid != null;
    }

    match /file/{document=**} {
      allow read, update, delete: if request.auth.uid == resource.data.uid
      allow create: if request.auth.uid != null;
    }

    match /base/{document=**} {
      allow read, delete: if request.auth.uid == resource.data.uid
      allow update: if resource == null || request.auth.uid == resource.data.uid
      allow create: if request.auth.uid != null;
    }
  }
}