How to validate firebase user current password

Viewed 2572

I am creating a form, in react-redux to change user password. I am wondering how can I validate the user current password in order to change to new one. in my form I have 2 fields: old password, new password.

this is my action:

const { currentUser } = auth
currentUser.updatePassword(newPassword)
.then(
  success => {
    dispatch({
      type: CHANGE_USER_PASSWORD_SUCCESS,
      payload: currentUser
    })
  },
  error => {
    dispatch({
      type: CHANGE_USER_PASSWORD_FAIL,
      error: error.message
    })
  }
)

I am wondering, how to validate the old password in firebase? Should I use signInWithEmailAndPassword()? Or, is there a function to validate the current password without calling the signIn again, since my user is already logged in? Thanks

1 Answers

Well, I believe you want the user to enter the old password just to verify whether it's the actual owner of the account or not.

Firebase handles this situation very well, you just need to call the updatePassword method on the user object and pass in the new password.

const changePassword = async newPassword => {
    const user = firebase.auth().currentUser;
    try {
      await user.updatePassword(newPassword)
      console.log('Password Updated!')
    } catch (err) {
      console.log(err)
    }
}

If it's been quite a while that the user last logged in then firebase will return back an error - "This operation is sensitive and requires recent authentication. Log in before retrying this request."

(Click to view image)

Thus, you don't really need to check the old password as firebase does it for you.

But if you just want to do it in one go, without having the user to log in again. There's a way for that as well.

There is a method on user object reauthenticateAndRetrieveDataWithCredential you just need to pass in a cred object(email and password) and it refreshes the auth token.

const reauthenticate = currentPassword => {
  const user = firebase.auth().currentUser;
  const cred = firebase.auth.EmailAuthProvider.credential(
      user.email, currentPassword);
  return user.reauthenticateAndRetrieveDataWithCredential(cred);
}

In your particular case, you can have something like this

const changePassword = async (oldPassword, newPassword) => {
  const user = firebase.auth().currentUser
  try {
    // reauthenticating
    await this.reauthenticate(oldPassword)
    // updating password
    await user.updatePassword(newPassword)
  } catch(err){
    console.log(err)
  }
}

Learn more about firebase reauth - https://firebase.google.com/docs/auth/web/manage-users#re-authenticate_a_user

Hope it helps

Related