通过电子邮件链接重新认证和删除用户

时间:2020-04-05 09:51:38

标签: swift xcode firebase firebase-authentication

我正在努力解决带有Firebase电子邮件链接的重新认证用户的问题。 我无法删除用户帐户。

该过程如下所示:

  1. 用户通过添加电子邮件地址创建帐户
  2. 链接已通过电子邮件成功发送
  3. 通用链接有效
  4. 通过单击链接进行身份验证会起作用
  5. 用户帐户是在Firebase上创建的
  6. 将此链接保存在UserDefaults上有效
  7. 重新验证用户时删除帐户不起作用...

它引发错误:

enter image description here

这是删除用户帐户的代码:

func deleteAccount() {

    // Create progres HUD
    let hud = JGProgressHUD(style: .dark)
    hud.textLabel.text = NSLocalizedString("Deleting Account", comment: "")
    hud.show(in: self.view)

    // #1 Create firebase credential to re-authenticate user
    let currentUser = Auth.auth().currentUser
    guard let email = Auth.auth().currentUser?.email else {return}
    let link = UserDefaults.standard.string(forKey: "Link")
    let credential = EmailAuthProvider.credential(withEmail: email, link: link!)

    // #2 Re-authenticate user
    currentUser?.reauthenticate(with: credential, completion: { (result, error) in

    // #3 if there is no error, remove user from database
    if error == nil {
        currentUser?.delete(completion: { (error) in
        guard let userID = currentUser?.uid else {return }
        let ref = Database.database().reference()
        ref.child("User").child(userID).removeValue()

        if error == nil{
            hud.dismiss()
            self.delegate?.deletePinAnnotation(email: email)
            self.navigationController?.popViewController(animated: true)
        } else {
            print(error.debugDescription)
        }
    } else {  // #4 If error when re-authenticate user occurs 
         print(error.debugDescription)         
    }                        
    hud.dismiss()                        
}

1 个答案:

答案 0 :(得分:0)

事实证明,我不应使用与创建帐户时相同的链接。重新认证期间,我应该发送另一个链接。

使用相同的方法:

Auth.auth().sendSignInLink(toEmail: email, actionCodeSettings: actionCodeSettings) { (error) in
      // ...
      if let error = error {
      self.createAlert(withDescription: error.localizedDescription)
      print(error)
      return
     }
   // The link was successfully sent. Inform the user.
   // Save the email locally so you don't need to ask the user for it again
   // if they open the link on the same device.
      UserDefaults.standard.set(email, forKey: "Email")
      self.createAlert(withDescription: "Open email to check the link")
   // ...
  }