Search code examples
javascriptfirebasefirebase-authenticationangularfire2

Using Firebase reauthenticate


I'll appreciate assistance with how to reauthenticate a user in Firebase. I wonder if it makes any sense adding all these great features if the documentation doesn't explain how to use it:

Currently, this is what I'm trying, and it ain't working. Errors as cannot read property 'credential' of undefined

In constructor:

  constructor(@Inject(FirebaseApp) firebaseApp: any) {
    this.auth = firebaseApp.auth();
    console.log(this.auth);
  }

then the function

changePassword(passwordData) {
    if(passwordData.valid) {
      console.log(passwordData.value);
      // let us reauthenticate first irrespective of how long
      // user's been logged in!

      const user = this.auth.currentUser;
      const credential = this.auth.EmailAuthProvider.credential(user.email, passwordData.value.oldpassword);
      console.log(credential);
      this.auth.reauthenticate(credential)
        .then((_) => {
          console.log('User reauthenticated');
          this.auth.updatePassword(passwordData.value.newpassword)
            .then((_) => {
              console.log('Password changed');
            })
            .catch((error) => {
              console.log(error);
            })
        })
        .catch((error) => {
          console.log(error);
        })
    }
  }

Solution

  • The reauthenticate() method is called on a firebase.User, not on firebase.auth.Auth itself.

    var user = firebase.app.auth().currentUser;
    var credentials = firebase.auth.EmailAuthProvider.credential('[email protected]', 'firebase');
    user.reauthenticate(credentials);
    

    Update (July 2017):

    There are some breaking change in the 4.0 version of the Firebase Web SDK. From the release notes:

    BREAKING: firebase.User.prototype.reauthenticate has been removed in favor of firebase.User.prototype.reauthenticateWithCredential.

    As far as I can tell the reauthenticateWithCredentialis a drop-in replacement for the old method.