I have a users collection where I store user data such as name, email etc and another collection for blocked users. I want to allow a user to read its own document and the document of the users that he/she has not blocked. I have implemented security rules but somehow a user cannot even read its own document. Can someone help?
Users Collection
users { // name of collection
a1 { // this is firebase id serving as document name
name: "abc",
email: [email protected]
}
a2 { // this is firebase id serving as document name
name: "efg",
email: [email protected]
}
a3 { // this is firebase id serving as document name
name: "hij",
email: [email protected]
}
a4 { // this is firebase id serving as document name
name: "klm",
email: [email protected]
}
}
Blocked Collection
blocked { // name of the collection
a1 { // name of the document
a2 : 1, // this means a1 has blocked a2
a4 : 1 // this means a1 has blocked a4
}
}
Security Rules
service cloud.firestore {
match /databases/{database}/documents {
match /users/{userId} {
allow read: if request.auth.uid != null
&& get(/databases/$(database)/documents/blocked/$(request.auth.uid)).userId != 1;
}
match /blocked/{fid} { // blocked collection/fid == owner firebase id
allow read: if request.auth.uid == fid;
}
}
}
Code
DocumentReference docref = Firestore.instance.collection("users").document(user.uid);
return docref.get();
get()
incorrectly in the rules. It returns a Resource object that has a data property where all the field values live. Note that accessing a property that doesn't exist is an error and will cause the rule to always reject. I also suggest using boolean values instead of numbers to indicate users that are blocked. firebase.google.com/docs/reference/rules/rules.firestore#.get – Doug Stevensonget()
you mentioned could be solved with just wide open read rules too. I do believe my answer should get you what you described in this post (the primary problem being what Doug described), but it may not actually be what you need. – robsiemb