How to check if user needs to re-authenticate using Firebase Authentication

Swift 3 I had to do this yesterday when trying to delete a user. One thing to note is FIRAuthErrorCodeCredentialTooOld is now FIRAuthErrorCode.errorCodeRequiresRecentLogin

What I did was trigger a UIView to ask for log in details if that error is thrown. Since I was using email and password, that's what I collected from the user in my example.

private func deleteUser() {
  //get the current user
  guard let currentUser = FIRAuth.auth()?.currentUser else { return }

  currentUser.delete { (error) in
    if error == nil {
      //currentUser is deleted
    } else {
      //this gets the error code
      guard let errorCode = FIRAuthErrorCode(rawValue: error!._code) else { return }
      if errorCode == FIRAuthErrorCode.errorCodeRequiresRecentLogin {
        //create UIView to get user login information
        let loginView = [yourLoginUIViewController]
        self.present(loginView, animated: true, completion: nil)
      }
    }
}

Once I had the login information I ran this function to reauthenticate the user. In my case I ran it the loginView in the above code if the login in was successful:

func reauthenticateUserWith(email: String, password: String) {
  FIRAuth.auth()?.signIn(withEmail: email, password: password) { (user, error) in
    if error == nil {
      //display UIView to delete user again
      let deleteUserView = deleteUserView()
      present(deleteUserView, animated: true, completion: nil)
    } else {
      //handle error
      print(error!.localizedDescription)
    }
  }
}

The deleteUserView in my case calls deleteUser() on a button tap from the user. You can also use UIAlertController in place of the custom UIViews, but that's up to you.

Hope this helps.


Update for current Swift 5

let user = Auth.auth().currentUser

user?.delete { error in
    if let error = error {
        let authErr = AuthErrorCode(rawValue: error.code)
        if authErr == .requiresRecentLogin {
            // reauthenticate
        }

        // other error
    } else {
        // delete success
    }
}