Reputation: 13
I have simple demo project that i downloaded and i am trying to do some simple changes. But i cant figure out how can i set DB rules so only somebody WHO CREATED project can open link with project. Now can open project link everybody who is logged in.
DB RULES FILE:
{
"rules": {
".read": "auth !== null",
".write":"auth !== null",
"users": {
"$uid": {
".write": "auth !== null && $uid === auth.uid",
".read": "$uid === auth.uid"
}
},
"projects": {
".indexOn": ["createdBy"]
}
}
}
I am wondering about adding lines to "projects":
like ".read": "createdBy === auth.uid"
but it does not work. I will be thankfull for any help.
Upvotes: 0
Views: 232
Reputation: 600141
Once you grant a user read or write permission on a node, they have that permission on all data under that node. You cannot take the permission away at a lower level. In the documentation this is mentioned under rules cascade.
At the top-level of your rules, you grant users this permission:
".read": "auth !== null",
".write":"auth !== null",
Given the above explanation, this means that any signed in user has read/write access to the complete database. Any read/write rules you have at lower levels, are simply ignored.
So your first step will be to remove these top-level access rules.
Next up you want to allow users to only be able to read a project if they created that project. In rules that would be :
"projects": {
".indexOn": ["createdBy"],
"$projectid": {
".read": "auth.uid == data.child('createdBy').val()"
}
}
With this a user can read /projects/myproject
if they created myproject
.
Note that with the above rules, no user can read from /projects
, since you don't grant anybody read permission on that node. Firebase security don't filter any data on your behalf, they merely check whether an operation is allowed or not. For more on this, see the documentation on rules are not filters.
If you want the user to be able to run a query that gets them all projects that they have created, you'll need two things:
A query that requests just those project.
ref.orderByChild("createdBy").equalTo(uid)
A rule on /projects
that allows just that query.
"projects": {
".read": "auth.uid != null &&
query.orderByChild == 'createdBy' &&
query.equalTo == auth.uid"
}
So now you only allow a read of /projects
when it's done with a query that only requests the projects the user created themselves. So the security rules and code work together to ensure the user only gets the data they are authorized to read.
For more on this last topic, see the documentation on query based rules.
Upvotes: 1