My firestore database is structured so that "leagues" is the top collection, and each league contains a field named after each approved userID (with a number value).
Each league also has a subcollection "users" of documents named after each approved userID.
Here is an example firestore query:
FirebaseAuth mAuth = FirebaseAuth.getInstance();
// userId = ABCDEF123 for this example
String userId = mAuth.getCurrentUser().getUid();
FirebaseFirestore firestore = FirebaseFirestore.getInstance();
firestore.collection("leagues").whereLessThan(userId, 99).get();
Can someone please tell me why this rule works:
match /leagues/{league} {
allow read, write: if resource.data.ABCDEF123 != null;
but not this:
match /leagues/{league} {
allow read, write: if resource.data.request.auth.uid != null;
Also, why does this rule work:
//"ZYXWV987" is an example of a league the user is in
match /leagues/{league} {
allow read, write: if exists(/databases/$(database)/documents/leagues/$('ZYXWV987')/users/$(request.auth.uid));
but not this:
match /leagues/{league} {
allow read, write: if exists(/databases/$(database)/documents/leagues/$(league)/users/$(request.auth.uid));
The error I get is "com.google.firebase.firestore.FirebaseFirestoreException: PERMISSION_DENIED: Missing or insufficient permissions"
I am looking to understand how these rules work, and consequently how to implement proper rules for my database!
EDIT:
I now realize that this works (still a WIP):
match /leagues/{league} {
allow read, create, update: if request.auth.uid != null;
//only ever deleting a single league at a time
allow delete: if exists(/databases/$(database)/documents/leagues/$(league)/users/$(request.auth.uid));
match /{docs = **} {
allow read, write: if exists(/databases/$(database)/documents/leagues/$(league)/users/$(request.auth.uid))}
}
and I sort of understand what's going on (I can't use the {league} wildcard when reading/writing potentially more than one league in a request?), but I'm still not exactly sure why?