5
votes

I want to delete my current user from Firebase. The authenticated user gets deleted however, I am unable to delete the data for that user in the database. What am i doing wrong?

This is my delete user method....

FIRAuth.auth()?.signIn(withEmail: (emailTextField?.text)! , password: (passwordTextField?.text)!, completion: { (user, error) in
            if error == nil {
                print("User Authenticate!!!")
                let user = FIRAuth.auth()?.currentUser

                user?.delete(completion: { (error) in
                    if error != nil {
                        print("Error unable to delete user")

                    } else {

                        DataService.ds.deleteCurrentFirebaseDBUser()
                        KeychainWrapper.standard.removeObject(forKey: KEY_UID)
                        self.performSegue(withIdentifier: "goToLogin", sender: nil)
                    }
                })

            } else {
                //Password was wrong, unable to authenicate user. Data is not updated
                print("!!!ALERT!!! Unable to authenticate user")
                let alert = UIAlertController(title: "Incorrect Password", message: "Please re-enter your password", preferredStyle: UIAlertControllerStyle.alert)
                alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil))
                self.present(alert, animated: true, completion: nil)
            }

        })

Firebase Rules:

{
"rules": {
    "users": {
      "$uid": {
        ".read": "$uid === auth.uid",
        ".write": "$uid === auth.uid"
      }
    }
  }
}

Database:

App
   -> users
           ->
             4erkjkl543jfe46
                            ->name
                            ->email

ERRORS:

2017-01-21 21:33:10.321704 APP[11582:4102711] [FirebaseDatabase] setValue: or removeValue: at /users/4erkjkl543jfe46 failed: permission_denied

Optional(Error Domain=com.firebase Code=1 "Permission denied" UserInfo={NSLocalizedDescription=Permission denied})

3

3 Answers

5
votes

I'm having the same issue. You are not able to make use of your function deleteCurrentFirebaseDBUser() because the Firebase delete function (if successful) removes the user auth object.

As a result user is not authenticated anymore at the time you want to delete user's data in database with deleteCurrentFirebaseDBUser().

Currently I delete user's data in database before Firebase delete function which is not the ideal solution.

0
votes

We can delete user from both side authentication and database.But before that we need to reauthenticate user first then we get latest token to delete the user.

Here is the pretty code:

  let user = Auth.auth().currentUser
            user?.reauthenticate(with:credential) { error in
                if let error = error {
                    // An error happened.
                    showAlertWithErrorMessage(message: error.localizedDescription)
                } else {
                    // User re-authenticated.
                    user?.delete { error in
                        if let error = error {
                            // An error happened.
                            showAlertWithErrorMessage(message: error.localizedDescription)
                        } else {
                            // Account deleted.
                            let userID = HelperFunction.helper.FetchFromUserDefault(name: kUID)
                            Database.database().reference(fromURL: kFirebaseLink).child(kUser).child(userID).removeValue()

                            try!  Auth.auth().signOut()
                             showAlertWithErrorMessage(message: "Your account deleted successfully...")
                           return
                        }
                    }

                }
            }

100% working in my project and well tested

0
votes

for just to delete a child from Firebase use "removeValue()"

 var db: DatabaseReference!
  override func viewDidLoad() {
        super.viewDidLoad()
        db = Database.database().reference()        
        deleteByID()
    }
 func deleteByID(){
        db.child("YOURID").removeValue()
    }