Vik
Vik

Reputation: 9289

firebase realtime database security rules for non user data

So, I have an app where users can order the cakes and do other profile management, the rules looks like below:

{
  "rules": {
    "cakes" : { 
      ".read": true,
      ".write": false
    },
    "users": {
      "$user_id": {
        ".read": "auth != null && $user_id === auth.uid",
        ".write": "auth != null && $user_id === auth.uid"
      }
    }
  }
}

Simply, they mean any one can read the cakes node (but no one can write). And an authenticated user can see or write to his on node.

This is good so far.

Now, my requirement is: When someone places an order through the app then i need to store it to firebase db in a top level node (lets say it orders). The question is what kind of security would be placed on orders node?

In functional definition: The app should be able to create new orders as user checks out, no one except seller should be able to read those orders, only seller should be able to have update access to a order.

Upvotes: 0

Views: 284

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 598847

If you want everybody to be able to write orders, and nobody able to read, the rules are simply the inverse of the ones for cakes:

"rules": {
  "orders" : { 
    ".read": false,
    "$orderId": {
      ".write": true
    }
  },

With this anyone can push new data under /orders. And as long as you use push() to generate the new keys, you're guaranteed that they'll never conflict.

With these rules only a system-level admin can read the data. That is: you can read it in the Firebase Console, or someone can read it if they use the Admin SDK.

You might want to open it up for reading a bit more, e.g. by having the concept of an application-level administrator. Say that your UID is uidOfVik, you could model a list of admins in your database:

admins: {
  uidOfVik: true
}

Now you can allow only admins to read the orders with:

"rules": {
  "orders" : { 
    ".read": "root.child('admins').child(auth.uid).exists()",
    "$orderId": {
      ".write": true
    }
  },

Upvotes: 1

Related Questions