2

I was learning through official doc for security rules, but i cant make it work.

in my collections users under document user have some map values, one of them is role: "guest". role values can be "guest" or "superAdmin"

i want access to /users only when role == "superAdmin"

here is what i tried

service cloud.firestore {
  match /databases/{database}/documents {
    match /users/{userId} {
        allow read: if get(/databases/$(database)/documents/users/$(userId)).data.role == "superAdmin";
    }
  }
}

and got error when i log in as superAdmin

ERROR Error: Missing or insufficient permissions.

i believe i followed docs correctly. and found a similar question in SO where says some bug specific to evaluating nested fields in queries. But i have no nested queries. am i doing anything wrong here?

here is my firestore look

enter image description here

Please help.

Hareesh
  • 6,770
  • 4
  • 33
  • 60
  • looks like a bug in firestore, its still in beta. found an alternative solution [here](https://stackoverflow.com/questions/46629170/firestore-security-rule-get-not-work). waiting for a correct answer. – Hareesh Oct 17 '17 at 13:50

2 Answers2

9

Instead of using get(), since you're fetching the document at the location you're reading from, simply address it using resource (which is the prefetched document at that location):

service cloud.firestore {
  match /databases/{database}/documents {
    match /users/{userId} {
        allow read: if resource.data.role == "superAdmin";
    }
  }
}

Only use get() if you're going to a different collection to fetch data.

Mike McDonald
  • 15,609
  • 2
  • 46
  • 49
0

I think the part that breaks it is allow read: if get(/databases/$(database)/documents/users/$(userId)). Here you are comparing the owner of the document, not the one requesting it. Try replacing userID with request.auth.uid.

Alexander Vitanov
  • 4,074
  • 2
  • 19
  • 22
  • you said it right. i tried it and waited 10 mins, but unfortunately same error. `if get(/databases/$(database)/documents/users/$(request.auth.uid)).data.role == "superAdmin"` is it correct? – Hareesh Oct 17 '17 at 12:53