Firebase: updatePassword() does not work

Asked

Viewed 44 times

0

I’m trying to perform a password reset system on my React Native project with Firebase but it doesn’t work at all.

The state of the email is displayed as normal in Alert, but the password returns Undefined.

update = async() => {
    const password = this.state;

    if(password != ""){

        auth().onAuthStateChanged(function(user) {
            if (user) {
                user.updatePassword(password.toString()).then(function() {
                    Alert.alert(`${user.email} - ${user.password}`);
                  }).catch(function(error) {
                    Alert.alert(error);
                  });
            } else {
                //Alert.alert("deslogado");   
            }
        });
    }

    else{
        this.setState({error: "Campo Vazio!"});
    }

}

1 answer

0

assuming that it will perform its function when the user is logged in:

don’t use onAuthStateChanged() to recover the user because it only recovers the user when there are login, logout and token exchange events (so it will not present value). simply use auth().currentUser.

update = async() => {
    const password = this.state;
    const user = auth().currentUser;
    if (password != "") {
      user.updatePassword(password).then(function() {
         Alert.alert(`Atualizado senha: ${user.email} - ${password}`);
      }).catch(function(error) {
         Alert.alert(`ocorreu um erro: ${error}`);   
      });
    } else {
      this.setState({error: "Campo Vazio!"});
    }
}

Remember that some actions that pose security risks, such as deleting an account, setting a primary email address, and changing a password, require the user to have logged in recently. If you perform one of these actions and the user has long logged in, the action will fail and generate an error. When this happens, authenticate the user again by generating new login credentials and transmitting them to reauthenticateWithCredential()

to use reauthenticateWithCredential():

const credential = firebase.auth.EmailAuthProvider.credential(email, password);
user.reauthenticateWithCredential(credential).then(function() {
  // Usuário reautenticado
  // agora você pode user.updatePassword() sem precupapções
}).catch(function(error) {
  // Um erro ocorreu.
})

Browser other questions tagged

You are not signed in. Login or sign up in order to post.