0

I am trying to implement a reset password flow in my application. In this post request, I am first checking if the database has the "linkPass" for the passed email which stores the expiration of the link. If not first check that the email is associated with a user account. If yes it generates a link and sends it to their email. If not (and that is where the problem occurs) it sends the client back to the form and displays a message. So as you can see every condition redirects you to the same page, but if the user does not exist I get the cannot set headers error. I know what is the problem just don't know how to resolve it. Tried to return the redirections but didn't help...

app.post(
  "/requireNewPassword",
  tryCatch(async (req, res) => {
    const { email, modulName, continueUrl } = req.body;

    const ipAddress = await axios
      .get("https://api.ipify.org")
      .then((res) => {
        return res.data;
      })
      .catch((err) => console.log(err));
    const [linkPass] = await getLinkPasses(email, "last");
    let linkAvailable = false;

    //check if linkPass is available and expired
    if (!linkPass || linkPass.expiration < Date.now()) {
      linkAvailable = false;

      const user = await admin
        .auth()
        .getUserByEmail(email)
        .then(async (user) => {
          return user;
        })
        .catch((err) => {
          //if user does not exist
          console.log(err.message);
          if (err.code === "auth/user-not-found") {
            linkAvailable = true;
            console.log(`${email} does not exist!`);
            return res.redirect(
              `/?email=${email}&linkAvailable=${linkAvailable}`
            );
          }
        });

      //if user exits
      if (user) {
        const link_id = await generateLinkPass(email, 5, true);
        //get firebase oobCode
        const pwdResetLink = await admin
          .auth()
          .generatePasswordResetLink(email)
          .then((link) => {
            const queryParams = new URLSearchParams(link);
            const oobCode = queryParams.get("oobCode");
            const apiKey = queryParams.get("apiKey");
            const recoveryLink = `${URL_PWD}/resetPassword/?    link_id=${link_id}&email=${email}&apiKey=${apiKey}&oobCode=${oobCode}&continueUrl=${continueUrl}`;
            console.log("Password recovery link has been created");
            return recoveryLink;
          })
          .catch((err) => {
            //if cannot generate pwdResetLink
            console.log(
              JSON.parse(
                err.errorInfo.message.match(/Raw server response: "(.*)"/)[1]
              ).error.message
            );
          });

        if (pwdResetLink) {
          axios
            .post(`${URL_EFDS}/sendEmailTemplate`, {
              recipient: {
                name: user.displayName || "John Doe",
                email: email,
                ip_address: ipAddress,
              },
              recoveryLink: pwdResetLink,
              moduleName: modulName,
              apiKey: EFDS_APIKEY,
              templateType: "forgottenPassword",
            })
            .then((res) => console.log(res.data))
            .catch((err) => console.log(err.data));

          console.log(`Password recovery email has been sent to ${email}`);
          return res.redirect(
            `/?email=${email}&linkAvailable=${linkAvailable}`
          );
        } else {
          //if pwdResetLink does not exsist
          console.log("pwdResetLink does not exsist");
          return res.redirect("partials/error", { err });
        }
      } else {
        console.log("user does not exist");
        const link_id = await generateLinkPass(email, 0, false);
        return res.redirect(`/?email=${email}&linkAvailable=${linkAvailable}`); //this line causing the error
      }
    } else {
      console.log("Valid link is already available");
      linkAvailable = true;
      //hiaba allitom true-ra a linkAvailablet, a get requestnel figyeli hogy az emailhez letrajott e linkPass, de nem jott letre, igy nem mutat uzenetet
      return res.redirect(`/?email=${email}&linkAvailable=${linkAvailable}`);
    }
  })
);
RubenSmn
  • 4,091
  • 2
  • 5
  • 24
  • There are over a hundred questions/answers on this exact error here on Stackoverflow. I'm quite sure that at least half of them would lead you to understand your error cause. – jfriend00 Feb 03 '23 at 07:21
  • Also, your error handling here is non-existent (you don't ever send a response when there are errors) and the mixing of `await` and `.then()` is not advised because it makes for confusing code. Pick one model or the other. – jfriend00 Feb 03 '23 at 07:23
  • Here's a hint. A `return` in a callback does NOT return from the parent function. So, it does not stop further execution in the parent function. – jfriend00 Feb 03 '23 at 07:24
  • Here's one such other answer on this topic: [ERR_HTTP_HEADERS_SENT: Cannot set headers after they are sent to the client](https://stackoverflow.com/questions/52122272/err-http-headers-sent-cannot-set-headers-after-they-are-sent-to-the-client/52122527#52122527) – jfriend00 Feb 03 '23 at 16:42

0 Answers0