首页 文章

公共和私有字段的Firestore安全规则

提问于
浏览
7

对于Firebase实时数据库的安全规则,公共和私有数据都可以使用如下规则存在于同一树中 .

但是,在使用Firestore时,它似乎无法让我们这样做,因为我们可以检索的数据只是在集合或文档下 . 当公共和私人数据在同一文档中定义并获取带有收集/文档的数据时,如果我们不是所有者,我们会收到私有数据权限不足的错误 .

使用RTDB时,我们可以获取'users / / publicInfo'的数据,因为我们对收集/文档一无所知 .

有什么方法可以使用Firestore来实现RTDB吗?否则,我们应该分开公共/私人收藏?

// rule of Firebase Realtime Database
"users": {
   "$user_id": {
       ".read": "auth.uid === $user_id",
       ".write": "auth.uid === $user_id",

       "private": {
          ".read": "auth.uid === $user_id"   // --- private data
       }

       "public": {
          ".read": "auth !== null";           // --- public data 
       }
   }
}

// Firestore
service cloud.firestore {
  match /databases/{database}/documents {
    match /users/{userId} {

      match /{private=**} {
        allow read, write: if request.auth == userId;
      }

      match /{public=**} {
        allow read, write: if request.auth != null;
      }
    }
  }
}

1 回答

  • 13

    因此,您无法为文档的单独部分提供单独的安全规则 . 您可以阅读整个文档,也可以不阅读 .

    也就是说,如果你想给你的userID文档一个包含公共和私有文档的“公共”和“私有”子集合,那么你可以完全做到这一点,就像你当前设置安全规则一样 .

    match /{private=**} 位为've written it doesn' t表示"Match any subcollection that's called 'private'" . 这意味着,“匹配任何子集合,无论如何,然后将其分配给名为 private ". The " Recursive matching with wildcards的变量”文档部分将更详细地介绍这一点 .

    此外,您需要引用 request.auth.uid 来获取用户的ID .

    所以,你可能想要更像这样的东西:

    // Firestore
    service cloud.firestore {
      match /databases/{database}/documents {
        match /users/{userId} {
          // You'll probably want to add security rules around the user document 
          // itself. For now, though, let's look at our subcollections:
    
          match /private/{anything=**} {
            // Only the user can read documents in their private collection
            allow read, write: if request.auth.uid == userId;
          }
    
          match /public/{anything=**} {
            // Anybody can read documents here, as long as they're signed in
            allow read, write: if request.auth != null;
          }
        }
      }
    }
    

相关问题