diff --git a/src/controllers/user.controller.js b/src/controllers/user.controller.js index 971aadc..29022e4 100644 --- a/src/controllers/user.controller.js +++ b/src/controllers/user.controller.js @@ -1,5 +1,8 @@ import prisma from '../config/prismaClient.js'; -import { uploadToCloudinary } from '../utils/cloudinary.utils.js'; +import { + deleteFromCloudinary, + uploadToCloudinary, +} from '../utils/cloudinary.utils.js'; import { comparePassword, hashPassword } from '../utils/password.utils.js'; import { updatePasswordValidation, @@ -414,3 +417,42 @@ export const uploadUserProfilePic = async (req, res, next) => { * @method DELETE * @access private - Requires admin or user himself */ +export const deleteUserProfilePic = async (req, res, next) => { + try { + const { userId } = req.params; + + // Validate userId + if (!userId) { + return res.status(400).json({ + success: false, + message: 'User ID is required', + }); + } + + // Check if user exists and is not deleted + const user = await prisma.user.findFirst({ + where: { + id: userId, + deletedAt: null, + }, + }); + + if (!user || !user.profilePic) { + return res.status(404).json({ message: 'Profile picture not found' }); + } + + await deleteFromCloudinary(user.profilePic); + + const updatedUser = await prisma.user.update({ + where: { id: userId }, + data: { profilePic: null }, + }); + + res.status(200).json({ + message: 'Profile picture deleted successfully', + user: updatedUser, + }); + } catch (error) { + next(error); + } +}; diff --git a/src/routes/user.routes.js b/src/routes/user.routes.js index c098f1d..55bd8dc 100644 --- a/src/routes/user.routes.js +++ b/src/routes/user.routes.js @@ -1,5 +1,6 @@ import { Router } from 'express'; import { + deleteUserProfilePic, getAllUsers, getUserById, restoreUser, @@ -64,4 +65,11 @@ router.post( verifyUserPermission, uploadUserProfilePic, ); + +router.delete( + '/api/users/:userId/profile-picture', + verifyAccessToken, + verifyUserPermission, + deleteUserProfilePic, +); export default router;