Im new to Firebase Firestore and I want to define the security Rules. My datastructure is very simpel as you can see in the picture.
Every user has his own document with subcollections. I want that a user can only read and write his own documents (including documents in subcollection), so my rules should look something like this:
service cloud.firestore {
match /databases/{database}/documents {
match /users/{userId} {
allow read, update, delete: if request.auth != null && request.auth.uid == userId;
allow create: if request.auth != null;
}
}
}
With this code, will the user be able to read and write documents in subcollection too? Is there anything else thats important what I need to add to the security rules or is this all I need to do?
The match
statements in your rules control what those rules apply to. In your case the:
match /users/{userId} {
This rule applies to the documents in the users
collection itself, and not to the documents in subcollections.
If you want to apply the same rule to all subcollections too, you can use a recursive wildcard match (=**
) like this:
match /users/{userId=**} {
Not with this, the same rule apply to the documents in the users
collection, and all subcollections/documents under there.
You can also more granularly control access to subcollections, by nesting the match
clause for them. For example, say you have a subcollection messages
, and you only want to allow the user read access to that subcollection, you can accomplish that with these rules:
match /users/{userId} {
allow read, update, delete: if request.auth != null && request.auth.uid == userId;
allow create: if request.auth != null;
match /messages/{messageId} {
allow read: if request.auth != null && request.auth.uid == userId;
}
}
As you can see, we're repeating the conditions verbatim here, so it's common to capture conditions in custom named functions to improve readability and maintainability.