更新Firebase Web身份验证用户密码

wgeznvg7  于 2022-11-17  发布在  其他
关注(0)|答案(1)|浏览(165)

由于某种原因,用户的密码无法更改。下面是我正在处理的问题:

function resetPass() {
    
    var email = document.getElementById("emailX").value;
    var oldpass = document.getElementById("oldpass").value;
    var newpass = document.getElementById("newpass").value;
  
    var cred = firebase.auth.EmailAuthProvider.credential(email, oldpass);
  
    auth.currentUser.reauthenticateWithCredential(cred)
        .then(() =>  console.log("Success: Authentication completed!"))
        .catch((er) => console.error("Error: " + er.message));
  
    auth.currentUser.updatePassword(newpass)
        .then(() => console.log("Success: Password is updated!"))
        .catch((err) => console.error("Error: Password updation failed. " + err.message));
  }

登录工作正常,但更新用户密码不起作用。

wfauudbj

wfauudbj1#

对Firebase Authentication的调用(与大多数云API一样)是异步的,您需要等待reauthenticateWithCredential完成,然后再调用updatePassword
因此,一个简单的解决方案是:

auth.currentUser.reauthenticateWithCredential(cred)
    .then(() => {
        console.log("Success: Authentication completed!")
        auth.currentUser.updatePassword(newpass)
            .then(() => console.log("Success: Password is updated!"))
            .catch((err) => console.error("Error: Password updation failed. " + err.message));
    })
    .catch((er) => console.error("Error: " + er.message));

或者(稍微短一点)让结果冒泡:

auth.currentUser.reauthenticateWithCredential(cred)
    .then(() => {
        console.log("Success: Authentication completed!")
        return auth.currentUser.updatePassword(newpass);
    })
    .then(() => console.log("Success: Password is updated!"))
    .catch((er) => console.error("Error: " + er.message));

相关问题