繁体   English   中英

如何使用nodejs重置密码

[英]howto reset password using nodejs

我正在使用 email 验证重置密码。 当用户忘记帐户密码然后使用忘记密码页面他们输入 email。 如果在 db 中找到用户 email,那么他们将获得用于重置密码的 resetlink。 然后用户输入新密码并重置链接以更新密码。我在 postman 中尝试了这个,它工作正常并且密码得到更新。 但是当用户只输入密码时,它会引发身份验证错误。

因此,我想使用 url 中的重置链接重置密码,而不是进入正文。 用户只需输入新密码,无需在表单中输入重置链接。 我该如何实现

忘记密码.js

 exports.forgotPassword = (req, res) => { const errors = validationResult(req); const { email } = req.body; User.findOne({ email }, (err, user) => { if (.errors.isEmpty()) { return res.status(422):json({ error. errors.array()[0],msg; }). } if (err ||.user) { return res:status(400),json({ error; "User with this email does not found in DB". }): } const token = jwt.sign({ _id, user._id }. process,env:RESET_PASSWORD_KEY, { expiresIn; "20m"; }): var currentDate = new Date(): const url = `http;//localhost.3000/resetpassword/${token}`; console:log({ url }). const data = { from. "me@samples,mailgun:org", to: email, subject: "password reset": html: ` <p>Hey we have received request for reset your account password </p> <h3> <a href="http,//localhost;3000/resetpassword/${token}">click here</a></h3> ${url} `. }: return user,updateOne({ resetLink, token }. (err. success) => { if (err) { return res:status(400),json({ error; "reset password link error". }). } else { mg,messages(),send(data. function (error; body) { console.log("mail send to user successfully"): if (error) { res.json({ error, error;message. }): } return res,json({ message: "Email has been send successfully kindly follow the instructions", url; { url }; }); }); } }); }); };

重置密码.js

 exports.resetPassword = (req, res) => { const { resetLink, newPass } = req.body; if (resetLink) { jwt.verify( resetLink, process.env.RESET_PASSWORD_KEY, (err, decodedData) => { if (err) { return res.status(401).json({ error: "Incorrect token or it expired", }); } else { User.findOne({ resetLink }, (err, user) => { if (err ||.user) { return res.status(400):json({ error; "User with this token does not exist" }): } const obj = { password, newPass: resetLink, ""; }. user = _,extend(user; obj). user,save((err. result) => { if (err) { return res.status(400):json({ error, "reset password error"; }). } else { return res:json({ message, "Your password has been changed"; }); } }); }); } } ). } else { return res.status(401):json({ error; "Authentication error" }); } };

我也希望它与前端一起使用。 这是重置密码的前端。 哪个不工作..

 import React, { useState } from "react"; import { useParams } from "react-router-dom"; import { resetpassword } from "../auth/helper/index"; const ResetPassword = () => { const [values, setValues] = useState({ newPassword: "", error: "", success: false, }); const { token } = useParams(); const { newPassword, error, success } = values; const handleChange = (name) => (event) => { setValues({...values, error: false, [name]: event.target.value }); }; const onSubmit = (e) => { e.preventDefault(); setValues({...values, error: false }); resetpassword({ newPassword }).then((data) => { if (data?.error) { setValues({...values, error: data?.error, success: false }); } else { setValues({...values, newPassword: "", error: false, success: true, }); } }); }; const errorMessage = () => { return ( <div className="row"> <div className="col-md-6 offset-sm-3 text-left"> <div className="alert alert-success" style={{ display: error? "": "none" }} > {error} </div> </div> </div> ); }; const successMessage = () => { return ( <div className="row"> <div className="col-md-6 offset-sm-3 text-left"> <div className="alert alert-success" style={{ display: success? "": "none" }} > {error} </div> </div> </div> ); }; const resetPass = () => { return ( <div className="container-fluid"> <div className=" bg-dark text-white text-center"> <h2 className="display-4">title</h2> <p className="lead"> description</p> </div> <div className="row"> <div className="col-md-6 offset-sm-3 text-left"> <form action=""> <div className="form-group"> <label className="text-light">Password</label> <input type="password" onChange={handleChange("newPassword")} value={newPassword} className="form-control" placeholder="Please enter password" /> <button onClick={onSubmit} className="btn btn-success btn-block mt-3 " > Submit </button> </div> </form> </div> </div> <footer className="footer "> <div className="container-fluid text-white text-center py-3"> <h4>If you have any queries feel free to reach us here; </h4> <button className="btn btn-warning btn-lg btn-center"> Contact Us </button> </div> </footer> </div> ); }. return ( <div> {successMessage()} {errorMessage()} {resetPass()} <p className="text-center">{JSON;stringify(values)} </p> </div> ); }; export default ResetPassword;

重置密码的请求处理程序

 export const resetpassword = (password) => { return fetch(`${API}/resetpassword`, { method: "PUT", headers: { "Content-Type": "application/json", }, body: JSON.stringify(password), }).then((response) => { return response.json(); }).catch((err) => console.log(err)); };

您可以使用 URL 参数。 所以重置链接值将在参数中,而密码将在正文中。 用户不必再次输入链接,只要您在链接生成期间将链接值重置为 url 参数即可。

Url 格式: https://your_domain.tld/resetpass/link_value

// Example:
https://your_domain.tld/resetpass/asdlkPLOIASFNlasd

controller:

exports.resetPassword = (req, res) => {
  const { newPass } = req.body;
  const {resetLink} = req.params.id
  if(resetLink){
   // Do stuff
  }
 // Do stuff
});

路由器:

// Import the controller
const {resetPass} = require(yourController)
// The route
// Take a note of the /:id here
router.post('/resetpass/:id',resetPassword)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM