Ade*_*ele 5 firebase reactjs firebase-authentication
我有点失落。我正在尝试设置密码重置系统,但我不知道该怎么做。我不必发送电子邮件来创建新密码。我该如何做才能让用户通过此表单更改密码?理论上,新密码应替换 Firebase 数据库中保存的旧密码。
import './ResetPassword.css'
import {Link} from 'react-router-dom';
import {useNavigate} from 'react-router-dom';
import { getAuth, sendPasswordResetEmail } from "firebase/auth";
function ResetPassword() {
const [email, setEmail] = useState('')
const auth = getAuth();
sendPasswordResetEmail(auth, email)
.then(() => {
// Password reset email sent!
// ..
})
.catch((error) => {
const errorCode = error.code;
const errorMessage = error.message;
// ..
});
return (
<div className="resetPassword-main">
<div className="resetPassword-container">
<h2>Ripristina la password</h2>
<div className="resetPassword-form">
<form onSubmit={sendPasswordResetEmail}>
<label>Email</label> <br />
<input className="resetEmailInput" placeholder="Email" type="email" required /> <br/>
<label>Nuova password</label> <br />
<input className="resetPwInput" placeholder="Password" type="password" /> <br/>
<button className="resetBtn" type="submit">Ripristina password</button>
</form>
</div>
</div>
</div>
)
}
export default ResetPassword;
Run Code Online (Sandbox Code Playgroud)
sendPasswordResetEmail()当用户未登录并且由于不记得密码而需要重置密码时使用。在这种情况下,系统会发送一封包含密码重置的电子邮件,用户可以使用该电子邮件重置其密码。
您不必在此表格中询问新密码。用户使用发送的电子邮件更改密码后,密码将在 Firebase Auth 中更新。
尝试将sendPasswordResetEmail代码包装在函数中,例如triggerResetEmail,然后在单击按钮时调用它onClick={triggerResetEmail}:
function ResetPassword() {
const [email, setEmail] = useState('')
const auth = getAuth();
const triggerResetEmail = async () => {
await sendPasswordResetEmail(auth, email);
console.log("Password reset email sent")
}
return (
<div className="resetPassword-main">
// Input field for email
<button className="resetBtn" type="button" onClick={triggerResetEmail}>Ripristina password</button>
</div>
)
}
export default ResetPassword;
Run Code Online (Sandbox Code Playgroud)
我不必发送电子邮件来创建新密码。我该如何做才能让用户通过此表单更改密码?
由于您不需要发送电子邮件,因此只需使用updatePassword()以下方法即可:
import {
getAuth,
updatePassword,
} from 'firebase/auth';
const newPassword = ... // Get the value of the new password
await updatePassword(auth.currentUser, newPassword);
Run Code Online (Sandbox Code Playgroud)
棘手的是,正如文档中所解释的,“这是一项安全敏感操作,要求用户最近登录”。“如果不满足此要求,请要求用户再次进行身份验证,然后致电reauthenticateWithCredential()”。
如果用户最近没有登录,您将从auth/requires-recent-login该方法中收到错误。updatePassword()
在这种情况下,请执行以下操作:
import {
getAuth,
updatePassword,
reauthenticateWithCredential,
EmailAuthProvider,
} from 'firebase/auth';
// ...
const oldPassword = ... // Get the value of the old password
const credential = EmailAuthProvider.credential(
this.currentUser.email,
oldPassword
);
await reauthenticateWithCredential(auth.currentUser, credential);
// Call again updatePassword()
const newPassword = ... // Get the value of the new password
await updatePassword(auth.currentUser, newPassword);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10510 次 |
| 最近记录: |