Using newData on Updates in Firebase Security Rule

2019-08-21 19:31发布

问题:

I'm having issues using newData within Firebase security rules when doing a update operation.

Here is my data structure:

And here are my rules:

{
  "rules": {
    "videos": {
        "$videoId": {
            "data": {
                "content": {
                    "srcURL": {
                        ".write": "root.child('videos/' + $videoId + '/tokens/' + newData.child('/videos/-1vidid/requestToken').val() + '/read' ).exists()"
                    },
                },
                "meta": {
                    "status": {
                        ".write": "root.child('videos/' + $videoId + '/tokens/testTok/read').exists()"
                    }
                }
            },
            "requestToken": {
                ".write": true,
            }
        }
    }
  }
}

Here is data I'm trying to write via update:

 {
  "videos/-1vidid/data/meta/status": "uploaded", 
  "videos/-1vidid/data/content/srcURL": "https",
  "videos/-1vidid/requestToken": "testTok"
  }

And here are my rules failing when I try to use newData;

Notice it's working when I hardcode in the token ("testTok"), but when I try and use newData it won't clear.

Here are more attempts when I get rid of the "videos" and $videoId ("-1vidid) from the newData childs:

Any idea why newData does not appear to be working on updates?

回答1:

Your relevant rules:

root.child('videos/' + $videoId + '/tokens/' + newData.child('/videos/-1vidid/requestToken').val() + '/read' ).exists()"

The newData variable refers to the new data at the current location. There is no child /videos under the location where you've defined the rule.

I assume you want to start reading from the root. In that case you can either use root, which gives you the existing data at the root, or use newData.parent().parent()... (repeated for however many levels up you need to go) for getting the updated data.