Skip to content

Comments

refactor: platform managed user org admin access#22597

Merged
supalarry merged 18 commits intomainfrom
lauris/cal-6118-refactor-platform-managed-user-admin-permissions
Jul 28, 2025
Merged

refactor: platform managed user org admin access#22597
supalarry merged 18 commits intomainfrom
lauris/cal-6118-refactor-platform-managed-user-admin-permissions

Conversation

@supalarry
Copy link
Contributor

Linear CAL-6118

@supalarry supalarry requested a review from a team July 17, 2025 15:22
@supalarry supalarry requested a review from a team as a code owner July 17, 2025 15:22
@linear
Copy link

linear bot commented Jul 17, 2025

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jul 17, 2025

Walkthrough

This change refactors organization admin and owner permissions for managed users across several modules. It introduces new service and repository methods to check for organization admin/owner roles, enables organization admins to bypass team membership checks when accessing or updating team event types, and modifies endpoints and authorization logic to allow organization admins to view all organization teams and manage team event types. Helper functions and test cases are added to support and verify these behaviors. The changes are focused on backend service, repository, controller, and API handler layers, with some adjustments in example platform code.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Assessment against linked issues

Objective Addressed Explanation
1. Create organization team event type: update create.handler.ts to allow org admin/owner to create team event types without requiring team membership (CAL-6118)
2. Read all organization teams: update organizations-teams.controller.ts so org admins see all org teams, not just those they belong to (CAL-6118)
3. Read team event type: update getEventTypeById.ts and repository/eventType.ts to allow org admins/org owners to read any team event type in their org (CAL-6118)
4. Update team event: update event-types-atom.service.ts to allow org admins/owners to update team event types for teams in their org (CAL-6118)

Assessment against linked issues: Out-of-scope changes

Code Change Explanation
Refactoring and modularization in packages/platform/examples/base/src/pages/api/managed-user.ts These changes improve code structure and add helper functions for managed user/test data setup, but are not directly related to admin permission logic for team event types as described in CAL-6118.
Changes to generateRandomEmail and related logic in packages/platform/examples/base/src/pages/_app.tsx Updates to email generation for test/demo users are unrelated to the admin permission objectives.

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 UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 78971b7 and e482622.

⛔ Files ignored due to path filters (1)
  • yarn.lock is excluded by !**/yarn.lock, !**/*.lock
📒 Files selected for processing (1)
  • apps/api/v2/package.json (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • apps/api/v2/package.json
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
  • GitHub Check: Install dependencies / Yarn install & cache
  • GitHub Check: Socket Security: Pull Request Alerts
✨ Finishing Touches
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch lauris/cal-6118-refactor-platform-managed-user-admin-permissions

🪧 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.
    • @coderabbitai modularize this function.
  • 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.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

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

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

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.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

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.

@graphite-app graphite-app bot requested a review from a team July 17, 2025 15:22
@keithwillcode keithwillcode added core area: core, team members only platform Anything related to our platform plan labels Jul 17, 2025
@graphite-app
Copy link

graphite-app bot commented Jul 17, 2025

Graphite Automations

"Add consumer team as reviewer" took an action on this PR • (07/17/25)

1 reviewer was added to this PR based on Keith Williams's automation.

@delve-auditor
Copy link

delve-auditor bot commented Jul 17, 2025

No security or compliance issues detected. Reviewed everything up to 276b033.

Security Overview
  • 🔎 Scanned files: 14 changed file(s)
Detected Code Changes
Change Type Relevant files
Enhancement ► atoms.module.ts
    Add Organizations Teams Repository
► event-types-atom.service.ts
    Update team event type permissions
► organizations-teams.controller.ts
    Add organization admin team access
► organizations-teams.repository.ts
    Add organization teams pagination with members
► managed-user.ts
    Refactor user creation and add round robin event type
► _app.tsx
    Update email generation with names
Configuration changes ► package.json
    Update platform libraries version

Reply to this PR with @delve-auditor followed by a description of what change you want and we'll auto-submit a change to this PR to implement it.

Copy link
Contributor

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

🧹 Nitpick comments (3)
packages/platform/examples/base/src/pages/_app.tsx (1)

16-27: Consider making the names configurable for better maintainability.

The implementation correctly generates predictable emails with name prefixes. However, the hardcoded names could be made more flexible.

Consider extracting the names to a constant or configuration:

+const DEMO_NAMES = ["keith", "somay", "rajiv", "morgan", "lauris"];
+
function generateRandomEmail(name: string) {
  const localPartLength = 5;
  const domain = ["example.com", "example.net", "example.org"];
  // ... rest of implementation
}

This would make it easier to modify the demo users without changing the function calls.

apps/api/v2/src/modules/atoms/services/event-types-atom.service.ts (1)

78-99: Verify security implications of context switching for organization admins.

This change allows organization admins to operate in the context of the event type's owner rather than their own context. While this aligns with the PR's goal of enhancing org admin access, it's important to ensure:

  1. This doesn't bypass any critical security checks
  2. Audit logs properly reflect who made changes (the admin, not the effective user)
  3. The behavior is clearly documented for API consumers

The logic is sound, but the security implications should be carefully considered.

Consider adding audit logging to track when an org admin operates on behalf of another user. This would help with compliance and debugging.

packages/platform/examples/base/src/pages/api/managed-user.ts (1)

68-75: Use optional chaining for cleaner code.

The static analysis correctly identifies an opportunity to use optional chaining.

-  if (existingUser && existingUser.calcomUserId) {
+  if (existingUser?.calcomUserId) {
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 292073e and 3c3fe83.

📒 Files selected for processing (8)
  • apps/api/v2/src/modules/atoms/services/event-types-atom.service.ts (3 hunks)
  • apps/api/v2/src/modules/organizations/memberships/services/organizations-membership.service.ts (1 hunks)
  • apps/api/v2/src/modules/organizations/teams/index/organizations-teams.controller.ts (3 hunks)
  • apps/api/v2/src/modules/organizations/teams/index/organizations-teams.repository.ts (1 hunks)
  • apps/api/v2/src/modules/organizations/teams/index/services/organizations-teams.service.ts (1 hunks)
  • packages/platform/examples/base/src/pages/_app.tsx (3 hunks)
  • packages/platform/examples/base/src/pages/api/managed-user.ts (4 hunks)
  • packages/trpc/server/routers/viewer/eventTypes/create.handler.ts (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (3)
apps/api/v2/src/modules/organizations/teams/index/organizations-teams.controller.ts (1)
apps/api/v2/src/modules/organizations/memberships/services/organizations-membership.service.ts (1)
  • isOrgAdminOrOwner (30-41)
apps/api/v2/src/modules/atoms/services/event-types-atom.service.ts (2)
apps/api/v2/src/modules/memberships/memberships.repository.ts (1)
  • isUserOrganizationAdmin (50-61)
packages/lib/event-types/getEventTypeById.ts (1)
  • getEventTypeById (36-260)
packages/platform/examples/base/src/pages/api/managed-user.ts (1)
packages/platform/constants/api.ts (2)
  • X_CAL_SECRET_KEY (49-49)
  • X_CAL_CLIENT_ID (50-50)
🪛 Biome (1.9.4)
packages/platform/examples/base/src/pages/api/managed-user.ts

[error] 68-68: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
  • GitHub Check: Check for E2E label
  • GitHub Check: Security Check
🔇 Additional comments (7)
apps/api/v2/src/modules/organizations/memberships/services/organizations-membership.service.ts (1)

30-41: LGTM! Well-implemented role checking method.

The isOrgAdminOrOwner method correctly implements role-based access control by:

  • Reusing existing repository method for consistency
  • Providing clear error handling with descriptive messages
  • Following the established service pattern
  • Using proper return type for boolean checks

This method will enable proper authorization checks across the organization modules.

packages/platform/examples/base/src/pages/_app.tsx (1)

53-57: Email generation calls are consistent with the refactored function.

The updated calls to generateRandomEmail with specific names align well with the function signature change and support the demo user creation workflow.

apps/api/v2/src/modules/organizations/teams/index/services/organizations-teams.service.ts (1)

27-34: LGTM! Method follows established service patterns.

The getPaginatedOrgTeamsWithMembers method correctly:

  • Maintains consistency with existing service methods
  • Uses proper pagination parameters with sensible defaults
  • Delegates to the repository layer appropriately
  • Supports the role-based access control requirements

This method enables organization admins/owners to retrieve all teams with member information.

packages/trpc/server/routers/viewer/eventTypes/create.handler.ts (1)

92-93: LGTM! Authorization logic correctly exempts organization admins.

The updated condition properly implements the organization admin privilege by:

  • Adding !isOrgAdmin check to bypass membership role requirements
  • Maintaining existing system admin and membership role validations
  • Following logical precedence: system admin → org admin → membership role

This change aligns with the PR objective of refactoring platform managed user org admin access.

apps/api/v2/src/modules/organizations/teams/index/organizations-teams.repository.ts (1)

111-122: LGTM! Repository method efficiently retrieves teams with member data.

The findOrgTeamsPaginatedWithMembers method is well-implemented:

  • Correctly filters teams by organization ID
  • Uses selective field inclusion for members (accepted, userId, role) to optimize performance
  • Applies pagination properly with skip/take parameters
  • Follows established repository patterns
  • Supports the role-based access control requirements

The selective member field inclusion is particularly good for performance while providing necessary data for authorization checks.

apps/api/v2/src/modules/organizations/teams/index/organizations-teams.controller.ts (1)

60-63: LGTM! Proper dependency injection.

The OrganizationsMembershipService is correctly injected following NestJS conventions.

packages/platform/examples/base/src/pages/api/managed-user.ts (1)

15-56: Excellent refactoring to reduce code duplication!

The helper function properly consolidates the user creation logic and makes the code more maintainable.

@vercel
Copy link

vercel bot commented Jul 18, 2025

The latest updates on your projects. Learn more about Vercel for Git ↗︎

2 Skipped Deployments
Name Status Preview Comments Updated (UTC)
cal ⬜️ Ignored (Inspect) Jul 28, 2025 10:08am
cal-eu ⬜️ Ignored (Inspect) Jul 28, 2025 10:08am

Copy link
Contributor

@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

🧹 Nitpick comments (2)
packages/lib/server/repository/eventTypeRepository.ts (2)

751-764: Optimize the organization users query for better performance

The nested query with profiles.some could impact performance. Consider adding database indexes and potentially restructuring the query.

  1. Add indexes to improve query performance:

    • Index on Profile.organizationId
    • Index on Team.parentId
    • Composite index on EventType.userId and EventType.teamId
  2. Consider denormalizing the organization relationship on the EventType table for faster queries if this becomes a performance bottleneck.

Would you like me to generate the Prisma schema changes for these indexes?


749-777: Extract organization admin conditions into a separate method

Consider extracting the organization admin condition building logic into a separate private method for better readability and testability.

+  private buildOrganizationAdminConditions(currentOrganizationId: number) {
+    const organizationUsersEventTypesQuery = {
+      AND: [
+        { userId: { not: null } },
+        {
+          owner: {
+            profiles: {
+              some: {
+                organizationId: currentOrganizationId,
+              },
+            },
+          },
+        },
+      ],
+    };
+    
+    const organizationTeamsEventTypesQuery = {
+      AND: [
+        { teamId: { not: null } },
+        {
+          team: {
+            parentId: currentOrganizationId,
+          },
+        },
+      ],
+    };
+    
+    return [organizationUsersEventTypesQuery, organizationTeamsEventTypesQuery];
+  }

   const orgAdminConditions = [];
   if (isUserOrganizationAdmin && currentOrganizationId) {
-    const organizationUsersEventTypesQuery = {
-      AND: [
-        { userId: { not: null } },
-        {
-          owner: {
-            profiles: {
-              some: {
-                organizationId: currentOrganizationId,
-              },
-            },
-          },
-        },
-      ],
-    };
-    const organizationTeamsEventTypesQuery = {
-      AND: [
-        { teamId: { not: null } },
-        {
-          team: {
-            parentId: currentOrganizationId,
-          },
-        },
-      ],
-    };
-    orgAdminConditions.push(organizationUsersEventTypesQuery);
-    orgAdminConditions.push(organizationTeamsEventTypesQuery);
+    orgAdminConditions.push(...this.buildOrganizationAdminConditions(currentOrganizationId));
   }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 276b033 and e084c76.

📒 Files selected for processing (3)
  • packages/lib/event-types/getEventTypeById.ts (1 hunks)
  • packages/lib/server/repository/eventTypeRepository.ts (2 hunks)
  • packages/trpc/server/routers/viewer/eventTypes/create.handler.ts (1 hunks)
📓 Path-based instructions (1)
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit Inference Engine (.cursor/rules/review.mdc)

Flag excessive Day.js use in performance-critical code. Functions like .add, .diff, .isBefore, and .isAfter are slow, especially in timezone mode. Prefer .utc() for better performance. Where possible, replace with native Date and direct .valueOf() comparisons for faster execution. Recommend using native methods or Day.js .utc() consistently in hot paths like loops.

Files:

  • packages/lib/server/repository/eventTypeRepository.ts
🧬 Code Graph Analysis (1)
packages/lib/server/repository/eventTypeRepository.ts (1)
apps/api/v2/src/modules/memberships/memberships.repository.ts (1)
  • isUserOrganizationAdmin (50-61)
🚧 Files skipped from review as they are similar to previous changes (2)
  • packages/lib/event-types/getEventTypeById.ts
  • packages/trpc/server/routers/viewer/eventTypes/create.handler.ts
🧰 Additional context used
📓 Path-based instructions (1)
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit Inference Engine (.cursor/rules/review.mdc)

Flag excessive Day.js use in performance-critical code. Functions like .add, .diff, .isBefore, and .isAfter are slow, especially in timezone mode. Prefer .utc() for better performance. Where possible, replace with native Date and direct .valueOf() comparisons for faster execution. Recommend using native methods or Day.js .utc() consistently in hot paths like loops.

Files:

  • packages/lib/server/repository/eventTypeRepository.ts
🧬 Code Graph Analysis (1)
packages/lib/server/repository/eventTypeRepository.ts (1)
apps/api/v2/src/modules/memberships/memberships.repository.ts (1)
  • isUserOrganizationAdmin (50-61)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
  • GitHub Check: Install dependencies / Yarn install & cache
  • GitHub Check: Socket Security: Pull Request Alerts
🔇 Additional comments (1)
packages/lib/server/repository/eventTypeRepository.ts (1)

471-481: Ignore admin‐status verification in the repository
The findById method is a data-access layer API that intentionally trusts the isUserOrganizationAdmin flag provided by its caller. Authorization (including any necessary MembershipRepository.isUserOrganizationAdmin checks) is performed in the service or controller layer before invoking this repository method. You can safely ignore the previous suggestion to re-verify admin status inside findById.

Likely an incorrect or invalid review comment.

ibex088
ibex088 previously approved these changes Jul 24, 2025
Copy link
Contributor

@ibex088 ibex088 left a comment

Choose a reason for hiding this comment

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

🚀 🚀 🚀

@socket-security
Copy link

Review the following changes in direct dependencies. Learn more about Socket for GitHub.

Diff Package Supply Chain
Security
Vulnerability Quality Maintenance License

View full report

@supalarry supalarry dismissed keithwillcode’s stale review July 28, 2025 11:50

implemented keiths feedback

@supalarry supalarry merged commit 19d7764 into main Jul 28, 2025
41 of 42 checks passed
@supalarry supalarry deleted the lauris/cal-6118-refactor-platform-managed-user-admin-permissions branch July 28, 2025 11:50
@coderabbitai coderabbitai bot mentioned this pull request Aug 29, 2025
3 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

core area: core, team members only platform Anything related to our platform plan ready-for-e2e

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants