簡體   English   中英

Nuxt + Firebase FirebaseError:缺少權限或權限不足

[英]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 這是我當前的數據庫結構:

Firebase 數據結構

關於為什么該規則沒有按預期工作的任何想法?

我已經解決了這個問題,從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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM