简体   繁体   中英

Change password of firebase user in flutter

I want to change the password of a firebase account. To do that the user should enter the old password before. If it is correct then he is allowed to change pass. I used this code which is only for changing the pass and not comparing the old one.

void _changePassword(String password) async{
//Create an instance of the current user. 
FirebaseUser user = await FirebaseAuth.instance.currentUser();

//Pass in the password to updatePassword.
user.updatePassword(password).then((_){
  print("Successfully changed password");
}).catchError((error){
  print("Password can't be changed" + error.toString());
  //This might happen, when the wrong password is in, the user isn't found, or if the user hasn't logged in recently.
});
}

The idea is to verify old password by resigning in user using firebaseAuth, you can get user email by passing user.email to string, and let user input old password. If sign in proccess failed, password change shouldn't happen.

void _changePassword(String password) async {
    FirebaseUser user = await FirebaseAuth.instance.currentUser();
    String email = user.email;

    //Create field for user to input old password

    //pass the password here
    String password = "password";
    String newPassword = "password";

    try {
      UserCredential userCredential = await FirebaseAuth.instance.signInWithEmailAndPassword(
          email: email,
          password: password,
      );
      
      user.updatePassword(newPassword).then((_){
        print("Successfully changed password");
      }).catchError((error){
        print("Password can't be changed" + error.toString());
        //This might happen, when the wrong password is in, the user isn't found, or if the user hasn't logged in recently.
      });
    } on FirebaseAuthException catch (e) {
      if (e.code == 'user-not-found') {
        print('No user found for that email.');
      } else if (e.code == 'wrong-password') {
        print('Wrong password provided for that user.');
      }
    }
  }

it will not allow you to verify its previous or old password. it will directly send email for forgot and there you need to add your new password. and and you have to back again to application and your password will be updated as you wil try to login.

If the user hasn't signed in recently, Firebase will automatically require them to reauthenticate before they can change their password (or perform other sensitive operations). So you typically should only require the user to reauthenticate when Firebase tells you to.

When that happens, follow the steps in the documentation on reauthenticating a user .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM