gia*_*nni 2 javascript firebase reactjs firebase-authentication react-redux
我正在创建一个表单,在 react-redux 中更改用户密码。我想知道如何验证用户当前密码以更改为新密码。在我的表单中,我有 2 个字段:旧密码,新密码。
这是我的行动:
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
})
}
)
Run Code Online (Sandbox Code Playgroud)
我想知道,如何在 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)
}
}
Run Code Online (Sandbox Code Playgroud)
如果用户上次登录已经有一段时间了,那么 firebase 将返回一个错误 - “此操作是敏感的,需要最近的身份验证。在重试此请求之前登录。”

因此,您实际上并不需要像 firebase 那样检查旧密码。
但是,如果您只想一次性完成,而无需用户再次登录。也有办法做到这一点。
用户对象上有一个方法,reauthenticateAndRetrieveDataWithCredential您只需要传入一个信用对象(电子邮件和密码),它就会刷新身份验证令牌。
const reauthenticate = currentPassword => {
const user = firebase.auth().currentUser;
const cred = firebase.auth.EmailAuthProvider.credential(
user.email, currentPassword);
return user.reauthenticateAndRetrieveDataWithCredential(cred);
}
Run Code Online (Sandbox Code Playgroud)
在您的特定情况下,您可以有这样的事情
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)
}
}
Run Code Online (Sandbox Code Playgroud)
了解有关 firebase reauth 的更多信息 - https://firebase.google.com/docs/auth/web/manage-users#re-authenticate_a_user
希望能帮助到你
| 归档时间: |
|
| 查看次数: |
1454 次 |
| 最近记录: |