简体   繁体   English

如何使用nodejs重置密码

[英]howto reset password using nodejs

I am resetting the password using email verification.我正在使用 email 验证重置密码。 When user forgot account password then using the forgot password page they enter email.当用户忘记帐户密码然后使用忘记密码页面他们输入 email。 If user email found in db then they get the resetlink for resetting the password.如果在 db 中找到用户 email,那么他们将获得用于重置密码的 resetlink。 Then user enter new password and resetlink to update the password.I tries this into the postman it works fine and password get updated.然后用户输入新密码并重置链接以更新密码。我在 postman 中尝试了这个,它工作正常并且密码得到更新。 But when user only enter the password it throws an Authentication error.但是当用户只输入密码时,它会引发身份验证错误。

So, I want to reset the password using the reset link in the url not into the body.因此,我想使用 url 中的重置链接重置密码,而不是进入正文。 User only needs to enter new password there is no need to enter reset link into the form.用户只需输入新密码,无需在表单中输入重置链接。 How can I implement that我该如何实现

forgotPassword.js忘记密码.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 }; }); }); } }); }); };

resetPassword.js重置密码.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" }); } };

Also I want to it works with frontend.我也希望它与前端一起使用。 Here is the frontend for reset password.这是重置密码的前端。 Which is not working..哪个不工作..

 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;

Request handler for 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)); };

You can make use of the URL parameters.您可以使用 URL 参数。 So the reset link value will be in the params while the password will be in the body.所以重置链接值将在参数中,而密码将在正文中。 The user does not have to enter the link again as long as you append the reset link value to the url params during the link generation.用户不必再次输入链接,只要您在链接生成期间将链接值重置为 url 参数即可。

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

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

The controller: controller:

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

The router:路由器:

// 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