Reputation: 2468
I have 2 collections in my Firestore
users : uid, email periods : periodId, name, owner_id
I need rules for users access only to it's 'users' collection and another that allow read and write to 'periods' collection only if ownerId uid is equal to authentified user id.
I do that
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /users/{userId} {
allow read, write : if request.auth != null && request.auth.uid == userId;
allow create: if request.auth != null;
}
match /periods/{periodId} {
allow read, write : if request.auth.uid == request.resource.data. owner_id;
}
}
}
But it doesn't work.
:(
Upvotes: 1
Views: 1134
Reputation: 83068
You don't share the queries corresponding to these security rules, but we can already identify several problems in your Security rules:
/users/{userId}
you have some overlapping between create
and write
.The following shall solve this problem:
match /users/{userId} {
allow read, update, delete: if request.auth != null && request.auth.uid == userId;
allow create: if request.auth != null;
}
See the doc: "In the case where multiple allow expressions match a request, the access is allowed if any of the conditions is true".
/periods/{periodId}
you need to split between read
and write
.For read access rights, the
resource
variable refers to the requested document, andresource.data
is a map of all of the fields and values stored in the document.For write access rights the
request.resource
variable contains the future state of the document.
(source)
So the following should do the trick (untested):
match /periods/{periodId} {
allow read : if request.auth.uid == resource.data.owner_id;
allow write : if request.auth.uid == request.resource.data.owner_id;
}
I would suggest you watch the following official video on Security Rules. Actually the entire "Get to know Cloud Firestore" video series is a must...
Upvotes: 3