Home > OS >  How do I catch specific error returned by Firebase Auth, when user updates their password?
How do I catch specific error returned by Firebase Auth, when user updates their password?

Time:09-08

I am writing an app, where I want to give the user possibility to change their password. So I have a simple UpdatePassword.js page, where I invoke Firebase Authentication .updatePassword(password) method. As explained in the docs, this is a sensitive operation, and as such, the user needs to authenticate (if they haven't authenticated recently), in order to change their password to a new one.

This is my method:

const update = async () => {
    const user = await firebase.auth().currentUser;
    await user
      .updatePassword(password)
      .then(() => {
        setUpdated(true);
      })
      .catch((error) => {
        //I want to handle this specific error but I don't know how
        if (
          error.message ===
          "This operation is sensitive and requires recent authentication. Log in again before retrying this request."
        ) {
          console.log("should display a modal for user to authenticate again");
        }
        console.log("error while updating pass: ", error);
        setSaving(false);
      });
  };

As you can see from my console.logs, in the case where the user needs to authenticate again, I want to display a modal, where they will sign in with their credentials again. This is not a problem and is easy to do. However, my question is, how do I catch this specific type of error where the user needs to authenticate? As per my console.logs, the way I have implemented it right now, I am just comparing the error message which I receive from Firebase Authentication, which is really not the right way to do. What if Firebase Auth change the error message to something else? Is there something like an error code which I can compare to the error thrown, and handle the exception by error code or something more safe than just a string message?

CodePudding user response:

As you will see in the doc, the error that is thrown in this case (i.e. "if the user's last sign-in time does not meet the security threshold") has an auth/requires-recent-login error code.

So:

//...
.catch((error) => {
     if (error.code === 'auth/requires-recent-login') {
         // Display the modal 
     } else {
         // ...
  • Related