在更改密码之前用当前密码验证旧密码

validate old password with current password before change password

我想更改 firebase auth 的当前密码。但是如何使用旧密码使用 flutter 验证当前密码?

我的change_password.dart表格文件

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,
                        ),
                ),

从小部件调用函数的更改密码函数:

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

图片

在调用 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
}