文档字段的Firestore规则

Gen*_*erd 12 firebase google-cloud-firestore firebase-security-rules

我正在Firestore中努力为文档设置安全规则。使用RTDB可以为特定对象属性设置规则,而我正尝试使用Firestore进行设置。

RTDB代码:

"users": {
    ".read": true,
    ".indexOn": ["profile/name"],
    "$uid": {
        ".read": "auth != null",
        ".write":
            "$uid === auth.uid && !data.exists()",
        "profile": {
            "birthday": {
                ".write": "$uid === auth.uid"
            },
            "name": {
                ".write": "$uid === auth.uid"
            },
            "banned": {
                ".write": "root.child('admins').child(auth.uid).exists()"
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

在Firestore中的相同代码下方:

service cloud.firestore {
    match /databases/{database}/documents {
        match /users/ {
            allow read
            match /{$user} {
                allow read: if request.auth.uid != null
                allow write: if request.auth.uid == request.resource.id &&  exists(/databases/$(database)/documents/users/$(request.resource.id)) === false

                match /birthday {
                    allow write: if request.auth.uid == request.resource.id
                }
                match /name {
                    allow write: if request.auth.uid == request.resource.id
                }
                match /banned  {
                    allow write: get(/databases/$(database)/documents/users/$(request.auth.uid)).data.userType > 3
                }

            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

当我为子集合编写安全规则时,它工作正常。但是对于文档字段,它不起作用。这是不可能的,还是path比赛参考中有特殊的细分?该文档没有对此进行任何说明。

Jas*_*man 5

您可以通过检查request.resource.data属性来执行此操作。如本节文档所示。您只需要匹配文档级别。您使用if条件检查字段规则。

但是,您无法控制对单个字段的读取访问。用户可以阅读整个文档,也可以不阅读。如果需要存储私有数据,请考虑将其添加到用户文档的子集合中。

这是一个例子

service cloud.firestore {
  match /databases/{database}/documents {
    // Make sure all cities have a positive population and
    // the name is not changed
    match /cities/{city} {
      allow update: if request.resource.data.population > 0
                    && request.resource.data.name == resource.data.name;
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

  • 这可能适用于写操作,但不适用于阅读。它还会创建更多的意大利面条代码。 (3认同)
  • 使用Cloud Firestore,您不能限制单个字段的读取。您只能允许/禁止阅读文档。但是,可以控制各个字段的写入。如果要存储私人数据,则应向用户文档添加一个可以包含该私人数据的集合。我通常有3个集合,“ public”,“ private”(可由用户访问)和“ internal”。您也可以添加一个admin集合。 (2认同)