Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firestore rules on subcollection

I have a "game" collection on firestore with a "levels" sub-collection. I'm trying to set-up the security rules so that you can only access game or level you created.

All documents (games or levels) have an authorId field with the uid of the user that created them. I have try this rule but still got an Missing or insufficient permissions error:

service cloud.firestore {
  match /databases/{database}/documents {    
    match /games/{document=**} {
        allow read, write: if document.data.authorId == request.auth.uid;
    }
  }
}

What am I missing?

I have tried the following rules too with no success:

service cloud.firestore {
  match /databases/{database}/documents {    
    match /games/{game}/levels/{level} {
        allow read, write: if level.data.authorId == request.auth.uid;
    }
  }
}

service cloud.firestore {
   match /games/{game} {
     allow read, write: if game.data.authorId == request.auth.uid;     

       match /levels/{level} {
          allow read, write: if level.data.authorId == request.auth.uid;
       }
    }
}
like image 992
Christophe Le Besnerais Avatar asked Jan 28 '23 22:01

Christophe Le Besnerais


2 Answers

According to the reference documentation, resource is the object that contains the document data that the user is trying to write. You use its data property to get a hold of its field values.

service cloud.firestore {
  match /databases/{database}/documents {    
    match /games/{document=**} {
        allow read, write: if resource.data.authorId == request.auth.uid;
    }
  }
}
like image 73
Doug Stevenson Avatar answered Feb 04 '23 00:02

Doug Stevenson


  match /databases/{database}/documents {
     match /users/{uid} {
      allow read, write: if request.auth.uid == uid;
    }
    match /data/{uid}/temperature
    /{document=**}{
    allow read, write: if request.auth.uid == uid;
    }
    match /data/{uid}/blood_pressure
    /{document=**}{
    allow read, write: if request.auth.uid == uid;
    }
   
  }
}

I did this to access subcollections "blood_pressure" and "temperature" for only authenticated users. It works fine for me.

like image 40
Azhar Ali Avatar answered Feb 03 '23 22:02

Azhar Ali