Skip to content

Commit

Permalink
fix: implement UserPolicy.canDestroy as policy for UserController.des…
Browse files Browse the repository at this point in the history
…troy
  • Loading branch information
rupl committed Dec 6, 2021
1 parent aa308e8 commit 842dd35
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 12 deletions.
24 changes: 12 additions & 12 deletions api/controllers/UserController.js
Original file line number Diff line number Diff line change
Expand Up @@ -494,31 +494,31 @@ module.exports = {
* description: Requested user not found.
*/
async destroy(request, reply) {
// Don't allow admins to delete their account.
if (!request.auth.credentials.is_admin
&& request.auth.credentials._id.toString() !== request.params.id) {
// Find user in DB.
const user = await User.findById(request.params.id);

// User not found.
if (!user) {
logger.warn(
`[UserController->destroy] User ${request.auth.credentials._id.toString()} is not allowed to delete user ${request.params.id}`,
`[UserController->destroy] Could not find user ${request.params.id}`,
{
request,
fail: true,
},
);
throw Boom.forbidden('You are not allowed to delete this account');
throw Boom.notFound();
}

// Find user in DB.
const user = await User.findOne({ _id: request.params.id });

if (!user) {
// User is admin and cannot be deleted.
if (user.is_admin) {
logger.warn(
`[UserController->destroy] Could not find user ${request.params.id}`,
`[UserController->destroy] User ${request.params.id} is an admin and cannot be deleted.`,
{
request,
fail: true,
},
);
throw Boom.notFound();
throw Boom.forbidden();
}

// Notify user that their account was deleted.
Expand All @@ -527,14 +527,14 @@ module.exports = {
// Delete this user.
await user.remove();

// Log the event and return success code.
logger.info(
`[UserController->destroy] Removed user ${request.params.id}`,
{
request,
security: true,
},
);

return reply.response().code(204);
},

Expand Down
1 change: 1 addition & 0 deletions config/routes.js
Original file line number Diff line number Diff line change
Expand Up @@ -398,6 +398,7 @@ module.exports = [
path: '/api/v3/user/{id}',
options: {
pre: [
UserPolicy.canDestroy,
AuthPolicy.isTOTPEnabledAndValid,
],
handler: UserController.destroy,
Expand Down

0 comments on commit 842dd35

Please # to comment.