Catch certain Firebase Error in iOS not working

Viewed 124

Updated question

I am trying to manually check if the user is has to be reauthenticated or not. This is what I've come up with:

    //MARK: updateEmail
static func updateEmail(email: String, finished: @escaping (_ done: Bool, _ hasToReauthenticate: Bool) -> Void) {
    let currentUser = Auth.auth().currentUser
    currentUser?.updateEmail(to: email) { err in
        if err != nil {
            if let errCode = AuthErrorCode(rawValue: err!._code) {
                switch errCode {
                case .userTokenExpired:
                    print("expired")
                    finished(true, true)
                    break
                default:
                    Utilities.showErrorPopUp(labelContent: "Fehler", description: err!.localizedDescription)
                    finished(false, false)
                }
            }
        } else {
            finished(true, false)
        }
    }
}

But this is never going through the .userTokenExpired case even when it should.. What am I missing here ?

3 Answers

There is no API in Firebase Authentication that returns when the user has last authenticated, or whether that was recently. The only built-in functionality is that Firebase automatically checks for recent authentication for certain sensitive operations, but that seems to be of no use to you here.

But since your application is making API calls when the user authenticates, you can also record the time when they do so, and then check whether that was recent enough for your use-case.

If you need to check if user is authenicated - is same as reauthenication. Firebase will do their work to do some lower levels like tokens, etc. We don't have to worry about it.

guard let currentUser = Auth.auth().currentUser else {
 //authenicate the user.
}

if you want to update the email address in user, the logic should be

check if the user is not nil, then update the email address.

If it is nil, then log in (anonymous or regular workflow to sign in), then update the email address.

I use this similar logic to check if the user is signed in, then do something. Otherwise, sign in as anonymous, then do same something.

The issue was quite simple: I caught the wrong error:

The error I have to catch in my case is .requiresRecentLogin . With that, everything is working fine.

Related