0
votes

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:

  • allow authenticated user to access/read only requests which are raised by him/her.
  • allow admin user to read/update all requests.

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

1
A lot of this depends on how you implement the concept of admin users. Please edit your question to include two code snippets: 1) the minimal code for an operation that should be allowed, 2) the minimal code for an operation that should be disallowed. It also would be good to see your existing (minimal) security rules for the requests. - Frank van Puffelen
Thanks. I have added my existing security rules. - Pari

1 Answers

2
votes

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*/
        }
    }
}