Home > Software engineering >  Android Studio Firebase realtime database always denies deleting data
Android Studio Firebase realtime database always denies deleting data

Time:06-25

Every time I try to delete user data from the database, it gets rejected. Could anyone help me how to solve it?

The rules I set are:

{
"rules": {
    "admin": {
        ".read": "true",
        ".write": "auth != null"
    },
    "products": {
        ".read": "auth != null",
        ".write": "auth != null"
    },
    "users": {
        ".read": "root.child('users').child(auth.uid).child('account_role').val() == 'admin'",
        ".write": "root.child('users').child(auth.uid).child('account_role').val() == 'admin'",
        "$uid": {
            ".read": "auth.uid == $uid",
            ".write": "auth.uid == $uid"
        }
    }
}

}

My code to delete the data is this:

databaseReference = FirebaseDatabase.getInstance().getReference("users").child(userUid);
    databaseReference.removeValue().addOnSuccessListener(unused -> Log.d(TAG, getString(R.string.data_successful_deleted))).addOnFailureListener(e -> {
        Log.d(TAG, e.getMessage());
        Toast.makeText(DeleteAccountActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
    });

Database

What I can't understand is why I can create, read and update the data, but I can't delete. I can only delete if I put the rules ".write": true.

Can someone please help me?

Thanks

CodePudding user response:

Given the error message and the rules, the only conclusion seems to be that the user is not/no longer signed in when you try to delete their data. I recommend always checking that sort of condition in the code with an assertion, for example like this:

databaseReference = FirebaseDatabase.getInstance().getReference("users").child(userUid);
if (FirebaseAuth.getInstance().getCurrentUser() == null) throw new AssertionError("Trying to delete user data without a current user");
databaseReference.removeValue().addOnSuccessListener(unused -> Log.d(TAG, getString(R.string.data_successful_deleted))).addOnFailureListener(e -> {
    Log.d(TAG, e.getMessage());
    Toast.makeText(DeleteAccountActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
});

If you expected the user to be signed in, it might be good to check when they were signed out, for example with an auth state change listener.

One reason that the user might not be signed in anymore is if you delete the user account, before deleting their data from the database. Deleting an account is a synchronous operation, so you'll want to delete the data from the database before deleting the account.

  • Related