Reset Password with Nodejs & NodeMailer

Subscribe to my newsletter and never miss my upcoming articles

Reset Password with Nodejs & NodeMailer - Easy Way !

password is one of the most critical inputs, to retrieve them it is necessary to apply a robust method

  • follow the steps to create a solid backend that allows you to change the password

you need to import the nodemailer package

const nodemailer = require("nodemailer");

you need also to create a transporter with your SMTP

const transporter = nodemailer.createTransport({
  host: "your_smtp_host",
  port: port_smtp,
  auth: {
    user: "your_email",
    pass: "your_password",
  },
});

after this step, you need to create a method to reset the password and send it to the client side.

reset password method

const resetPassword = (req, res) => {
  crypto.randomBytes(32, (err, buffer) => {
    if (err) {
      console.log(err);
    }
    const token = buffer.toString("hex");
    UserModal.findOne({ email: req.body.email }).then((user) => {
      if (!user) {
        return res
          .status(422)
          .json({ error: "User dont exists  with that Email" });
      }
      user.resetToken = token;
      user.expireToken = Date.now() + 3600000;
      const data = {
        to: user.email,
        from: "no-replay@mega-coding.com",
        subject: "Password Reset",
        html: `
          <div class="card-div">
      <div class="paragraphe-center">
        <h1 style="text-align: center;">Reset Your password</h1>
        <p class="p1">
          Hi there, if you've lost password or wish to reset it, use the link
          below to get started
        </p>
        <button class="password-btn">
          <a href="http://localhost:3000/reset-password/${token}">Reset your password</a>
        </button>
        <p class="p2">
          if you did not request a password reset , you can safety ignore this
          email only a person with access to your email can reset your account
          password.
        </p>
      </div>
    </div>
  </body>
</html>
<style>
  @import url("https://fonts.googleapis.com/css2?family=Roboto:wght@300&display=swap");
  .card-div {
    font-family: "Roboto", sans-serif;
    position: relative;
    background: #fff;
    margin: 1em;
    display: inline-block;
    text-align: left;
    overflow: hidden;
    font-size: 14px;
    border-radius: 3px;
    height: 300px;
    max-width: 600px;
    -moz-transition: 0.5s;
    -o-transition: 0.5s;
    -webkit-transition: 0.5s;
    transition: 0.5s;
    -webkit-box-shadow: 0 3px 7px -3px rgba(0, 0, 0, 0.3);
    -moz-box-shadow: 0 3px 7px -3px rgba(0, 0, 0, 0.3);
    box-shadow: 0 3px 7px -3px rgba(0, 0, 0, 0.3);
  }
  .paragraphe-center {
    padding: 15px;
  }
  .password-btn {
    background-color: blue;
    border: none;
    color: white;
    border-radius: 5px 5px 5px 5px;
    display: table;
    margin: 0 auto;
    padding: 12px;
  }
  a {
    text-decoration: none;
    text-decoration-color: none;
    color: white;
  }
  .p1,
  .p2 {
    padding: 12px;
  }
</style>

          `,
      };
      user.save().then((result) => {
        transporter
          .sendMail(data)
          .then(async () => {
            console.log("emeil sent", result);
          })
          .catch((err) => console.log(err));
        res.json({ message: " check your email" });
      });
    });
  });
};

new password method

const newPassword = (req, res) => {
  const newPassword = req.body.password;
  const sentToken = req.body.token;
  UserModal.findOne({ resetToken: sentToken, expireToken: { $gt: Date.now() } })
    .then((user) => {
      if (!user) {
        return res.status(422).json({ error: "Try again session expired" });
      }
      bcrypt.hash(newPassword, 12).then((hashedpassword) => {
        user.password = hashedpassword;
        user.resetToken = undefined;
        user.expireToken = undefined;
        user.save().then((saveduser) => {
          res.json({ message: "password updated success" });
        });
      });
    })
    .catch((err) => {
      console.log(err);
    });
};

This is what you must do, thank you for reading and good reading.

MOHAMMED JAITI CEO @ MEGA CODING.

No Comments Yet