Pari
Pari

Reputation: 1493

Firebase Security rule

I have data in firebase in following format -

  "requests" : {
    "-KpPjt5jQZHBalQRxKSK" : {
      "email" : "[email protected]",
      "itemId" : "-KmazkKp5wavdHOczlDS",
      "quantity" : 1,
      "status" : "new"
    },
    "-KpZsw3KHE9oD1CIFQ4R" : {
      "email" : "[email protected]",
      "itemId" : "-Kmb-ZXfao7VdfenhfYj",
      "quantity" : 1,
      "status" : "new"
    }
  }

Every request contains

"email" <- user's email id who has initiated the request.
"itemId" <- id of requested item
"quantity" <- item quantity
"status" <- "new" | "approved" | decline.

I am struggling to write Firebase rule which would:

My current rule is as follows :

{
  "rules": {
    ".read": false,
    ".write": false,
    "items" : {
    ".read": "auth != null",
    ".write": "root.child('roles').child(auth.uid).val() === 'admin'"
    },
    "requests": {
        ".write": "root.child('roles').child(auth.uid).val() === 'admin'", /*Only Admins can update request*/
        "$rId": {
            ".read": "data.child('email').val() == auth.email || root.child('roles').child(auth.uid).val() === 'admin'"/*Request owner and admin can only read the particular request*/
        }
    }
  }
}

I have maintained separate node roles which has { "uid" : "role" }

I am using AngularFire2 to query Firebase in my app.

Sample code to retrieve requests with given status as below

const queryList$ = this.db.list('/requests', {
    query: {
        orderByChild: 'status',
        equalTo: status
    }
})

Thanks Pari

Upvotes: 0

Views: 221

Answers (1)

user6259970
user6259970

Reputation:

I suggest you make the following changes:

In the root of the database create a new object admins

"admins": {
    "<ADMIN_1_UID>": "true",
    "<ADMIN_2_UID>": "true"
}

Then make changes to your security rules like this:

"rules": {
    "admins": {
        ".read": false,
        ".write": false /*This ensures that only from firebase console you can add data to this object*/
    },
    "requests": {
        ".read": "root.child('admins').child(auth.uid).val()",
        ".write": "root.child('admins').child(auth.uid).val()", /*Only Admins can read/update all requests*/
        "$rId": {
            ".read": "data.child('email').val() == auth.email"/*Request owner can read only the particular request*/
        }
    }
}

Upvotes: 2

Related Questions