From 16f10c50f7f24b1428f8394277d7db1945ffbe7a Mon Sep 17 00:00:00 2001 From: Emnaghz Date: Sat, 21 Sep 2024 12:38:24 +0100 Subject: [PATCH] fix: improve code + add requested changes --- api/src/user/controllers/role.controller.ts | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) diff --git a/api/src/user/controllers/role.controller.ts b/api/src/user/controllers/role.controller.ts index 7fe36c3..d159534 100644 --- a/api/src/user/controllers/role.controller.ts +++ b/api/src/user/controllers/role.controller.ts @@ -19,8 +19,8 @@ import { Patch, Query, UseInterceptors, - Session, ForbiddenException, + Session, } from '@nestjs/common'; import { CsrfCheck } from '@tekuconcept/nestjs-csrf'; import { Session as ExpressSession } from 'express-session'; @@ -148,11 +148,16 @@ export class RoleController extends BaseController { @Delete(':id') @HttpCode(204) async deleteOne(@Param('id') id: string, @Session() session: ExpressSession) { - const roles = ( - await this.userService.findOneAndPopulate(session.passport?.user?.id, [ - 'roles', - ]) - ).roles.map((role) => role.id); + const currentUser = await this.userService.findOneAndPopulate( + session.passport.user.id, + ['roles'], + ); + if (!currentUser) { + throw new NotFoundException('User not found'); + } + + const roles = currentUser.roles.map((role) => role.id); + if (roles.includes(id)) { throw new ForbiddenException("Your account's role can't be deleted"); } else {