@@ -15,6 +15,7 @@ const {
15
15
setPreviousPasswords,
16
16
generatePassword,
17
17
sendAccountUnlockedEmail,
18
+ deleteUser : deleteUserUtil ,
18
19
} = require ( "../utils/authUtil" ) ;
19
20
20
21
// Constants
@@ -30,11 +31,11 @@ const deleteUser = async (req, res) => {
30
31
try {
31
32
const { id } = req . params ;
32
33
33
- const deletedCount = await User . destroy ( { where : { id } } ) ;
34
+ const deleted = await deleteUserUtil ( id , "Admin Removal" ) ;
34
35
35
36
// If deleted count is 0, user not found
36
- if ( deletedCount === 0 ) {
37
- throw { status : 404 , message : "User not found " } ;
37
+ if ( ! deleted ) {
38
+ throw { status : 404 , message : "Error Removing User. " } ;
38
39
}
39
40
40
41
// User successfully deleted
@@ -226,14 +227,32 @@ const changePassword = async (req, res) => {
226
227
const bulkDeleteUsers = async ( req , res ) => {
227
228
try {
228
229
const { ids } = req . body ;
229
- const deletedCount = await User . destroy ( { where : { id : ids } } ) ;
230
230
231
- // If deleted count is 0, user not found
232
- if ( deletedCount === 0 ) {
233
- throw { status : 404 , message : "Users not found" } ;
231
+ let deletedCount = 0 ;
232
+ let idsCount = ids . length ;
233
+ // Loop through each user and delete
234
+ for ( let id of ids ) {
235
+ const deleted = await deleteUserUtil ( id , "Admin Removal" ) ;
236
+ if ( deleted ) {
237
+ deletedCount ++ ;
238
+ }
234
239
}
240
+
241
+ if ( deletedCount !== idsCount ) {
242
+ res . status ( 207 ) . json ( {
243
+ success : false ,
244
+ message : "Some users could not be deleted" ,
245
+ data : { deletedCount, idsCount } ,
246
+ } ) ;
247
+ }
248
+
249
+ res . status ( 200 ) . json ( {
250
+ success : true ,
251
+ message : "Users deleted successfully" ,
252
+ data : { deletedCount } ,
253
+ } ) ;
235
254
} catch ( err ) {
236
- logger . error ( `Update user applications : ${ err . message } ` ) ;
255
+ logger . error ( `Bulk Delete Users : ${ err . message } ` ) ;
237
256
res
238
257
. status ( err . status || 500 )
239
258
. json ( { success : false , message : err . message } ) ;
0 commit comments