0
votes

I'm new to using Firebase rules but I have read through the documentation. I know that a top most rule takes priority but a validate rule should still run. My problem is I'm trying to create unique usernames, but whenever I simulate an insert the validate is never run. The validate rule I want to create should check the collection of usernames and see if it already exists, if it does then the write should fail. I have posted my data structure and rules below. The fire_uid is a placeholder for the uids generated in fire base

Current Database

{
  "userProfile" : {
    "fire_uid" : {
      "email" : "[email protected]",
      "name" : "matt maxton"
    },
    "fire_uid" : {
      "email" : "[email protected]",
      "name" : "victor tictor"
    }
  },
  "usernames" : {
    "testcaseusername" : "fire_uid"
  }
}

Firebase Rules

{
    "rules": {
        "$uid": {
            ".write": "auth !== null",
            ".read": "auth !== null && auth.provider === 'password'",
            "usernames": {
                ".validate": "!root.child('usernames').child(newData.val()).exists() ||root.child('usernames').child(newData.val()).val() == $uid "
            }
        }
    }
}

Simulation Test( I made sure that the user id in this test is different from the uid used to create the entry in the Database

location : /usernames

Json Data: {"testcaseusername": "fire_uid" }

1

1 Answers

0
votes

Your validation rule is on /$uid/usernames. But your JSON has /userProfile/$uid/name. To validate the user name in the latter, use:

{
    "rules": {
      "userProfile":
        "$uid": {
            ".write": "auth !== null",
            ".read": "auth !== null && auth.provider === 'password'",
            "name": {
                ".validate": "!root.child('usernames').child(newData.val()).exists()
                             ||root.child('usernames').child(newData.val()).val() == $uid "
            }
        }
      }
    }
}