Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Nodemailer verification using jwt

I’m trying to make e-mail verification using nodemailer and jwt key. The problem is that when I’m trying to verify jwt key, id of user is always undefined.
What am I doing wrong?

app.post("/api/createAccount", async (req, res) => {
  const { login, password } = req.body;
  const newUser = await user.create({
    login: login,
    password: password,
  });

  jwt.sign(
    { userId: newUser.id },
    "SECRETKEY",
    {
      expiresIn: "7d",
    },
    (err, token) => {
      const url = `http://localhost:5000/api/confirmMail/${token}`;
      const options = {
        from: "xxx",
        to: login,
        subject: "verifyacc",
        html: `<a href="${url}">${url}</a> `,
      };
      transporter.sendMail(options, function (err, info) {
        if (err) {
          console.log(err);
        } else {
          console.log(info);
        }
      });
    }
  );
});

app.get("/api/confirmMail/:token", async (req, res) => {
  try {
    const {
      userId: { id },
    } = jwt.verify(req.params.token, "SECRETKEY");
    await user.update({ confirmed: 1 }, { where: { id: id } });
  } catch (err) {
    console.log(err);
  }
  return res.redirect("http://localhost:3000/login");
});

The error :
err: Error: WHERE parameter "id" has invalid "undefined" value

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The payload of the token you are creating is

{ 
  userId: "foobar"
}

But in the deconstruction during verification

const { userId: { id } } = jwt.verify(...);

you expect it to be

{
  userId: { 
    id: "foobar"
  }
}

because the deconstruction you used, roughly translates to

const tmp = jwt.verify(...);
const id = tmp.userId.id; 

Thus id is of course undefined, as tmp.userId is (probably) a string or a number, which doesn’t have an id property.

Use

const { userId: id} = jwt.verify(...);
await user.update({ confirmed: 1 }, { where: { id } });

which roughly translates to

const tmp = jwt.verify(...);
const id = tmp.userId;

or alternatively

const { userId} = jwt.verify(...);
await user.update({ confirmed: 1 }, { where: { id: userId } });
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading