我正在创建一个表单,在 react-redux 中更改用户密码。我想知道如何验证用户当前密码以更改为新密码。 在我的表单中,我有 2 个字段:旧密码、新密码。
这是我的 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
})
}
)
我想知道,如何在 firebase 中验证旧密码?我应该使用 signInWithEmailAndPassword() 吗?或者,由于我的用户已经登录,是否有无需再次调用 signIn 即可验证当前密码的功能? 谢谢
最佳答案
好吧,我相信您希望用户输入旧密码只是为了验证它是否是帐户的实际所有者。
Firebase 很好地处理了这种情况,您只需调用用户对象的 updatePassword 方法并传入新密码即可。
const changePassword = async newPassword => {
const user = firebase.auth().currentUser;
try {
await user.updatePassword(newPassword)
console.log('Password Updated!')
} catch (err) {
console.log(err)
}
}
如果用户上次登录已经有一段时间了,那么 firebase 将返回一个错误 - “此操作很敏感,需要最近的身份验证。在重试此请求之前先登录。”
因此,您真的不需要像 firebase 那样检查旧密码。
但是如果你只想一次性完成,而不需要用户再次登录。 也有一种方法。
用户对象上有一个方法 reauthenticateAndRetrieveDataWithCredential
你只需要传入一个 cred 对象(电子邮件和密码),它就会刷新身份验证 token 。
const reauthenticate = currentPassword => {
const user = firebase.auth().currentUser;
const cred = firebase.auth.EmailAuthProvider.credential(
user.email, currentPassword);
return user.reauthenticateAndRetrieveDataWithCredential(cred);
}
在你的特殊情况下,你可以有这样的东西
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)
}
}
详细了解 firebase 重新验证 - https://firebase.google.com/docs/auth/web/manage-users#re-authenticate_a_user
希望对你有帮助
关于javascript - 如何验证 firebase 用户当前密码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53981089/