Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firebase firestore rules, read only when document contain specific value

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.

like image 850
Hareesh Avatar asked Mar 15 '26 16:03

Hareesh


1 Answers

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.

like image 175
Mike McDonald Avatar answered Mar 20 '26 00:03

Mike McDonald



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!