'Firebase Firestore Security Rules for Users and Associated Documents
I've read other articles and watched the Firebase documentation video, but this isn't making complete sense for me. Would someone please verify that I have setup these Firebase Firestore rules correctly? On the server, there are two main collections (users, data). Information pertinent to the user's account is stored in "users" while data that is pertinent to specific documents the user creates are stored in "data." The documents are named after the user's auth ID that was assigned when the user created their account.
For example:
/users -> document named with userId (containing user's info)
/data -> document named with userId -> all data documents the user has created
I want to allow the user to read, write, and update his own user info in "users," as well as allow the user to read, write, update, and delete any of his documents in "data."
This is what I currently have setup, is it correct?
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /users/{userId} {
allow read, write, update: if request.auth.uid == userId;
}
match /data/{userId}/{documents=**} {
allow read, write, update, delete: if request.auth.uid == userId;
}
}
}
Solution 1:[1]
To have an answer to this question, there's a guide on how to write conditions for Firestore Security Rules that you already followed by modifying your security rules which @Frank mentioned in the comments.
Another common pattern is to make sure users can only read and write their own data:
service cloud.firestore {
match /databases/{database}/documents {
// Make sure the uid of the requesting user matches name of the user
// document. The wildcard expression {userId} makes the userId variable
// available in rules.
match /users/{userId} {
allow read, update, delete: if request.auth != null && request.auth.uid == userId;
// Applies to writes nonexistent user or users that doesn't have an account.
allow create: if request.auth != null;
}
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | RJC |
