diff --git a/Server/controllers/authController.js b/Server/controllers/authController.js index aef81f7ec..ee1724fb4 100644 --- a/Server/controllers/authController.js +++ b/Server/controllers/authController.js @@ -238,7 +238,7 @@ const resetPasswordController = async (req, res, next) => { const deleteUserController = async (req, res, next) => { try { // Validate user - await editUserParamValidation.validateAsync(req.params); + await editUserParamValidation.userDeleteValidation(req.params.userId); // Check if the user exists const user = await req.db.getUserById(req.params.userId); @@ -246,7 +246,19 @@ const deleteUserController = async (req, res, next) => { throw new Error(errorMessages.DB_USER_NOT_FOUND); } - // Delete the user + // Step 1: Find all monitors associated with the user + const monitors = await req.db.getMonitorsByUserId(req.params.userId); + + // Step 2: For each monitor, delete all associated checks and alerts + for (const monitor of monitors) { + await req.db.deleteChecks(monitor.id); + await req.db.deleteAlertByMonitorId(monitor.id); + } + + // Step 3: Delete all monitors associated with the user + await req.db.deleteMonitorsByUserId(req.params.userId); + + // Step 4: Finally, delete the user await req.db.deleteUser(req.params.userId); return res.status(200).json({ diff --git a/Server/db/MongoDB.js b/Server/db/MongoDB.js index 398e0d824..a2b7f4e80 100644 --- a/Server/db/MongoDB.js +++ b/Server/db/MongoDB.js @@ -303,6 +303,21 @@ const deleteAllMonitors = async (req, res) => { } }; +/** + * Delete all monitors associated with a user ID + * @async + * @param {string} userId - The ID of the user whose monitors are to be deleted. + * @returns {Promise} A promise that resolves when the operation is complete. + */ +const deleteMonitorsByUserId = async (userId) => { + try { + const result = await Monitor.deleteMany({ userId: userId }); + return result; + } catch (error) { + throw error; + } +}; + /** * Edit a monitor by ID * @async @@ -539,4 +554,5 @@ module.exports = { editAlert, deleteAlert, deleteAlertByMonitorId, + deleteMonitorsByUserId }; diff --git a/Server/validation/joi.js b/Server/validation/joi.js index 4316939b4..494a5cea9 100644 --- a/Server/validation/joi.js +++ b/Server/validation/joi.js @@ -43,6 +43,10 @@ const newPasswordValidation = joi.object({ confirm: joi.string(), }); +const userDeleteValidation = joi.object({ + userId: joi.string().required(), +}); + //**************************************** // Monitors //****************************************