Allow only admins to write data - Firebase Realtime Database - Security Rules

Viewed 464

I want to give .write permission only to those authenticated users with isAdmin:true Below is the structure of Database. In the clients(users) node uid is the Firebase generated auth uid.

{
  "clients" : {
    "-M8bGQaB....." : {
      "isAdmin" : true,
      "uid" : 5gvR1GzT...
     }
   },
  "products" : {
    "-M81GzT....." : {
     "productName": "Product 1"
      },
    "-M81GzT....." : {
     "productName": "Product 2"
    }
}
1 Answers

With your current data structure there is no way to look up the user profile in the security rules, as security rules can't search across all users.

That's why the proper data structure to store user uses their UID as the key. In your case that'd look like:

  "clients" : {
    "5gvR1GzT..." : {
      "isAdmin" : true
     }
   },

With this JSON, you can then only allow users to write a product when the isAdmin property for their UID is set to true with:

{
  "rules": {
    "products": {
      "$productid": {
        ".write": "root.child('clients').child(auth.uid).child('isAdmin').val() == true"
      }
    }
  }
}
Related