Reputation: 1167
I have a collection of documents. Each document has child uid
which is a reference to the owner. Exemplary document:
{
"uid": "slfjs092320i3jf023jf",
"content": "Example"
}
I want to store them under /documents
collection and allow only users with matching uid to store and retrieve them. I created the following rules:
{
"rules": {
"documents": {
"$documentId": {
".read": "data.child('uid').val() === auth.uid",
".write": "newData.exists() && newData.child('uid').val() === auth.uid || data.exists() && data.child('uid').val() === auth.uid",
".indexOn": ["uid"]
}
}
}
}
Unfortunatelly when I want to retrieve user's documents I receive permission denied. To retrieve documents I use:
export default getUserDocuments = () => {
const userUid = firebase.auth().currentUser.uid;
return firebase.database()
.ref('/documents')
.orderByChild('uid')
.equalTo(userUid)
.once('value');
};
How do I query user's documents? I guess the permission denied is related to read restriction required to perform the query.
Upvotes: 0
Views: 612
Reputation: 2534
Have a look on query based rules.
Rules are not filters, as Frank said, and he is right, but you can make some queries to works and achieve something similar to what you were looking for with this kind of stuff :
baskets": {
".read": "auth.uid != null &&
query.orderByChild == 'owner' &&
query.equalTo == auth.uid" // restrict basket access to owner of basket
}
And then, this will work :
db.ref("baskets").orderByChild("owner")
.equalTo(auth.currentUser.uid)
.on("value", cb)
And this, won't :
db.ref("baskets").on("value", cb)
Upvotes: 0
Reputation: 598765
Firebase Database enforced read permission when you attach a listener. To be able to read from /documents
, you will need to have read permission on /documents
. Since that isn't the case with your security rules, the listener is rejected.
This may be counter-intuitive initially, and means that security rules cannot be used to filter data in the way you are trying. This is known as rules are not filters in the documentation, and has been the topic of many previous questions. I recommend you check out some of those, and report back if you have more questions.
Upvotes: 1