首页 > 解决方案 > 安全规则 Firestore

问题描述

我正在尝试保护我在 Firestore 中的数据。我已经阅读了文档并观看了一些视频,但我仍然很难做到正确。

我构建的是一个项目应用程序。使用这样的数据结构:

"School": {
    school1:
    school2: {
        "Users": {
            userId: {
                "SchoolName": "school2"
            }
        }
        "Projects": {
            projectId: {
            }
       }
    }
}

只有经过身份验证的用户才能读取和写入整个数据库,并且只有同一学校的用户才能读取和写入该学校的数据。例如,只有 school2 中的用户可以将项目添加到 school2。

我尝试过这样的事情,但没有奏效

service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read, write: if request.auth.uid != null;
    }
    match /School/{schoolName} {
        allow read, write: if get(/databases/{database}/documents/School/$(schoolName)/Users/{userId}).data.SchoolName[(schoolName)]
    }
  }
}

有人可以告诉我如何做到这一点,也许对如何考虑安全规则有一些很好的解释。非常感谢您!

标签: google-cloud-firestorefirebase-security

解决方案


你只犯了一个错误,替换这一行:

 allow read, write: if get(/databases/{database}/documents/School/$(schoolName)/Users/{userId}).data.SchoolName[(schoolName)]

有了这个 :

 allow read, write: if get(/databases/{database}/documents/School/$(schoolName)/Users/{request.auth.uid}).data.SchoolName == "school2"

推荐阅读