Home > Software engineering >  validate old password with current password before change password
validate old password with current password before change password

Time:01-20

I want to change the current password of firebase auth. But how can I use the old password to validate with the current password using flutter?

my change_password.dart form file

Form(
      key: _formKey,
      child: Column(
        children: [
    
          TextFormField(
            controller: _oldPasswordController,
            obscureText: hidePassword,
            decoration: InputDecoration(
              labelText: AppString.oldPassword,
            ),
            validator: (value) {
              if (value!.isEmpty) {
                return AppString.enterPassword;
              } else if (value.length <= 5) {
                return AppString.passwordValidation;
              }
              return null;
            },
          ),
        
          TextFormField(
            controller: _changePasswordController,
            obscureText: hidePassword,
            decoration: InputDecoration(
              labelText: AppString.newPassword,    
            ),
            validator: (value) {
              if (value!.isEmpty) {
                return AppString.enterPassword;
              } else if (value.length <= 5) {
                return AppString.passwordValidation;
              }
              return null;
            },
          ),
          
          Row(
            children: [
                child: ElevatedButton(
                  style: buttonStyle,
                  onPressed: () async {
                    if (_formKey.currentState!.validate()) {
                      _formKey.currentState!.save();
                      changePassword(
                        _changePasswordController!.text,
                      );
                    }
                  },
                  child: Text(
                          AppString.changePassword,
                        ),
                ),

change password function where the function is called from the widget :

void changePassword(String password) async {
    try {
      await currentUser!.updatePassword(password);
      AuthProvider.logOut().whenComplete(() {
        snackBarWidgets(context, AppString.pswdChangedSuccessful);
      });
    } catch (e) {
      rethrow;
    }
  }

Image My change password widget

CodePudding user response:

Add these lines before calling updatePassword:

final user = FirebaseAuth.instance.currentUser;
// you should check here that email is not empty
final credential = EmailAuthProvider.credential(
    email: user.email!,
    password: <password>);
try {
  await user.reauthenticateWithCredential(credential);
  // proceed with password change
} on FirebaseAuthException catch (e) {
  // handle if reauthenticatation was not successful
}
  •  Tags:  
  • Related