Reputation: 63
In my company
documents, I have a reference field named owner
, which points to a user
document. In the rule, I am trying to check if the authenticated uid is the owner of the company:
match /companies/{companyId} {
allow read: if isOwner(resource.data.owner, request.auth.uid);
}
function isOwner(owner, userId) {
return path('/users/' + userId) == owner;
}
I tried many things but can't figure out how to make this work.
(I know using a string instead of a reference works, but I would rather use a reference)
Upvotes: 6
Views: 1263
Reputation: 3645
The following should enable you to compare on the reference field.
match /companies/{companyId} {
allow read: if /databases/$(database)/documents/user/$(request.auth.uid) == resource.data.owner
}
Note: resource.data.owner NOT request.resource.data.owner
Upvotes: 1
Reputation: 6864
When you construct the path, include this prefix: /databases/(default)/documents/
. It's part of the full path to a document.
match /companies/{companyId} {
allow read: if isOwner(resource.data.owner, request.auth.uid);
}
function isOwner(owner, userId) {
return path('/databases/(default)/documents/users/' + userId) == owner;
}
Upvotes: 12
Reputation: 863
Why not making an ownerId field in the compagny document and check if the authenticated user uid is equal to the value?
service cloud.firestore {
match /databases/{database}/documents {
match /companies/{compagnyId} {
allow read: if isOwner()
}
}
}
function currentData() {
return resource.data
}
function isOwner() {
return currentData().ownerId == request.auth.uid
}
Upvotes: 0