As of now I have below rules defined for my customer table.
{
"rules": {
"customers":{
".read": "auth != null",
".write": "auth != null",
"$CID":{
"UserId":{
".validate": "(data.exists() && data.val() == newData.val()) || newData.val() == auth.uid"
},
"CustomerName":{
".validate": "newData.isString() && newData.val().length < 100"
},
"CustomerCode":{
".validate": "newData.isString() && newData.val().length<4"
},
"CustomerLimit":{}
}
}
}
}
As you can see, that I have UserId under customers branch which would hold the value of the logged in user id. Each authenticated User can create customers which basically belongs to that particular user and read/get only those customers which was created by him.
But now when I read from database as below:
DatabaseReference mDatabaseReference= FirebaseDatabase.getInstance().getReference("customers");
This retrieves all the data under the customers. So I was thinking to add some read rule to the existing one as in
"rules": {
"customers":{
".read": "auth != null && auth.uid=loggedInUserId", //something like this
.....
}
}
But I just couldn't find anywhere how it can be done here in the rules.
As an option I tried to write a query on UserId which always returned null even after passing valid logged in UserId.
Query query=mDatabaseReference.equalsTo(loggedInUserId,"UserId");
This method which I don't prefer as it would be best written in rules. Hope someone knows how we can add rules for this requirement.