Dhaval Jardosh
Dhaval Jardosh

Reputation: 7299

Firebase - Problem updating password after re-authenticating

What I'm trying to do?

  1. Re-authenticate User, checking the current password (this.state.currentPassword)
  2. Update new Password (this.state.newPassword)

What problem I'm facing?

  1. STEP 1 is successfully being performed
  2. But when trying to do STEP 2, it throws an error and getting the error from outer try i.e. "Error Reauthenticating"

var user = firebaseApp.auth().currentUser;
var credential = firebase.auth.EmailAuthProvider.credential(
    firebaseApp.auth().currentUser.email,
    this.state.currentPassword
);

// Prompt the user to re-provide their sign-in credentials


// STEP 1 : re-authenticate user

user.reauthenticateAndRetrieveDataWithCredential(credential).then(function() {
  // User re-authenticated.

  //Upon re-authenticating, update password

  //STEP 2 : UPDATE PASSWORD

  var newPassword = firebase.getASecureRandomPassword();

  user.updatePassword(newPassword).then(function() {
    alert("SUCCESS")
    // Update successful.
  }).catch(function(error) {
    console.log(error)
    // An error happened.
  });


}).catch(function(error) {
  // An error happened.
  alert("Error Reauthenticating")
});

Upvotes: 1

Views: 1137

Answers (1)

Dhaval Jardosh
Dhaval Jardosh

Reputation: 7299

Not sure what the problem is but was able to get the desired output by the following code.

Credit to this article.

reauthenticate = (currentPassword) => {
  var user = firebase.auth().currentUser;
  var cred = firebase.auth.EmailAuthProvider.credential(
    user.email, currentPassword);
  return user.reauthenticateAndRetrieveDataWithCredential(cred);
}

changePassword = (currentPassword, newPassword) => {
  this.reauthenticate(currentPassword).then(() => {
    var user = firebase.auth().currentUser;
    user.updatePassword(newPassword).then(() => {
      console.log("Password updated!");
    }).catch((error) => {
      console.log(error);
    });
  }).catch((error) => {
    console.log(error);
  });
}

May be ES6 syntax is required but will inquire tomorrow.

Upvotes: 1

Related Questions