Skip to content

tenant-admin-flows-added#698

Open
MallanagoudaB wants to merge 2 commits into
developfrom
tenantAdminFlow
Open

tenant-admin-flows-added#698
MallanagoudaB wants to merge 2 commits into
developfrom
tenantAdminFlow

Conversation

@MallanagoudaB
Copy link
Copy Markdown
Collaborator

@MallanagoudaB MallanagoudaB commented Mar 2, 2026

Description

These recommendations are intended to promote code quality and team communication during software development. They cover a variety of topics, including ensuring that pull requests are submitted to the correct branch, documenting new methods, preserving consistency across many services, and avoiding typical blunders like accessing APIs or DB queries within loops. Sensitive data should not be uploaded, and changes to environment variables or database models should be executed consistently. Teams may work more effectively and develop higher-quality software by adhering to these standards.

Type of change

Please choose appropriate options.

  • Bug fix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • Enhancement (additive changes to improve performance)
  • This change requires a documentation update

Checklist

  • It's critical to avoid making needless file modifications in contributions, such as adding new lines, console logs, or additional spaces, to guarantee cleaner and more efficient code. Furthermore, eliminating unnecessary imports from a file might enhance code readability and efficiency.
  • Ensure that the pull request is assigned to the right base branch and that the development branch name contains the JIRA Task Id. Furthermore, each commit message should include the JIRA Task Id in the manner "ED-100: message".
  • Only update packages if it is mentioned and authorized in the design document, and make sure that you have the required permissions.
  • Avoid making API and database queries inside a loop as it can lead to performance issues and slow down the system.
  • When calling another function inside a given function, add comments explaining the purpose and meaning of the passed arguments and expected return values.
  • If adding a blank argument in a function, add a comment explaining the reason for the blank argument.
  • Before submitting a pull request, do a self-review of your code to ensure there are no conflicts with the base branch and all comments have been addressed.
  • Before merging a pull request, it's important to have other team members review it to catch any potential errors or issues
  • To maintain code integrity, it's important to remove all related changes when removing code during a code review.
  • If new constants, endpoints, or utility functions are introduced, it is important to check if they already exist in the service to avoid any duplication.
  • Whenever a new environment variable is added to a service, it's important to ensure that the necessary changes are made to related files such as ".env.sample" and "envVariables.js" to maintain consistency and avoid errors. Additionally, the new environment variable should be added to the devops repository to ensure that it is properly documented and accessible to the team.
  • When adding a new function to a service, it is important to document it with relevant information such as the name, parameters, and return value in a consistent format across all services. Additionally, if there are any changes to the API response, ensure that the documentation in the controllers is updated accordingly.
  • Write a clear and concise commit message that describes the changes made.
  • Maintain consistent function signature and code across all services when adding a function to multiple services. Implement changes to database models in all services that use the same model.
  • Use only let and const. Do not use var.
  • Make common functions for repetitive code blocks.
  • Avoid uploading sensitive information such as secret tokens or passwords in pull requests to ensure data security.
  • Maintain consistent indentation and spacing throughout the code.

Summary by CodeRabbit

Release Notes

  • Enhancements
    • Improved role-based access control for admin and tenant admin users with enhanced tenant detail retrieval.
    • Strengthened organization validation and scope management with better filtering and error handling.
    • Added tenant-scoped header support for survey service operations to improve tenant data isolation.

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Mar 2, 2026

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

The PR refactors role-based tenant detail retrieval across utility and service files by explicitly differentiating ADMIN_ROLE and TENANT_ADMIN access patterns. It extends TENANT_ADMIN support to organization validation and service headers, introduces organization ID normalization, and adjusts token-passing logic in middleware calls.

Changes

Cohort / File(s) Summary
Program Solution Utilities
generics/helpers/programSolutionUtilities.js
Replaced combined admin/tenant-admin role checks with explicit branches for tenant detail retrieval. ADMIN_ROLE fetches with token; TENANT_ADMIN fetches without. Centralized validation post-branching. Organization and entity validation logic preserved but now role-dependent.
Solution and Template Utilities
generics/helpers/solutionAndProjectTemplateUtils.js
Generalized scope organization fetching to support both ADMIN_ROLE and TENANT_ADMIN. Added conditional role-based fetchTenantDetails invocation with explicit organization lowercase normalization and fallback to user tenant org IDs when not provided.
Survey Service
generics/services/survey.js
Extended TENANT_ADMIN role handling in importTemplateToSolution, listSolutions, and updateSolution by adding tenant-scoped headers (x-auth-token and orgId) alongside existing admin/ORG_ADMIN header logic.
Program Helper
module/programs/helper.js
Extended organization validation in setScope to support both ADMIN_ROLE and TENANT_ADMIN via conditional fetchTenantDetails calls, with role-specific flag parameters. Introduces potential undefined reference if neither role is present.
Authenticator Middleware
generics/middleware/authenticator.js
Removed token parameter from validateIfOrgsBelongsToTenant function calls, passing only tenantId and orgId arguments.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~30 minutes

Possibly related PRs

  • tenant org lowercase #579: Overlapping modifications to the same tenant/org handling code across shared utility files with aligned role-based access pattern refactoring.

Suggested reviewers

  • VISHNUDAS-tunerlabs

Poem

🐰 Role-based paths now split with care,
Admin and tenant each have their share,
Organizations normalized, scopes aligned,
Tenant-scoped headers now designed,
Access control refined and fair!

🚥 Pre-merge checks | ✅ 1 | ❌ 2

❌ Failed checks (1 warning, 1 inconclusive)

Check name Status Explanation Resolution
Description check ⚠️ Warning The PR description is entirely a template copy-paste with no actual information about what this PR accomplishes; no type of change is selected, no checklist items are checked, and no meaningful description of the changes is provided. Replace the description with actual details of the changes: explain that the PR adds tenant-admin role support across multiple files, describe the specific refactorings (role-based branching, header augmentation), and check appropriate type-of-change options.
Title check ❓ Inconclusive The title 'tenant-admin-flows-added' is vague and generic; it uses non-descriptive phrasing that doesn't clearly convey what specific functionality or changes were implemented. Replace with a more descriptive title that specifically explains the main change, such as 'Add tenant-admin role support for tenant detail retrieval and scope management' or 'Enable tenant-admin role in organization validation flows'.
✅ Passed checks (1 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch tenantAdminFlow

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@MallanagoudaB
Copy link
Copy Markdown
Collaborator Author

@coderabbitai full review

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Mar 2, 2026

✅ Actions performed

Full review triggered.

Copy link
Copy Markdown

@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: 4

🧹 Nitpick comments (1)
generics/middleware/authenticator.js (1)

558-561: Make token optional behavior explicit in org validation helper.

Line 560 omits token, while validateIfOrgsBelongsToTenant still forwards a token argument internally. This works implicitly but is easy to regress. Consider making the helper explicitly branch on token presence.

Suggested cleanup
- async function validateIfOrgsBelongsToTenant(tenantId, orgId, token) {
+ async function validateIfOrgsBelongsToTenant(tenantId, orgId, token = '') {
   let orgIdArr = Array.isArray(orgId) ? orgId : typeof orgId === 'string' ? orgId.split(',') : []
-  let orgDetails = await userService.fetchTenantDetails(tenantId, token)
+  let orgDetails = token
+    ? await userService.fetchTenantDetails(tenantId, token)
+    : await userService.fetchTenantDetails(tenantId)
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@generics/middleware/authenticator.js` around lines 558 - 561, The call to
validateIfOrgsBelongsToTenant(req.headers['tenantid'], req.headers['orgid'])
should make the optional token handling explicit: detect the token at the call
site (e.g. const token = req.headers['authorization'] || req.headers['token'] )
and then either call validateIfOrgsBelongsToTenant(tenantId, orgId, token) when
token is present or call validateIfOrgsBelongsToTenant(tenantId, orgId) / with
null when not, or alternatively adjust validateIfOrgsBelongsToTenant to accept
an optional third param and branch internally on its presence; update the call
in the authenticator middleware (the invocation shown) to pass the token or
undefined explicitly so token-forwarding is no longer implicit.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@generics/helpers/programSolutionUtilities.js`:
- Around line 56-57: The membership check is case-sensitive: normalize
organization codes from tenantDetails.data.organizations and from
bodyData.organizations (e.g., trim and toLowerCase) before comparing so
casing/whitespace differences don't break validation; update the construction of
validOrgCodes and the isValid check to use the normalized codes (referencing
validOrgCodes, tenantDetails.data.organizations, bodyData.organizations, and
isValid) so you compare normalized values rather than raw strings.

In `@generics/helpers/solutionAndProjectTemplateUtils.js`:
- Around line 330-339: The code may dereference undefined validOrgs when roles
do not include CONSTANTS.common.ADMIN_ROLE or CONSTANTS.common.TENANT_ADMIN;
ensure validOrgs is always defined before checking validOrgs.success by either
initializing validOrgs to a safe default (e.g., { success: false, data: null })
before the role checks or adding an else branch that sets validOrgs
appropriately; update the block around userDetails.userInformation.roles,
CONSTANTS.common.ADMIN_ROLE, CONSTANTS.common.TENANT_ADMIN and the subsequent
validOrgs.success check (and any error handling that follows) to handle the
default case so there are no runtime exceptions when
userService.fetchTenantDetails is not called.

In `@generics/services/survey.js`:
- Around line 62-68: The code calls userDetails.tenantAndOrgInfo.orgId.join(',')
inside the TENANT_ADMIN conditional (when roles includes
CONSTANTS.common.TENANT_ADMIN) which can throw if tenantAndOrgInfo or orgId is
missing or not an array; update each TENANT_ADMIN block (the sections that
assign options.headers with 'x-auth-token' and orgId) to safely guard and
compute the header value by checking userDetails && userDetails.tenantAndOrgInfo
&& Array.isArray(userDetails.tenantAndOrgInfo.orgId) and only call .join(',')
when true, otherwise set a safe default (empty string or omit the header) so it
cannot raise a runtime exception.

In `@module/programs/helper.js`:
- Around line 46-55: The check assumes validOrgs is always assigned; ensure you
handle non-admin roles before dereferencing validOrgs: in the block around
userDetails and the calls to userService.fetchTenantDetails (and the roles
CONSTANTS.common.ADMIN_ROLE / CONSTANTS.common.TENANT_ADMIN), initialize
validOrgs to a safe default (e.g., an object with success=false) or add an else
branch that sets validOrgs appropriately or returns early; then perform the if
(!validOrgs.success) check only after validOrgs is guaranteed to be defined.

---

Nitpick comments:
In `@generics/middleware/authenticator.js`:
- Around line 558-561: The call to
validateIfOrgsBelongsToTenant(req.headers['tenantid'], req.headers['orgid'])
should make the optional token handling explicit: detect the token at the call
site (e.g. const token = req.headers['authorization'] || req.headers['token'] )
and then either call validateIfOrgsBelongsToTenant(tenantId, orgId, token) when
token is present or call validateIfOrgsBelongsToTenant(tenantId, orgId) / with
null when not, or alternatively adjust validateIfOrgsBelongsToTenant to accept
an optional third param and branch internally on its presence; update the call
in the authenticator middleware (the invocation shown) to pass the token or
undefined explicitly so token-forwarding is no longer implicit.

ℹ️ Review info

Configuration used: defaults

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 2ca23dc and cccf93f.

📒 Files selected for processing (5)
  • generics/helpers/programSolutionUtilities.js
  • generics/helpers/solutionAndProjectTemplateUtils.js
  • generics/middleware/authenticator.js
  • generics/services/survey.js
  • module/programs/helper.js

Comment thread generics/helpers/programSolutionUtilities.js
Comment thread generics/helpers/solutionAndProjectTemplateUtils.js Outdated
Comment thread generics/services/survey.js
Comment thread module/programs/helper.js
// Check if user is Admin or Tenant Admin
if (UTILS.validateRoles(userDetails.userInformation.roles, adminTenantAdminRole)) {
// Fetch tenant details to validate organization codes
if (UTILS.validateRoles(userDetails.userInformation.roles, CONSTANTS.common.ADMIN_ROLE)) {
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

@MallanagoudaB Please update the changes as per discussion

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