ManOfWar
ManOfWar

Reputation: 121

Firebase rules. validate only certain fields

I want to access my firebase "write" only for the next structure: My structure

The idea is to forbid data writing by any way like this:

User -> email phone username

Upvotes: 1

Views: 356

Answers (1)

André Kool
André Kool

Reputation: 4978

If you want users to be able to have only email, phone and username fields you can use rules simular to this:

{
  "rules": {
    "Users": {
        "$user_id": {
            //Every authenticated user can read
            ".read": "auth != null ",
            // grants write access to the owner of this user account
            // whose uid must exactly match the key ($user_id)
            ".write": "$user_id === auth.uid",
            //This line says the new data must have ATLEAST these children
            ".validate": "newData.hasChildren(['email','phone', 'username'])",   
            //You can add individual validation for email, phone and username here     
            "email": { ".validate": true },
            "phone": { ".validate": true },
            "username": { ".validate": true },
            //This rule prevents validation of data with more child than defined in the 2 lines above (or more if you specify more children)
            "$other": { ".validate": false }
        }
    }
  }
}

For more information about validating your data you can take a look at the firebase security docs.

Upvotes: 3

Related Questions