Here are the steps

  • If user forgot password, you need to ask their email address.
  • Then query your database to see if any user with that email exist.
  • If yes, then you can send a link to their email.
  • Upon click you can login the user so that he can update his password from his profile update page (you need to have that feature)
  • This last step could also be replaced by asking user to provide new password before login (after the email link click).
// routes/auth
router.post("/forgot-password", auth.forgotPassword);

// controllers/auth
export const forgotPassword = async (req, res) => {
  try {
    const { email } = req.body;

    const user = await User.findOne({ email });
    if (!user) {
      res.json({ error: "Could not find user with that email" });
    } else {
      const resetCode = nanoid();

      const token = jwt.sign({ resetCode }, config.JWT_SECRET, {
        expiresIn: "60m",
      });
      // save to user db
      user.resetCode = resetCode;
      user.save();

      // send email
      config.AWSSES.sendEmail(
        emailTemplate(
          email,
          `
        <p>Please click the link below to access your account.</p>
        <a href="${config.CLIENT_URL}/auth/access-password/${token}">Access my account</a>
    `,
          config.REPLY_TO,
          "Access your account"
        ),
        (err, data) => {
          if (err) {
            return res.json({ error: "Provide a valid email address" });
          } else {
            return res.json({ error: "Check email to access your account" });
          }
        }
      );
    }
  } catch (err) {
    console.log(err);
    res.json({ error: "Something went wrong. Try again." });
  }
};