Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I am using Firebase to log in users into my app, but when I am adding the capability to manage their account like changing their email, password and so on. The documentation says that if the user have not recently signed in they need to re-authenticate, but my question is: How can I check if the user have signed in recently or not? According to the docs the error will return FIRAuthErrorCodeCredentialTooOld, but how can I check this?

From the Firebase docs:

like image 375
Magnus Avatar asked Jan 01 '17 08:01

Magnus


2 Answers

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
    }
}

like image 131
iamin Avatar answered Oct 21 '22 16:10

iamin


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.

like image 41
D. Greg Avatar answered Oct 21 '22 15:10

D. Greg