Обновление пароля в firebase (Angular 5) - PullRequest
0 голосов
/ 29 августа 2018

Я создаю компонент настроек для учетных записей в приложении, над которым я работаю, и я хочу, чтобы у пользователя была возможность обновить свой пароль из этих настроек учетной записи. Я создал эту функцию Firebase:

 updateUserPassword(password) {
    this.currentUser.updatePassword(password).then(function() {
      console.log('succcess!')
    }).catch(function(error) {
      alert(error)
    });
  }

однако каждый раз, когда я звоню, я получаю следующую ошибку: enter image description here

Я понимаю, что мне нужно пройти повторную аутентификацию для выполнения подобных запросов, однако я не могу понять, как это сделать! Есть предложения?

Ответы [ 2 ]

0 голосов
/ 29 августа 2018

Если логин пользователя слишком далеко в прошлом, и вы хотите изменить важную информацию, такую ​​как пароль, который пользователь должен повторно подтвердить подлинность, чтобы сделать процесс. В официальной документации Firebase содержится масса информации об этом.

0 голосов
/ 29 августа 2018

Для повторной аутентификации пользователя с учетными данными, вы в основном указываете адрес электронной почты и пароль. Ниже я покажу вам свою страницу account.ts, на которой есть кнопка, позволяющая пользователю сменить пароль. Когда пользователь нажимает кнопку, появляется предупреждение с вводом:

account.ts

changePassword(){
    console.log('Change Password Button Clicked');
    //Creating the promt alert with inputs
    let alert = this.alertCtrl.create({
      title: 'Change Password',
      inputs: [
        {
          name: 'oldPassword',
          placeholder: 'Your old password..',
          type: 'password'
        },
        {
          name: 'newPassword',
          placeholder: 'Your new password..',
          type: 'password'
        },
        {
          name: 'newPasswordConfirm',
          placeholder: 'Confirm your new password..',
          type: 'password'
        }
      ],
      buttons: [
        {
          text: 'Cancel',
          role: 'cancel',
          handler: data => {
            console.log('Cancel clicked');
          }
        },
         {
          text: 'Update Password',
          handler: data => {
            //First you get the current logged in user
            const cpUser = firebase.auth().currentUser; 

            /*Then you set credentials to be the current logged in user's email
            and the password the user typed in the input named "old password"
            where he is basically confirming his password just like facebook for example.*/

            const credentials = firebase.auth.EmailAuthProvider.credential(
              cpUser.email, data.oldPassword);

              //Reauthenticating here with the data above
              cpUser.reauthenticateWithCredential(credentials).then(
                success => {
                  if(data.newPassword != data.newPasswordConfirm){
                    let alert = this.alertCtrl.create({
                      title: 'Change Password Failed',
                      message: 'You did not confirm your password correctly.',
                      buttons: ['Try Again']
                    });
                    alert.present();
                  } else if(data.newPassword.length < 6){
                    let alert = this.alertCtrl.create({
                      title: 'Change Password Failed',
                      message: 'Your password should be at least 6 characters long',
                      buttons: ['Try Again']
                    });
                    alert.present();
                  } else {
                    let alert = this.alertCtrl.create({
                      title: 'Change Password Success',
                      message: 'Your password has been updated!',
                      buttons: ['OK']
                    });
                    alert.present();
                  /* Update the password to the password the user typed into the
                    new password input field */
                  cpUser.updatePassword(data.newPassword).then(function(){
                    //Success
                  }).catch(function(error){
                    //Failed
                  });
                  }
                },
                error => {
                  console.log(error);
                  if(error.code === "auth/wrong-password"){
                    let alert = this.alertCtrl.create({
                      title: 'Change Password Failed',
                      message: 'Your old password is invalid.',
                      buttons: ['Try Again']
                    });
                    alert.present();
                  }
                }
              )
              console.log(credentials); 
            }
          }
      ]
    });
    alert.present();
  }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...