From a83da7839a0dd52d3967f7d8a79bb72d9858df8b Mon Sep 17 00:00:00 2001 From: Josh Everett <44347292+MrJoshE@users.noreply.github.com> Date: Thu, 20 Apr 2023 16:11:33 +0100 Subject: [PATCH] Extracted user id from the jwt for delete all --- src/routes/notification.js | 34 +++++++++++++++++++++++++++++----- 1 file changed, 29 insertions(+), 5 deletions(-) diff --git a/src/routes/notification.js b/src/routes/notification.js index f53ce6e..5df24f5 100644 --- a/src/routes/notification.js +++ b/src/routes/notification.js @@ -72,16 +72,40 @@ router.delete("/delete/:id", async (req, res) => { }); -router.delete("/delete/all/:id", async (req, res) => { +router.delete("/delete/all", async (req, res) => { // delete all the notifications // grab the user id // delete on the database try { - const notifications = await Notification.deleteMany({ user_id: req.params.id }) - if (!notifications) { - return res.status(404).send(); + // Get the JWT secret from the environment variables + const secretKey = process.env.JWT_SECRET; + + // If this is not set we want to throw an error as this is required to retrieve the user + // id from the provided token. + if (secretKey == null) { + console.error('JWT_SECRET is not set in the environment variables'); + return res.status(500).send("JWT_SECRET is not set in the environment variables"); } - res.send(notifications); + + // Get the token from the request headers + const token = req.headers.authorization.split(" ")[1]; + + // Decode this token with the secret key + const payload = jwt.decode(token, secretKey, false, jwtAlgorithm); + + // Get the user id from the decoded token payload. + const userId = payload.id; + + console.log("deleting all notifications for user: " + userId) + + const notifications = await Notification.deleteMany({ user_id: userId }) + + // If the delete was not successful send a 500 error. + if (!notifications.acknowledged) { + return res.status(500).send(); + } + + res.status(200); } catch (error) { res.status(500).send(error); } -- GitLab