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
CodePudding user response:
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 } });