1

I'm using Firebase to add Users. I also have a Newuser, which is an empty user that can be initialised using an id (the id's come from tags I already made).

Now when a newuser is initialised, Firebase should check if the given tagid is already used in the users table (as a key).

This is what my Users and NewUser data looks like;

enter image description here

This is the Firebase Rule I'm applying which is working in the simulator

{
  "rules": {
    ".read": true,
    ".write": true,
    "newuser": {
      "tagid": {
        ".validate": "root.child('users/'+newData.val()).val() === null"
      }
    }
  }
}

But for some reason I'm able to add this newuser record, using an existing tagid using the Firebase REST API. (with Postman)

halfer
  • 19,824
  • 17
  • 99
  • 186
Miguel Stevens
  • 8,631
  • 18
  • 66
  • 125

1 Answers1

0

The rules you've configured don't quite match the database structure you're working with, so you'll need to try something more like:

{
  "rules": {
    ".read": true,
    ".write": true,
    "newuser": {
      "$pushid" : {
        ".validate": "root.child('users/'+newData.child('tagid').val()).val() === null"
      }
    }
  }
}

In the above rules, the $pushid value will match any key at /newuser/$pushid (for example, your key of -KxhGb7zZy8cZM5Pkntz), and then using newData.child('tagid') will obtain the tagid value from that new data.

Using a $location value in the rules is like a wildcard variable, so it will automatically match any node name at that location. From the $location rules documentation:

A variable that can be used to reference the key of a $location that was used earlier in a rule structure.

When you have a $location in your rules structure, you can use a matching $ variable within your rule expression to get the name of the actual child being read or written.

This is required with your current structure, because when you're adding to your newuser node, your payload looks something like this:

{
    "newuser" {
        "$pushId": {
            "tagid": int
        }
    }
}

You can test your rules in the Rules Simulator in the Firebase database console. In my tests of this, the write was denied when I had /users/1 already in the database and my payload included the value of tagid: 1:

simulator screenshot

Grimthorr
  • 6,856
  • 5
  • 41
  • 53