Skip to content

Conversation

@nevil-mathew
Copy link
Collaborator

@nevil-mathew nevil-mathew commented Aug 8, 2025

feat(org-admin): update deactivateUser endpoint to support tenant code

Summary by CodeRabbit

  • New Features

    • Added support for deactivating multiple users at once using either user IDs or email addresses within the same organization and tenant.
    • Automatically ends all active sessions for deactivated users.
  • Improvements

    • Enhanced validation to accept arrays of user IDs and/or emails, ensuring at least one is provided and each entry is valid.
    • More informative responses now indicate which users were deactivated by ID and by email.
    • Refined deactivation logic to handle users by IDs and emails separately with unified processing.
  • Bug Fixes

    • Improved error handling and logging during the deactivation process.

@coderabbitai
Copy link

coderabbitai bot commented Aug 8, 2025

Walkthrough

The changes introduce support for deactivating multiple users by either IDs or emails within an organization. This involves refactoring validation logic, updating the controller and service layers, and adding new helper and query functions for batch deactivation and session cleanup. Method signatures and validation schemas are updated accordingly.

Changes

Cohort / File(s) Change Summary
Controller: Org Admin
src/controllers/v1/org-admin.js
Removed the explicit validation check for presence of id or email in deactivateUser, delegating responsibility for input validation to the validator layer. Now directly calls the service method with request data.
Database Query: User Deactivation
src/database/queries/users.js
Added deactivateUserInOrg function to batch deactivate users by filter, organization, and tenant. Returns the number of affected rows and optionally the list of updated users. Handles querying, updating, and error management for user deactivation in the database.
Helper: User Session Cleanup
src/helpers/userHelper.js
Introduced removeAllUserSessions method to remove all active sessions for one or multiple user IDs within a tenant. Handles session retrieval, Redis key deletion, and database updates for session termination. Returns the count of removed sessions.
Service: Org Admin Deactivation Logic
src/services/org-admin.js
Refactored deactivateUser to accept arrays of IDs and/or emails, perform batch deactivation for each, aggregate results, remove all sessions for affected users, and broadcast a deactivation event. Enhanced error handling and added detailed documentation. Updated method signature and internal logic for multi-user support.
Validation: Org Admin Deactivation
src/validators/v1/org-admin.js
Updated validation logic for deactivateUser to accept and validate optional arrays emails and ids, ensuring at least one is present. Each element is checked for correct type (email format or numeric). Added a custom validator to enforce presence of at least one field.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant Controller
    participant Validator
    participant Service
    participant UserQueries
    participant UserHelper
    participant EventBus

    Client->>Controller: POST /org-admin/deactivateUser {ids, emails}
    Controller->>Validator: Validate request body
    Validator-->>Controller: Validation result
    Controller->>Service: deactivateUser({ids, emails}, tokenInfo)
    Service->>UserQueries: deactivateUserInOrg(filter by ids, org, tenant)
    UserQueries-->>Service: [affectedRows, updatedUsersById]
    Service->>UserQueries: deactivateUserInOrg(filter by emails, org, tenant)
    UserQueries-->>Service: [affectedRows, updatedUsersByEmail]
    Service->>UserHelper: removeAllUserSessions(allDeactivatedUserIds, tenant)
    UserHelper-->>Service: {success, removedCount}
    Service->>EventBus: broadcast deactivateUpcomingSession (userIds)
    Service-->>Controller: Success/Failure response
    Controller-->>Client: Response
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~40 minutes

Poem

Oh, what a hop in the admin's domain,
Batch deactivation, no effort in vain!
By emails or IDs, users retire,
Sessions are ended, as logs require.
With helpers and queries, the logic is neat—
This bunny's review is now complete! 🐇✨

Note

🔌 MCP (Model Context Protocol) integration is now available in Early Access!

Pro users can now connect to remote MCP servers under the Integrations page to get reviews and chat conversations that understand additional development context.


📜 Recent review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 908ef73 and 8e2c8f0.

📒 Files selected for processing (1)
  • src/database/queries/users.js (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/database/queries/users.js
✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch deactivate-user

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai generate unit tests to generate unit tests for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@coderabbitai coderabbitai bot changed the title @coderabbitai Add support for batch user deactivation by IDs or emails in organizations Aug 8, 2025
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 7

🧹 Nitpick comments (2)
src/services/org-admin.js (2)

456-456: Remove debug logging

Avoid console.log in services. Use a logger or remove.

-        console.log(rowsAffected, updatedUsers)

443-456: Minor: reduce duplicated updates and payload

  • If an ID and its email are both provided, the second update may re-touch the same rows. Not critical, but you can de-duplicate target IDs upfront or exclude already-updated IDs/emails on the second call.
  • After adjusting deactivateUserInOrg to return IDs (see query comment), you can avoid returning Sequelize instances and simplify to:
- const [rowsAffected, updatedUsers] = await userQueries.deactivateUserInOrg(..., true)
- updatedByIds.push(...updatedUsers.map((user) => user.id))
+ const [rowsAffected, updatedIds] = await userQueries.deactivateUserInOrg(..., true)
+ updatedByIds.push(...updatedIds)

Also applies to: 462-475

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 011713b and d9a6e20.

📒 Files selected for processing (5)
  • src/controllers/v1/org-admin.js (0 hunks)
  • src/database/queries/users.js (1 hunks)
  • src/helpers/userHelper.js (2 hunks)
  • src/services/org-admin.js (2 hunks)
  • src/validators/v1/org-admin.js (1 hunks)
💤 Files with no reviewable changes (1)
  • src/controllers/v1/org-admin.js
🧰 Additional context used
📓 Path-based instructions (3)
src/validators/**

⚙️ CodeRabbit Configuration File

Validate all incoming data thoroughly. Check for missing or incomplete validation rules.

Files:

  • src/validators/v1/org-admin.js
src/database/queries/**

⚙️ CodeRabbit Configuration File

Review database queries for performance. Check for N+1 problems and ensure indexes can be used.

Files:

  • src/database/queries/users.js
src/services/**

⚙️ CodeRabbit Configuration File

This is core business logic. Please check for correctness, efficiency, and potential edge cases.

Files:

  • src/services/org-admin.js
🧠 Learnings (5)
📓 Common learnings
Learnt from: nevil-mathew
PR: ELEVATE-Project/user#776
File: src/database/models/entityType.js:38-38
Timestamp: 2025-07-31T08:43:35.971Z
Learning: The migration for converting tenant_code to a primary key in the EntityType model was already handled in a previous PR, not in the current refactoring PR that focuses on organization codes instead of organization IDs.
Learnt from: nevil-mathew
PR: ELEVATE-Project/user#776
File: src/services/entities.js:18-23
Timestamp: 2025-07-31T08:44:36.982Z
Learning: In the ELEVATE-Project/user codebase, organizationCode and tenantCode parameters passed to service methods always come from req.decodedToken.organization_code and req.decodedToken.tenant_code, which are guaranteed to be present after token validation. Additional validation for these parameters in service methods is unnecessary as the token validation process ensures they are always available.
📚 Learning: 2025-08-06T07:27:08.445Z
Learnt from: nevil-mathew
PR: ELEVATE-Project/user#783
File: src/database/queries/fileUpload.js:40-59
Timestamp: 2025-08-06T07:27:08.445Z
Learning: In the ELEVATE-Project/user repository, pagination is handled by src/middlewares/pagination.js which validates page and limit parameters and sets req.pageNo and req.pageSize. Service methods like getBulkInvitesFilesList use these pre-validated values when calling database query functions like listUploads. Additional parameter validation in database query functions is redundant since the middleware handles validation upstream.

Applied to files:

  • src/helpers/userHelper.js
  • src/validators/v1/org-admin.js
📚 Learning: 2025-08-06T07:27:08.445Z
Learnt from: nevil-mathew
PR: ELEVATE-Project/user#783
File: src/database/queries/fileUpload.js:40-59
Timestamp: 2025-08-06T07:27:08.445Z
Learning: In the ELEVATE-Project/user repository, pagination parameters are validated by src/middlewares/pagination.js middleware which sets req.pageNo and req.pageSize. Service methods like getBulkInvitesFilesList use these pre-validated values when calling database query functions. Database query functions like listUploads receive already-validated pagination parameters, so additional validation in the query layer is redundant.

Applied to files:

  • src/helpers/userHelper.js
  • src/validators/v1/org-admin.js
📚 Learning: 2025-08-06T07:28:13.285Z
Learnt from: nevil-mathew
PR: ELEVATE-Project/user#783
File: src/database/queries/fileUpload.js:40-59
Timestamp: 2025-08-06T07:28:13.285Z
Learning: In the ELEVATE-Project/user repository, pagination parameters (page and limit) are validated in src/middlewares/pagination.js middleware which is applied globally to all routes. The middleware sets req.pageNo and req.pageSize with proper validation, so database query functions like listUploads don't need additional parameter validation.

Applied to files:

  • src/validators/v1/org-admin.js
📚 Learning: 2025-07-31T08:43:35.971Z
Learnt from: nevil-mathew
PR: ELEVATE-Project/user#776
File: src/database/models/entityType.js:38-38
Timestamp: 2025-07-31T08:43:35.971Z
Learning: The migration for converting tenant_code to a primary key in the EntityType model was already handled in a previous PR, not in the current refactoring PR that focuses on organization codes instead of organization IDs.

Applied to files:

  • src/database/queries/users.js
  • src/services/org-admin.js
🔇 Additional comments (2)
src/database/queries/users.js (1)

549-571: No additional indexes needed for deactivateUserInOrg

The user_organizations table already has the following in place (via 20250506095633-update-relations.js and the PK on creation):

  • Primary key on (tenant_code, user_id, organization_code)
  • idx_user_organizations_org_tenant on (organization_code, tenant_code)
  • idx_user_organizations_user_tenant on (user_id, tenant_code)
  • idx_user_organizations_tenant_code on (tenant_code)

The users table uses its primary key (id) for lookups; we don’t filter by tenant_code on users in this query, so no extra index is required.

src/services/org-admin.js (1)

404-431: Good docstring

The method-level documentation is clear and accurately reflects behavior and limitations.

@ELEVATE-Project ELEVATE-Project deleted a comment from coderabbitai bot Aug 8, 2025
@ELEVATE-Project ELEVATE-Project deleted a comment from coderabbitai bot Aug 8, 2025
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

♻️ Duplicate comments (2)
src/validators/v1/org-admin.js (2)

31-31: Apply request-body whitelist and block spoofed tenant codes

Add the whitelist filter to align with other handlers and ensure only allowed keys (emails/ids) are processed. This also prevents clients from injecting tenant_code/organization_code via body; those should come from req.decodedToken per our conventions.

Apply this diff:

 deactivateUser: (req) => {
+    req.body = filterRequestBody(req.body, orgAdmin.deactivateUser)
     req.checkBody('emails').optional().isArray().withMessage('The "emails" field must be an array, if provided.')

Run to verify the whitelist entry and allowed keys:

#!/bin/bash
set -euo pipefail

# Locate blacklistConfig
fd -a blacklistConfig src

# Show deactivateUser config context
rg -n "deactivateUser" src/constants/blacklistConfig.* -n -A 8 -B 8 || true

# Confirm that 'emails' and 'ids' are allowed and tenant keys are NOT allowed
rg -n "'emails'|'ids'" src/constants/blacklistConfig.* || true
rg -n "tenant(Code|_code)|organization(Code|_code)" src/constants/blacklistConfig.* || true

40-43: Stricter ID validation: enforce positive integers (no floats/negatives)

Use isInt({ min: 1 }) instead of isNumeric() and update the error message. Optionally coerce to integers.

-    .isNumeric()
-    .withMessage('Each item in the "ids" array must be a numeric value.')
+    .isInt({ min: 1 })
+    .withMessage('Each item in the "ids" array must be a positive integer.')
+    .toInt()
🧹 Nitpick comments (1)
src/validators/v1/org-admin.js (1)

31-38: Optional hardening: cap batch sizes and normalize input

Prevent oversized payloads and standardize emails. Pick limits that match ops constraints.

-    req.checkBody('emails').optional().isArray().withMessage('The "emails" field must be an array, if provided.')
+    req.checkBody('emails')
+      .optional()
+      .isArray()
+      .withMessage('The "emails" field must be an array, if provided.')
+      .custom(arr => arr.length <= 1000)
+      .withMessage('The "emails" array cannot exceed 1000 items.')
@@
-    req.checkBody('emails.*')
+    req.checkBody('emails.*')
       .optional()
-      .isEmail()
+      .isEmail()
+      .trim()
+      .normalizeEmail()
       .withMessage('Each item in the "emails" array must be a valid email address.')
@@
-    req.checkBody('ids').optional().isArray().withMessage('The "ids" field must be an array, if provided.')
+    req.checkBody('ids')
+      .optional()
+      .isArray()
+      .withMessage('The "ids" field must be an array, if provided.')
+      .custom(arr => arr.length <= 1000)
+      .withMessage('The "ids" array cannot exceed 1000 items.')

Note: If your express-validator version lacks normalizeEmail(), keep trim() only.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between d9a6e20 and 908ef73.

📒 Files selected for processing (3)
  • src/database/queries/users.js (1 hunks)
  • src/services/org-admin.js (2 hunks)
  • src/validators/v1/org-admin.js (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/database/queries/users.js
  • src/services/org-admin.js
🧰 Additional context used
📓 Path-based instructions (1)
src/validators/**

⚙️ CodeRabbit Configuration File

Validate all incoming data thoroughly. Check for missing or incomplete validation rules.

Files:

  • src/validators/v1/org-admin.js
🧠 Learnings (3)
📓 Common learnings
Learnt from: nevil-mathew
PR: ELEVATE-Project/user#776
File: src/database/models/entityType.js:38-38
Timestamp: 2025-07-31T08:43:35.971Z
Learning: The migration for converting tenant_code to a primary key in the EntityType model was already handled in a previous PR, not in the current refactoring PR that focuses on organization codes instead of organization IDs.
Learnt from: nevil-mathew
PR: ELEVATE-Project/user#776
File: src/services/entities.js:18-23
Timestamp: 2025-07-31T08:44:36.982Z
Learning: In the ELEVATE-Project/user codebase, organizationCode and tenantCode parameters passed to service methods always come from req.decodedToken.organization_code and req.decodedToken.tenant_code, which are guaranteed to be present after token validation. Additional validation for these parameters in service methods is unnecessary as the token validation process ensures they are always available.
Learnt from: nevil-mathew
PR: ELEVATE-Project/user#790
File: src/helpers/userHelper.js:10-10
Timestamp: 2025-08-08T13:06:32.884Z
Learning: In ELEVATE-Project/user, avoid potential circular dependencies between src/helpers/userHelper.js and src/services/user-sessions by extracting shared session cleanup logic (finding active sessions, deleting Redis keys, ending sessions) into a dedicated utility (e.g., helpers/sessionCleanup.js) that both layers can consume.
Learnt from: nevil-mathew
PR: ELEVATE-Project/user#790
File: src/helpers/userHelper.js:117-156
Timestamp: 2025-08-08T15:12:44.400Z
Learning: In ELEVATE-Project/user, prefer extracting shared session teardown (find active sessions, delete Redis keys, mark ended_at) into helpers/sessionCleanup.js so both helpers and services use it, preventing upward (helper→service) dependencies and avoiding circular imports.
📚 Learning: 2025-08-06T07:27:08.445Z
Learnt from: nevil-mathew
PR: ELEVATE-Project/user#783
File: src/database/queries/fileUpload.js:40-59
Timestamp: 2025-08-06T07:27:08.445Z
Learning: In the ELEVATE-Project/user repository, pagination is handled by src/middlewares/pagination.js which validates page and limit parameters and sets req.pageNo and req.pageSize. Service methods like getBulkInvitesFilesList use these pre-validated values when calling database query functions like listUploads. Additional parameter validation in database query functions is redundant since the middleware handles validation upstream.

Applied to files:

  • src/validators/v1/org-admin.js
📚 Learning: 2025-08-06T07:27:08.445Z
Learnt from: nevil-mathew
PR: ELEVATE-Project/user#783
File: src/database/queries/fileUpload.js:40-59
Timestamp: 2025-08-06T07:27:08.445Z
Learning: In the ELEVATE-Project/user repository, pagination parameters are validated by src/middlewares/pagination.js middleware which sets req.pageNo and req.pageSize. Service methods like getBulkInvitesFilesList use these pre-validated values when calling database query functions. Database query functions like listUploads receive already-validated pagination parameters, so additional validation in the query layer is redundant.

Applied to files:

  • src/validators/v1/org-admin.js
🔇 Additional comments (2)
src/validators/v1/org-admin.js (2)

45-54: Good: enforce at least one non-empty identifier array

This custom validator correctly blocks requests where both arrays are missing or empty.


45-54: Verify express-validator array argument support

I wasn’t able to locate express-validator in package.json or lockfiles—please confirm the installed version supports passing an array to req.checkBody(). Versions without this signature will skip the custom validator silently. If your version doesn’t accept req.checkBody(['field1','field2']), update each multi-field check to a single-field call that inspects all required props.

Affected locations:

  • src/validators/v1/org-admin.js (lines 45–54)
  • src/validators/v1/account.js (lines 93–99 & 191–197)
  • src/validators/v1/admin.js (lines 66–72)

Example replacement in org-admin.js:

- req.checkBody(['emails','ids']).custom(() => {
+ req.checkBody('emails').custom((_, { req }) => {
    const { emails, ids } = req.body
    if ((!emails || emails.length === 0) && (!ids || ids.length === 0)) {
      throw new Error('Provide at least one non-empty "emails" or "ids" array.')
    }
    return true
  })

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants