Ethan SK
Ethan SK

Reputation: 888

How to only allow one field to be written in firebase realtime database security rules?

I want write access to only 1 field that I decide in security rules. I tried with this :

 "users":{  
     ".read":"auth !== null", 
       "$user_id" : {
        ".write":"newData.children.size() === 1 newData.hasChild('isConnected') && newData.child('isConnected').isBoolean()", // i know this is a little weird, but for prescence, it needs to be able to write to the user enpoint even if the token expired
      }

But I get this error: No such method/property 'children'.

Upvotes: 0

Views: 613

Answers (1)

Doug Stevenson
Doug Stevenson

Reputation: 317362

Define the rule on the specific field itself, not the parent. Make sure that the parent does not allow writes anywhere, then enable writes for individual fields on their own terms:

"users":{  
  ".read": "auth !== null", 
  "$user_id": {
    "isConnected": {
      ".write": "newData.isBoolean()"
    }
  }
}

If you're comparing security rules with Firestore (which does let you get a list of fields in a document), you should know that Firestore doesn't let you express individual rules per field, which is why you have to check for them individually in the rule for the overall document. Realtime Database does let you specify rules for arbitrarily nested children, so you can take advantage of that here.

Upvotes: 1

Related Questions