Reputation: 3
I am making shopping app with a cart and storing cart content in database. I set rules so that the user can only read and write on his own cart. here is my code:
final DatabaseReference cartListRef = FirebaseDatabase.getInstance().getReference().child("Carts");
double totalprice = buyCount.getValue() * Double.parseDouble(productPrice.getText().toString());
final HashMap<String, Object> cartMap = new HashMap<>();
cartMap.put("id", productId);
cartMap.put("name", productName.getText().toString());
cartMap.put("price", productPrice.getText().toString());
cartMap.put("date", saveCurrentDate);
cartMap.put("time", saveCurrentTime);
cartMap.put("quantity", Long.toString(buyCount.getValue()));
cartMap.put("discount", "");
cartMap.put("image", imageUrl);
cartMap.put("totalPrice", totalprice);
cartListRef.child("Users").child(mAuth.getCurrentUser().getUid())
.child("Products").child(productId)
.updateChildren(cartMap)
.addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if (task.isSuccessful()) {
Toast.makeText(ProductDetailsActivity.this, "تمت اضافة المنتج اٍلى السلة", Toast.LENGTH_LONG).show();
Intent intent = new Intent(ProductDetailsActivity.this, HomeActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK|Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();
}
}
});
and here are my rules:
{
"rules": {
"Users": {
"$uid": {
".write": "auth != null && auth.uid == $uid",
".read": "auth != null && auth.uid == $uid"
}
},
"Products": {
".read": "auth != null",
".write": "auth != null"
},
"Carts": {
"Users":{
"$uid": {
".read": "auth != null && auth.uid == $uid",
".write": "auth != null && auth.uid == $uid"
}
}
}
}
}
I get error permission denied:
10-03 18:04:06.567 14964-15226/com.cloud.fashenista W/SyncTree: Listen at /Orders/Users/lDQI2pwcuLfStHEfdC9cbfMsYf92 failed: DatabaseError: Permission denied 2020-10-03 18:04:06.753 14964-15226/com.cloud.fashenista W/SyncTree: Listen at /Orders/Users/lDQI2pwcuLfStHEfdC9cbfMsYf92/Products/IVvWWSaVC5YRMZoZs9AO failed: DatabaseError: Permission denied –
I am not sure if this make any difference but there is no child named "Carts" yet
Upvotes: 0
Views: 579
Reputation: 598668
The error message shows that you're trying to read the data at /Orders/Users/lDQI2pwcuLfStHEfdC9cbfMsYf92
, for which no rules are defined - so that read is rejected.
You'll want to update your security rules to also allow the user to read their orders:
{
"rules": {
...
"Orders": {
"Users": {
"$uid": {
".read": "auth != null && auth.uid == $uid"
}
}
},
}
Upvotes: 0