Skip to content

Refactor AdminHelper.create to add validation, role checks, and event emission#779

Merged
nevil-mathew merged 5 commits intodevelopfrom
admin-create-api
Aug 4, 2025
Merged

Refactor AdminHelper.create to add validation, role checks, and event emission#779
nevil-mathew merged 5 commits intodevelopfrom
admin-create-api

Conversation

@nevil-mathew
Copy link
Collaborator

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

Summary by CodeRabbit

  • New Features

    • Enhanced admin user creation with transactional control, improved validation, and tenant-specific role assignment.
    • Automatic username generation if not provided.
    • User-organization and user-role relationships are now established upon creation.
    • Real-time notifications triggered on new admin user creation.
  • Bug Fixes

    • Improved error handling and validation during admin user creation.
  • Chores

    • Updated database query functions to support additional options and improved error propagation.

@coderabbitai
Copy link

coderabbitai bot commented Aug 4, 2025

Walkthrough

The create method in the AdminHelper class was refactored to add transactional control, validate tenant and admin role existence, check for duplicate users, generate unique usernames if missing, create user and associated user-organization-role mappings, emit an internal event upon user creation, and improve error handling and logging. Additionally, related database query create functions were updated to accept optional Sequelize options and to throw errors after logging instead of returning them.

Changes

Cohort / File(s) Change Summary
Admin User Creation Refactor
src/services/admin.js
Refactored create method to use a database transaction, validate default tenant and admin role, check for duplicate admin users, encrypt email, hash password, generate unique usernames, create user and user-organization-role associations within the transaction, fetch user details post-creation, restore plaintext email in response, broadcast a user creation event, and handle errors with rollback and specific failure responses. Imports were reorganized for clarity.
User-Organization Creation Update
src/database/queries/userOrganization.js
Updated create function to accept an optional options parameter passed to UserOrganization.create. Changed error handling to throw errors after logging instead of returning them. Removed unused import of Op from sequelize.
User-Organization-Role Creation Update
src/database/queries/userOrganizationRole.js
Modified create function to accept an optional options parameter passed to Sequelize create call. Changed error handling to throw errors after logging instead of returning them.
User Creation Update
src/database/queries/users.js
Modified create function to accept an optional options parameter passed to Sequelize User.create. Changed error logging from console.log to console.error. Core logic and error handling otherwise unchanged.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant AdminHelper
    participant DB
    participant EventBus
    participant Env

    Client->>AdminHelper: create(bodyData)
    AdminHelper->>Env: Get default org and tenant codes
    AdminHelper->>DB: Begin transaction
    AdminHelper->>DB: Find default tenant by code and active status
    AdminHelper->>DB: Check for existing admin user with encrypted email and tenant code
    AdminHelper->>DB: Fetch admin role scoped to tenant
    AdminHelper->>DB: Encrypt email, hash password, assign tenant code and role ID
    alt Username missing
        AdminHelper->>DB: Generate unique username
    end
    AdminHelper->>DB: Create user in transaction
    AdminHelper->>DB: Create user-organization mapping in transaction
    AdminHelper->>DB: Create user-organization-role mapping in transaction
    AdminHelper->>DB: Commit transaction
    AdminHelper->>DB: Fetch created user with organization details (excluding password)
    AdminHelper->>EventBus: Broadcast user creation event
    AdminHelper->>Client: Return success response with user data
    alt Error occurs
        AdminHelper->>DB: Rollback transaction if active
        AdminHelper->>Client: Return failure response or rethrow error
    end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~40 minutes

Poem

In the warren of admins, new rules take their place,
With tenants and orgs, each user finds space.
Emails encrypted, roles checked with care,
Unique usernames sprout like carrots everywhere.
Events hop along, as changes unfold,
A garden of logic, robust and bold! 🥕✨

Note

⚡️ Unit Test Generation is now available in beta!

Learn more here, or try it out under "Finishing Touches" below.


📜 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 2a8b00e and 0a96739.

📒 Files selected for processing (3)
  • src/database/queries/userOrganization.js (4 hunks)
  • src/database/queries/userOrganizationRole.js (4 hunks)
  • src/services/admin.js (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
  • src/database/queries/userOrganization.js
  • src/services/admin.js
  • src/database/queries/userOrganizationRole.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 admin-create-api

🪧 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 Refactor AdminHelper.create to add validation, role checks, and event emission Aug 4, 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: 1

🔭 Outside diff range comments (2)
src/services/admin.js (2)

238-241: Improve error handling with context

The generic console.log and rethrow pattern could be enhanced to provide better debugging context.

} catch (error) {
-  console.log(error)
+  console.error('Failed to create admin user:', {
+    error: error.message,
+    stack: error.stack,
+    email: bodyData.email?.toLowerCase()
+  })
  throw error
}

713-749: Inconsistent error handling pattern

These methods return errors directly instead of throwing them like other methods in the class. This inconsistency could lead to unexpected behavior.

Consider maintaining consistent error handling:

} catch (error) {
-  console.error('An error occurred in userDelete:', error)
-  return error
+  console.error('An error occurred in triggerViewRebuild:', error)
+  throw error
}

Also, the error message mentions "userDelete" which appears to be a copy-paste error.

🧹 Nitpick comments (1)
src/services/admin.js (1)

206-209: Avoid direct object mutation

Instead of directly mutating the user object, consider creating a new object to maintain immutability.

-const processedUser = user
-processedUser.email = plaintextEmailId
+const processedUser = {
+  ...user,
+  email: plaintextEmailId
+}
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 21c0aa2 and 6e61a4b.

📒 Files selected for processing (1)
  • src/services/admin.js (2 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
src/services/**

⚙️ CodeRabbit Configuration File

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

Files:

  • src/services/admin.js
🧠 Learnings (1)
📓 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.
🔇 Additional comments (6)
src/services/admin.js (6)

9-40: Well-organized imports structure

The imports are properly categorized into logical sections, which improves code readability and maintainability.


109-125: Proper email handling and tenant validation

Good implementation of email normalization and encryption, along with appropriate tenant validation.


127-145: Effective duplicate user prevention

The duplicate check properly validates against existing admin users within the same tenant.


167-194: Secure user creation with proper relationships

Good implementation with password hashing, automatic username generation, and proper establishment of user-organization-role relationships.


390-578: Well-implemented admin assignment with comprehensive validation

The method properly handles multiple identifier types, validates user and organization existence, prevents duplicate assignments, and correctly manages role assignments. The cache clearing and event broadcasting are appropriately handled.


657-711: Efficient bulk user deactivation implementation

The method properly handles both ID and email-based deactivation with appropriate event broadcasting for dependent systems.

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: 1

🔭 Outside diff range comments (1)
src/services/admin.js (1)

236-237: Replace console.log with structured logging.

Using console.log for error logging in production code is not recommended. Consider using a structured logging library.

-console.log(error)
+logger.error('Failed to create admin user', { error: error.message, stack: error.stack })
♻️ Duplicate comments (1)
src/services/admin.js (1)

161-162: Environment variable validation should happen at startup.

The validation of DEFAULT_ORGANISATION_CODE at runtime can cause unexpected failures. This should be validated during application initialization.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 6e61a4b and 214a8d9.

📒 Files selected for processing (1)
  • src/services/admin.js (2 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
src/services/**

⚙️ CodeRabbit Configuration File

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

Files:

  • src/services/admin.js
🧠 Learnings (2)
📓 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.
📚 Learning: in the elevate-project/user codebase, organizationcode and tenantcode parameters passed to service m...
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.

Applied to files:

  • src/services/admin.js
🔇 Additional comments (1)
src/services/admin.js (1)

9-40: Well-organized import structure!

The categorization of imports into third-party libraries, constants, database queries, services, helpers, and DTOs improves code readability and maintainability.

@nevil-mathew
Copy link
Collaborator Author

@coderabbitai full review

@coderabbitai
Copy link

coderabbitai bot commented Aug 4, 2025

✅ Actions performed

Full review triggered.

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: 3

🔭 Outside diff range comments (1)
src/database/queries/users.js (1)

163-221: Consider adding pagination to findAllUserWithOrganization

The findAllUserWithOrganization function fetches all matching users without pagination, which could cause performance issues with large datasets.

Consider adding optional pagination parameters:

-exports.findAllUserWithOrganization = async (filter, options = {}, tenantCode, raw = false) => {
+exports.findAllUserWithOrganization = async (filter, options = {}, tenantCode, raw = false, page = null, limit = null) => {
 	try {
+		const paginationOptions = {}
+		if (page && limit) {
+			paginationOptions.offset = (page - 1) * limit
+			paginationOptions.limit = parseInt(limit, 10)
+		}
+
 		let users = await database.User.findAll({
 			where: filter,
 			...options,
+			...paginationOptions,
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 21c0aa2 and 2a8b00e.

📒 Files selected for processing (4)
  • src/database/queries/userOrganization.js (1 hunks)
  • src/database/queries/userOrganizationRole.js (1 hunks)
  • src/database/queries/users.js (1 hunks)
  • src/services/admin.js (2 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
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/userOrganizationRole.js
  • src/database/queries/userOrganization.js
  • 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/admin.js
🧠 Learnings (2)
📚 Learning: in the elevate-project/user codebase, organizationcode and tenantcode parameters passed to service m...
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.

Applied to files:

  • src/database/queries/userOrganization.js
  • src/services/admin.js
📚 Learning: the migration for converting tenant_code to a primary key in the entitytype model was already handle...
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/services/admin.js
🧬 Code Graph Analysis (1)
src/database/queries/users.js (4)
src/services/org-admin.js (1)
  • options (284-289)
src/services/user.js (2)
  • options (311-315)
  • options (432-436)
src/services/account.js (2)
  • options (1574-1580)
  • options (2034-2034)
src/services/organization.js (2)
  • options (254-256)
  • options (292-294)
🔇 Additional comments (4)
src/database/queries/users.js (1)

25-32: LGTM! Proper error handling and transaction support

The changes to the create function are well-implemented:

  • Added options parameter for transaction support
  • Improved error logging with console.error
  • Maintains consistent error throwing pattern
src/services/admin.js (3)

9-41: Well-organized imports

Excellent organization of imports into logical groups. This improves code readability and maintainability.


118-154: Comprehensive validation implementation

Excellent implementation of validation checks:

  • Tenant existence and status validation
  • Duplicate user prevention with encrypted email
  • Admin role verification
  • Automatic username generation

182-203: Proper event emission after transaction commit

Good practice to emit the event after the transaction is committed, ensuring data consistency. The event body is properly constructed with all necessary user details.

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.

1 participant