Firestore安全规则和Vuefire

时间:2020-05-25 07:20:59

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

我在这里有以下示例应用程序:Github repo

它在ChatList.vue中使用vuefire

// vuefire firestore component manages the real-time stream to that reactive data property.
firestore() {
    return {
        chats: db.collection('chats').where('members', 'array-contains', this.uid)
    }
},

我现在编写了安全规则来保护数据,但似乎无法使vuefire和安全规则结合使用:

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read, write: if false;
    }
    // THIS IS THE PART I'D LIKE TO REMOVE
    match /chats/{chatId=**} {
      allow read: if request.auth.uid != null;  
    }
    // THIS WORKS AS INTENDED, AND I'D LIKE TO INCLUDE "READ"
    match /chats/{chatId}/{documents=**} {
      allow write: if chatRoomPermission(chatId)
    }
    function chatRoomPermission(chatId) {
      return request.auth.uid in get(/databases/$(database)/documents/chats/$(chatId)).data.members;
    }
  }
}

因此,目标是:使单独的聊天仅对Firestore成员数组中的用户可读和可写。 (当前,我部分实现了此目的,因为所有聊天都可以被任何人读取,但只能对members数组中的用户写入。)

我是否必须重写vuefire组件,才能拥有以下安全规则? (它会显示一条错误消息:由于缺少权限,无法列出聊天记录)

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read, write: if false;
    }
    match /chats/{chatId}/{documents=**} {
      allow read, write: if chatRoomPermission(chatId)
    }
    function chatRoomPermission(chatId) {
      return request.auth.uid in get(/databases/$(database)/documents/chats/$(chatId)).data.members;
    }
  }
}

为完整起见,有效的解决方案是(归Renaud Tarnec所有):

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read, write: if false;
    }
    match /chats/{chatId=**} {
      allow read: if request.auth.uid in resource.data.members; 
    }
    match /chats/{chatId}/{documents=**} {
      allow read, write: if chatRoomPermission(chatId)
    }
    function chatRoomPermission(chatId) {
      return request.auth.uid in get(/databases/$(database)/documents/chats/$(chatId)).data.members;
    }
  }
}

1 个答案:

答案 0 :(得分:1)

由于要检查,因此在安全规则中,如果文档的Array类型的字段中包含给定值(在这种情况下为用户uid),则可以使用{{1} List类型的}运算符。

因此,以下方法可以解决问题:

in
相关问题