Home > Software engineering >  Firebase Getting Data From Maps In Rules
Firebase Getting Data From Maps In Rules

Time:12-19

So I Have A Firestore Database Having The Following Structure where roles are in a map object.

/users
   userid1 
      roles = ["user":true]
   userid2
      roles = ["user":true,"admin":true]
/cars
   car1
     name = "Car 1"
   car2
     name = "Car 2"

Now I am Writing Firebase Rules To make my data secure and only be accessed by admins.

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {

    function getRole(role){
     return get(/databases/$(database)/documents/users/$(request.auth.uid).data.roles[role])
    }
    
    match /cars/{carID} {
      allow read: if request.auth !=null;
      allow create,update,delete: if getRole('admin') ;
    }

I Am Trying To Use The Following Code But Then Its Allowing To Update/Create For Users Having Admin role.
Also Firebase Tells Me A Warning

"Invalid type. Received one of [path]. Expected one of [map]."
So I Wanted To Know Where I am going wrong

CodePudding user response:

You missed one closing bracket is missing in the following line so .data.roles definitely doesn't contain the data of that document:

return get(/databases/$(database)/documents/users/$(request.auth.uid).data.roles[role])
//                                                                  ^

Try refactoring the line as shown below so you can access the data property of the document:

return get(/databases/$(database)/documents/users/$(request.auth.uid)).data.roles[role]
  • Related