Firestore rules for document field

大兔子大兔子 提交于 2019-11-28 02:55:47

问题


I'm struggling within Firestore to set security rules for a document. With the RTDB is was possible to set rules for a specific object property and I'm trying to do the same with Firestore.

RTDB Code:

"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()"
            }
        }
    }
}

Below the same code in 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
                }

            }
        }
    }
}

When I'm writing security rules for a subcollection it's working fine. But for a document field it's not working. Is this not possible or is there a special path segment in the match reference? The documentation doesn't state anything about this.


回答1:


You can do this by checking the request.resource.data property. As shown in this section of the documentation. You only need to match the document level. You check the field rules with an if condition.

However, you are unable to control read access to individual fields. A user can either read a whole document or not. If you need to store private data, consider adding this to a sub-collection of the user document.

Here is an example

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;
    }
  }
}


来源:https://stackoverflow.com/questions/49919641/firestore-rules-for-document-field

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!