Reputation: 622
I have been trying to improve the Firestore rules that secure the database for a few days now. I only seems to lock everyone out with every edit. The rules I use now are the basic rules found in the Firestore documentation. Which are:
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read, write: if request.auth.uid != null;
}
}
}
But I would like to extend the security a bit to tighten up the edit rules. My database looks like this:
Users (collection) > User (document) > User specific data
What I would like to have is that every authenticated user can read all the data, but only the user a document belongs to (by unique user id) may edit/add/delete their data.
I hope one of you could point me in the right direction, as I seem to not get any wiser from the official documentation.
Update: How I integrated Firestore in my Android app.
user = FirebaseAuth.getInstance().getCurrentUser();
db = FirebaseFirestore.getInstance().collection("users");
CollectionReference colRef = db.document(user.getUid()).collection("watched");
colRef.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
@Override
public void onComplete(@NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
ArrayList<Movie> tempItems = new ArrayList<>();
for (DocumentSnapshot document : task.getResult()) {
// Handle data
}
} else {
Log.d(TAG, "Error getting documents: ",task.getException());
}
}
});
Upvotes: 0
Views: 372
Reputation: 622
I apparantly read the documentation about the resource.data wrong. I had to add the author_id field myself. I did not know this, but once I added this it worked like a charm!
Upvotes: 1
Reputation: 11344
You can write a rule to make sure that the uid of the requesting user matches the author_id
field of the document:
service cloud.firestore {
match /databases/{database}/documents {
match /Users/{User} {
allow read: if request.auth.uid != null;
allow create, update, delete: if request.auth.uid == resource.data.author_id;
}
}
}
Upvotes: 0