Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(api): Add NotFound exception on passing an invalid roleId while inviting user in workspace #408

Merged
merged 3 commits into from
Aug 17, 2024

Conversation

PriyobrotoKar
Copy link
Contributor

Description

Added validation to ensure that If a workspace role is provided in the roleIds array doesn't exist, a NotFoundException is thrown.

Fixes #405

Dependencies

No new dependencies were added.

Future Improvements

Mention any improvements to be done in future related to any file/feature

Mentions

Mention and tag the people

Screenshots of relevant screens

Add screenshots of relevant screens

Developer's checklist

  • My PR follows the style guidelines of this project
  • I have performed a self-check on my work

If changes are made in the code:

  • I have followed the coding guidelines
  • My changes in code generate no new warnings
  • My changes are breaking another fix/feature of the project
  • I have added test cases to show that my feature works
  • I have added relevant screenshots in my PR
  • There are no UI/UX issues

Documentation Update

  • This PR requires an update to the documentation at docs.keyshade.xyz
  • I have made the necessary updates to the documentation, or no documentation changes are required.

Copy link
Contributor

PR Reviewer Guide 🔍

⏱️ Estimated effort to review: 2 🔵🔵⚪⚪⚪
🧪 No relevant tests
🔒 No security concerns identified
⚡ Key issues to review

Code Duplication
The code for checking valid roles is duplicated in two different methods. Consider extracting this logic into a separate method to improve maintainability.

Performance Concern
The role validation involves multiple database queries and array operations. For large workspaces with many roles, this could potentially impact performance.

Copy link
Contributor

codiumai-pr-agent-free bot commented Aug 16, 2024

PR Code Suggestions ✨

CategorySuggestion                                                                                                                                    Score
Enhancement
✅ Extract role validation logic into a separate method for better code organization and reusability
Suggestion Impact:The role validation logic was extracted into a separate method named `findInvalidWorkspaceRoles`, improving code reusability and maintainability.

code diff:

+    const invalidRoles = await this.findInvalidWorkspaceRoles(
+      workspace.id,
+      roleIds
     )
 
     if (invalidRoles.length > 0) {
@@ -1000,18 +991,9 @@
         )
       }
 
-      //Check if the member has valid roles
-      const roles = await this.prisma.workspaceRole.findMany({
-        where: {
-          id: {
-            in: member.roleIds
-          },
-          workspaceId: workspace.id
-        }
-      })
-
-      const invalidRoles = member.roleIds.filter(
-        (id) => !roles.map((role) => role.id).includes(id)
+      const invalidRoles = await this.findInvalidWorkspaceRoles(
+        workspace.id,
+        member.roleIds
       )
 
       if (invalidRoles.length > 0) {
@@ -1085,6 +1067,26 @@
     }
   }
 
+  private async findInvalidWorkspaceRoles(
+    workspaceId: string,
+    roleIds: string[]
+  ) {
+    const roles = await this.prisma.workspaceRole.findMany({
+      where: {
+        id: {
+          in: roleIds
+        },
+        workspaceId: workspaceId
+      }
+    })
+
+    const roleIdSet = new Set(roles.map((role) => role.id))
+
+    const invalidRoles = roleIds.filter((id) => !roleIdSet.has(id))
+
+    return invalidRoles

Consider extracting the role validation logic into a separate method to improve code
reusability and maintainability. This method can be used in both the update and
invite scenarios.

apps/api/src/workspace/service/workspace.service.ts [418-435]

-const roles = await this.prisma.workspaceRole.findMany({
-  where: {
-    id: {
-      in: roleIds
-    },
-    workspaceId: workspace.id
+await this.validateWorkspaceRoles(workspace, roleIds);
+
+// New method to be added to the class:
+private async validateWorkspaceRoles(workspace: Workspace, roleIds: string[]): Promise<void> {
+  const roles = await this.prisma.workspaceRole.findMany({
+    where: {
+      id: { in: roleIds },
+      workspaceId: workspace.id
+    }
+  });
+
+  const invalidRoles = roleIds.filter((id) => !roles.map((role) => role.id).includes(id));
+
+  if (invalidRoles.length > 0) {
+    throw new NotFoundException(
+      `Workspace ${workspace.name} (${workspace.id}) does not have roles ${invalidRoles.join(', ')}`
+    );
   }
-})
-
-const invalidRoles = roleIds.filter(
-  (id) => !roles.map((role) => role.id).includes(id)
-)
-
-if (invalidRoles.length > 0) {
-  throw new NotFoundException(
-    `Workspace ${workspace.name} (${workspace.id}) does not have roles ${invalidRoles.join(', ')}`
-  )
 }
 
  • Apply this suggestion
Suggestion importance[1-10]: 7

Why:

7
Performance
✅ Use Set for more efficient role ID comparison

Use Set data structure for more efficient role ID comparison instead of using
Array.prototype.includes().

apps/api/src/workspace/service/workspace.service.ts [427-429]

-const invalidRoles = roleIds.filter(
-  (id) => !roles.map((role) => role.id).includes(id)
-)
+const roleIdSet = new Set(roles.map((role) => role.id));
+const invalidRoles = roleIds.filter((id) => !roleIdSet.has(id));
 

[Suggestion has been applied]

Suggestion importance[1-10]: 7

Why:

7
Best practice
Use a more appropriate exception type for invalid role IDs

Consider using a more specific error type like BadRequestException instead of
NotFoundException when invalid role IDs are provided, as it's more appropriate for
this scenario.

apps/api/src/workspace/service/workspace.service.ts [431-435]

 if (invalidRoles.length > 0) {
-  throw new NotFoundException(
-    `Workspace ${workspace.name} (${workspace.id}) does not have roles ${invalidRoles.join(', ')}`
+  throw new BadRequestException(
+    `Invalid role IDs provided for workspace ${workspace.name} (${workspace.id}): ${invalidRoles.join(', ')}`
   )
 }
 
  • Apply this suggestion
Suggestion importance[1-10]: 7

Why:

7
Security
Add a limit to the number of role IDs that can be processed at once

Consider adding a limit to the number of role IDs that can be processed at once to
prevent potential performance issues or abuse.

apps/api/src/workspace/service/workspace.service.ts [418-425]

+const MAX_ROLES = 50; // Adjust this value as needed
+if (roleIds.length > MAX_ROLES) {
+  throw new BadRequestException(`Cannot process more than ${MAX_ROLES} roles at once.`);
+}
 const roles = await this.prisma.workspaceRole.findMany({
   where: {
     id: {
       in: roleIds
     },
     workspaceId: workspace.id
   }
 })
 
  • Apply this suggestion
Suggestion importance[1-10]: 7

Why:

7

@PriyobrotoKar
Copy link
Contributor Author

@rajdip-b I have made those changes.

@rajdip-b rajdip-b merged commit 0b2e4af into keyshade-xyz:develop Aug 17, 2024
4 checks passed
rajdip-b pushed a commit that referenced this pull request Sep 5, 2024
rajdip-b pushed a commit that referenced this pull request Sep 5, 2024
## [2.4.0](v2.3.0...v2.4.0) (2024-09-05)

### 🚀 Features

* **api-client:** Create controller for Event module ([#399](#399)) ([122df35](122df35))
* **api-client:** Create controller for Integration module ([#397](#397)) ([697d38b](697d38b))
* **api-client:** Create controller for Project module ([#370](#370)) ([fa25866](fa25866))
* **api-client:** Create controller for Secret module ([#396](#396)) ([7e929c0](7e929c0))
* **api-client:** Create controller for Variable module ([#395](#395)) ([3e114d9](3e114d9))
* **api:** Add global search in workspace ([c49962b](c49962b))
* **api:** Add max page size ([#377](#377)) ([ed18eb0](ed18eb0))
* **cli:** Add functionality to operate on Environments ([#324](#324)) ([4c6f3f8](4c6f3f8))
* **cli:** Quit on decryption failure ([#381](#381)) ([1349d15](1349d15))

### 🐛 Bug Fixes

* **api-client:** Fixed broken export ([096df2c](096df2c))
* **api:** Add NotFound exception on passing an invalid roleId while inviting user in workspace ([#408](#408)) ([ab441db](ab441db))
* **cli:** Fixed missing module ([f7a091f](f7a091f))
* **platform:**  Build failure in platform ([#385](#385)) ([90dcb2c](90dcb2c))

### 🔧 Miscellaneous Chores

* Add api client build script and updated CI ([da0e27a](da0e27a))
* **api:** Reorganized import using path alias ([d5befd1](d5befd1))
* **ci:** Update CLI CI name ([8f4c456](8f4c456))
* **cli:** Add Zod validation to parseInput function ([#362](#362)) ([34e6c39](34e6c39))
* Fixed api client tests and rearranged controllers ([1307604](1307604))
* Housekeeping ([c5f1330](c5f1330))
* **platform:** Added strict null check ([072254f](072254f))
* **web:** Added strict null check ([7e12b47](7e12b47))

### 🔨 Code Refactoring

* **api:** Update logic for forking projects ([#398](#398)) ([4cf3838](4cf3838))
Kiranchaudhary537 pushed a commit to Kiranchaudhary537/keyshade that referenced this pull request Oct 13, 2024
Kiranchaudhary537 pushed a commit to Kiranchaudhary537/keyshade that referenced this pull request Oct 13, 2024
## [2.4.0](keyshade-xyz/keyshade@v2.3.0...v2.4.0) (2024-09-05)

### 🚀 Features

* **api-client:** Create controller for Event module ([keyshade-xyz#399](keyshade-xyz#399)) ([122df35](keyshade-xyz@122df35))
* **api-client:** Create controller for Integration module ([keyshade-xyz#397](keyshade-xyz#397)) ([697d38b](keyshade-xyz@697d38b))
* **api-client:** Create controller for Project module ([keyshade-xyz#370](keyshade-xyz#370)) ([fa25866](keyshade-xyz@fa25866))
* **api-client:** Create controller for Secret module ([keyshade-xyz#396](keyshade-xyz#396)) ([7e929c0](keyshade-xyz@7e929c0))
* **api-client:** Create controller for Variable module ([keyshade-xyz#395](keyshade-xyz#395)) ([3e114d9](keyshade-xyz@3e114d9))
* **api:** Add global search in workspace ([c49962b](keyshade-xyz@c49962b))
* **api:** Add max page size ([keyshade-xyz#377](keyshade-xyz#377)) ([ed18eb0](keyshade-xyz@ed18eb0))
* **cli:** Add functionality to operate on Environments ([keyshade-xyz#324](keyshade-xyz#324)) ([4c6f3f8](keyshade-xyz@4c6f3f8))
* **cli:** Quit on decryption failure ([keyshade-xyz#381](keyshade-xyz#381)) ([1349d15](keyshade-xyz@1349d15))

### 🐛 Bug Fixes

* **api-client:** Fixed broken export ([096df2c](keyshade-xyz@096df2c))
* **api:** Add NotFound exception on passing an invalid roleId while inviting user in workspace ([keyshade-xyz#408](keyshade-xyz#408)) ([ab441db](keyshade-xyz@ab441db))
* **cli:** Fixed missing module ([f7a091f](keyshade-xyz@f7a091f))
* **platform:**  Build failure in platform ([keyshade-xyz#385](keyshade-xyz#385)) ([90dcb2c](keyshade-xyz@90dcb2c))

### 🔧 Miscellaneous Chores

* Add api client build script and updated CI ([da0e27a](keyshade-xyz@da0e27a))
* **api:** Reorganized import using path alias ([d5befd1](keyshade-xyz@d5befd1))
* **ci:** Update CLI CI name ([8f4c456](keyshade-xyz@8f4c456))
* **cli:** Add Zod validation to parseInput function ([keyshade-xyz#362](keyshade-xyz#362)) ([34e6c39](keyshade-xyz@34e6c39))
* Fixed api client tests and rearranged controllers ([1307604](keyshade-xyz@1307604))
* Housekeeping ([c5f1330](keyshade-xyz@c5f1330))
* **platform:** Added strict null check ([072254f](keyshade-xyz@072254f))
* **web:** Added strict null check ([7e12b47](keyshade-xyz@7e12b47))

### 🔨 Code Refactoring

* **api:** Update logic for forking projects ([keyshade-xyz#398](keyshade-xyz#398)) ([4cf3838](keyshade-xyz@4cf3838))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

API: Error while inviting user to workspace
2 participants