简体   繁体   中英

howto reset password using nodejs

I am resetting the password using email verification. When user forgot account password then using the forgot password page they enter email. If user email found in db then they get the resetlink for resetting the password. Then user enter new password and resetlink to update the password.I tries this into the postman it works fine and password get updated. 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. 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

 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

 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. 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 format: https://your_domain.tld/resetpass/link_value

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

The 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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