Skip to content

Feat/edit provider #372

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

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open

Feat/edit provider #372

wants to merge 4 commits into from

Conversation

SahilKumar000
Copy link
Contributor

@SahilKumar000 SahilKumar000 commented Apr 7, 2025

Description

Added Edit Button for Oauth Provider

Testing

Additional Notes

Summary by CodeRabbit

  • New Features

    • Introduced an editable mode for OAuth settings, allowing users to easily toggle between viewing and updating their integration details with dynamic notifications.
    • Enabled seamless updates for existing OAuth configurations, ensuring smoother integration management.
    • Enhanced Google integration by providing up-to-date statistics on file counts and message volumes.
    • Added support for additional props in the OAuthTab component, improving configurability and data management.
  • Refactor

    • Streamlined state management and validation processes to improve responsiveness and overall user experience.

Copy link

coderabbitai bot commented Apr 7, 2025

Walkthrough

This pull request enhances the OAuth integration functionality across both the frontend and backend. In the frontend, the OAuthTab component and associated OAuthForm have been updated to support an editing mode with optional connector IDs and improved state management. On the backend, new functions and endpoints have been introduced to update OAuth provider configurations, including validation and database updates. Additional changes include new asynchronous calls in the Google integration for fetching file and message counts and minor import updates in the user database module.

Changes

File(s) Change Summary
frontend/src/components/OAuthTab.tsx Updated OAuthTab: changed setOAuthIntegrationStatus prop type, added optional connectorId, introduced isEditing state, and implemented handleEdit and handleFormSuccess for toggling editing mode and conditional rendering of OAuthForm/OAuthButton.
frontend/src/routes/_authenticated/admin/integrations/google.tsx Added asynchronous function updateOAuthForm to update OAuth settings. Modified OAuthForm to accept optional isEditing and connectorId props and updated the OAuthFormData type for enhanced editing mode handling.
server/api/admin.ts, server/integrations/google/index.ts, server/server.ts, server/types.ts Introduced backend OAuth update enhancements: added UpdateOAuthProvider to update provider details (with JWT, connector validation, and drizzle-orm), new PUT /oauth/update and GET /oauth/ endpoints, and a new updateOAuthProvider schema with inferred type UpdateOAuthProviderForm. Also, enhanced Google OAuth ingestion with asynchronous calls to count Drive files and Gmail messages.
server/db/user.ts Added import statements for connectors and type Apps without altering existing functionality.

Sequence Diagram(s)

sequenceDiagram
    participant U as User
    participant T as OAuthTab
    participant F as OAuthForm
    participant API as Server API (/oauth/update)
    participant DB as Database
    
    U->>T: Click "Edit" (Pencil Icon)
    T->>F: Render OAuthForm (enter editing mode)
    U->>F: Submit updated OAuth credentials
    F->>API: Call updateOAuthForm (PUT request)
    API->>DB: Validate and update OAuth provider info
    DB-->>API: Return update confirmation
    API-->>F: Send success response
    F-->>T: Trigger onSuccess, exit editing mode
Loading
sequenceDiagram
    participant S as Server (Google Ingestion)
    participant Drive as Google Drive API
    participant Gmail as Gmail API
    participant Tracker as Stats Tracker
    
    S->>Drive: Call countDriveFiles(oauth2Client)
    S->>Gmail: Call getGmailCounts(oauth2Client)
    Drive-->>S: Return totalFiles
    Gmail-->>S: Return messagesExcludingPromotions
    S->>Tracker: Update stats with file & message counts
    Tracker-->>S: Confirm update
Loading

Possibly related PRs

Poem

I'm a coding bunny, hopping with delight,
Updated OAuth flows shining so bright.
With a click and a code, edits come alive,
In forms and endpoints, our integrations thrive.
From fields of state to server calls that flow,
I celebrate these changes — watch me go! 🐰💻

✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 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.
    • Generate unit testing code for this file.
    • 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 generate unit testing code for this file.
    • @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 generate unit testing code.
    • @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.

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 resolve resolve all the CodeRabbit review comments.
  • @coderabbitai plan to trigger planning for file edits and PR creation.
  • @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.

Copy link
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

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

Hello @SahilKumar000, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

Summary of Changes

This pull request introduces an edit button for OAuth providers, specifically for Google Drive. It allows users to update their OAuth integration settings (client ID, client secret, and scopes) after the initial setup. The changes involve modifying the OAuthTab component to include an edit button and updating the OAuthForm component to handle both creation and updating of OAuth provider settings. A new API endpoint /oauth/update is added to handle the update request.

Highlights

  • Edit Functionality: Adds an edit button to the OAuthTab component, allowing users to modify existing OAuth provider settings.
  • OAuth Form Update: Modifies the OAuthForm component to handle both creating and updating OAuth provider settings, based on the isEditing prop.
  • API Endpoint: Introduces a new API endpoint /oauth/update to handle the update request for OAuth provider settings.
  • UI Changes: Updates the button text in the OAuthForm to reflect whether the user is creating or updating the integration.

Changelog

Click here to see the changelog
  • frontend/src/components/OAuthTab.tsx
    • Imported useState, Dispatch, and SetStateAction from 'react'.
    • Imported the Pencil icon from 'lucide-react'.
    • Added isEditing state to control the form's edit mode.
    • Implemented handleEdit function to toggle the isEditing state and set the OAuth integration status.
    • Implemented handleFormSuccess function to update the OAuth integration status after a successful form submission.
    • Added a conditional rendering block to display either the OAuthForm in edit mode or the connect button with the edit pencil icon.
    • Passed isEditing and connectorId props to the OAuthForm component.
  • frontend/src/routes/_authenticated/admin/integrations/google.tsx
    • Added connectorId to the OAuthFormData type.
    • Modified the OAuthForm component to accept isEditing and connectorId props.
    • Implemented the updateOAuthForm function to handle the API call for updating OAuth provider settings.
    • Updated the form submission logic to call either submitOAuthForm or updateOAuthForm based on the isEditing prop.
    • Updated the button text to display 'Update Integration' when editing and 'Create Integration' when creating.
    • Added a useEffect hook to log the fetched stats.
  • server/api/admin.ts
    • Imported UpdateOAuthProviderForm from '@/types'.
    • Imported schema and drizzle functions for database interaction.
    • Implemented the UpdateOAuthProvider function to handle the update request for OAuth provider settings.
    • Added validation and error handling for the update request.
    • Updated the database with the new OAuth provider settings.
  • server/db/user.ts
    • Imported connectors from './schema'.
    • Imported Apps from '@/shared/types'.
  • server/integrations/google/index.ts
    • Added logic to update total mail and drive counts after OAuth ingestion.
  • server/server.ts
    • Imported updateOAuthProvider from '@/types'.
    • Imported UpdateOAuthProvider from '@/api/admin'.
    • Added a new PUT route /oauth/update to handle the update request for OAuth provider settings.
    • Added a GET route /oauth/.
  • server/types.ts
    • Added updateOAuthProvider schema.
    • Added UpdateOAuthProviderForm type.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point in your pull request via creating an issue comment (i.e. comment on the pull request page) using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in issue comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist is currently in preview and may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments to provide feedback.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.


A form to edit,
Secrets and IDs to knit,
Update the OAuth,
A digital growth,
New settings, submit!

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

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

Code Review

The pull request introduces the ability to edit OAuth providers, enhancing the admin interface for managing integrations. The changes include frontend components for editing OAuth configurations and backend API endpoints for updating the provider details. Overall, the code seems well-structured, but there are a few areas that could be improved for clarity and robustness.

Summary of Findings

  • Missing Error Handling: The handleEdit function in OAuthTab.tsx does not handle the case where connectorId is undefined or null, potentially leading to unexpected behavior. A more robust check or error message would improve the user experience.
  • Unnecessary useEffect: The useEffect hook in google.tsx within the UserStatsTable component seems unnecessary as it only logs the stats prop. This can be removed to reduce unnecessary re-renders and improve performance.
  • Inconsistent Naming: The naming of variables and functions could be more consistent. For example, using isEditing and then passing isEditing?: boolean can be confusing. Standardizing the naming conventions would improve readability.
  • Potential Type Assertion Issue: The type assertion connectorId as string in OAuthTab.tsx within the handleEdit function could lead to runtime errors if connectorId is actually undefined. A safer approach would involve a conditional check before the assertion.

Merge Readiness

The pull request is almost ready for merging. However, addressing the error handling in handleEdit, removing the unnecessary useEffect, ensuring consistent naming, and handling the type assertion more safely would significantly improve the code's robustness and maintainability. I am unable to approve this pull request, and recommend that others review and approve this code before merging. At a minimum, the high severity issues should be addressed before merging.

<Pencil
className="flex justify-end cursor-pointer text-muted-foreground hover:text-gray-800"
onClick={() => {
handleEdit(connectorId as string)
Copy link
Contributor

Choose a reason for hiding this comment

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

high

Consider adding a check to ensure connectorId is not null or undefined before asserting it as a string. This can prevent runtime errors if connectorId is unexpectedly missing.

                    handleEdit(connectorId ?? "")

Comment on lines 35 to 41
const handleEdit = (connectorId: string) => {
if (!connectorId) {
setOAuthIntegrationStatus(OAuthIntegrationStatus.Provider)
setIsEditing(false)
} else {
setIsEditing(true)
}
Copy link
Contributor

Choose a reason for hiding this comment

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

medium

The handleEdit function doesn't handle the case where connectorId is undefined or null after the if condition. Consider adding a default case or logging an error if connectorId is unexpectedly missing.

  const handleEdit = (connectorId: string | undefined) => {
    if (!connectorId) {
      setOAuthIntegrationStatus(OAuthIntegrationStatus.Provider)
      setIsEditing(false)
      console.warn("Connector ID is missing."); // Add this line
    } else {
      setIsEditing(true)
    }
  }

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

🧹 Nitpick comments (3)
server/integrations/google/index.ts (1)

661-669: Verify handling of potential API failures in Promise.all.

While the implementation is generally good, consider adding error handling for API call failures within the Promise.all. Currently, if any of these API calls fail, the entire function might fail, preventing other functionality from working.

Consider implementing more robust error handling:

-const [totalFiles, { messagesExcludingPromotions }] = await Promise.all([
-  countDriveFiles(oauth2Client),
-  getGmailCounts(oauth2Client),
-]);
+let totalFiles = 0;
+let messagesExcludingPromotions = 0;
+try {
+  const [fileCount, gmailResults] = await Promise.all([
+    countDriveFiles(oauth2Client).catch(err => {
+      Logger.error(err, "Failed to count Drive files");
+      return 0;
+    }),
+    getGmailCounts(oauth2Client).catch(err => {
+      Logger.error(err, "Failed to get Gmail counts");
+      return { messagesExcludingPromotions: 0 };
+    })
+  ]);
+  totalFiles = fileCount;
+  messagesExcludingPromotions = gmailResults.messagesExcludingPromotions;
+} catch (error) {
+  Logger.error(error, "Failed to get file and message counts");
+}
server/api/admin.ts (1)

140-140: Remove debugging console.log statement.

This log statement outputs sensitive user data to the console, which could expose PII. It appears to be left over from debugging.

-  console.log(userRes)
frontend/src/routes/_authenticated/admin/integrations/google.tsx (1)

454-457: Remove useEffect with console.log.

This appears to be debugging code that was left in the production code.

-          useEffect(() => {
-            console.log("Fetched stats:", stats)
-          }, [stats])
-          const totalCount: number = stats.totalDrive + stats.totalMail
+          const totalCount: number = stats.totalDrive + stats.totalMail
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 0e63f74 and b3e4caa.

📒 Files selected for processing (7)
  • frontend/src/components/OAuthTab.tsx (4 hunks)
  • frontend/src/routes/_authenticated/admin/integrations/google.tsx (6 hunks)
  • server/api/admin.ts (4 hunks)
  • server/db/user.ts (1 hunks)
  • server/integrations/google/index.ts (1 hunks)
  • server/server.ts (4 hunks)
  • server/types.ts (2 hunks)
🧰 Additional context used
🧬 Code Definitions (4)
server/server.ts (2)
server/types.ts (1)
  • updateOAuthProvider (90-96)
server/api/admin.ts (1)
  • UpdateOAuthProvider (186-221)
server/types.ts (1)
server/shared/types.ts (1)
  • Apps (25-25)
frontend/src/components/OAuthTab.tsx (1)
frontend/src/routes/_authenticated/admin/integrations/google.tsx (2)
  • OAuthForm (138-260)
  • OAuthButton (367-391)
frontend/src/routes/_authenticated/admin/integrations/google.tsx (4)
frontend/src/api.ts (1)
  • api (3-3)
server/shared/types.ts (1)
  • Apps (25-25)
frontend/src/hooks/use-toast.ts (1)
  • toast (188-188)
frontend/src/components/ui/button.tsx (1)
  • Button (57-57)
🔇 Additional comments (21)
server/db/user.ts (1)

14-15: New imports enhance OAuth provider editing functionality.

These imports support the new OAuth provider update functionality. The connectors import is used in the UpdateOAuthProvider function for database operations, while the Apps type is used for type validation in the OAuth provider schemas.

server/server.ts (3)

25-25: Added import for OAuth provider update schema.

The updateOAuthProvider schema is correctly imported from @/types to validate requests to the new update endpoint.


35-35: Added import for OAuth provider update handler.

The UpdateOAuthProvider handler is correctly imported to handle the new update endpoint.


206-210: Added new endpoint for updating OAuth providers.

This new PUT endpoint at /oauth/update uses the correct validation schema and handler for updating OAuth provider configurations.

server/integrations/google/index.ts (1)

661-669: Enhanced functionality to track Drive files and Gmail counts.

This improvement adds asynchronous operations to count total files in Google Drive and Gmail messages (excluding promotions). The use of Promise.all for parallel execution is efficient.

server/types.ts (2)

90-96: Added schema for OAuth provider updates.

The schema properly defines the required fields for updating an OAuth provider. This structure aligns well with the existing createOAuthProvider schema while adding the necessary connectorId field to identify which provider to update.


108-108: Added type definition for Update OAuth Provider form.

This type definition correctly infers the type from the Zod schema, maintaining type safety throughout the application.

server/api/admin.ts (2)

19-19: Added necessary imports for UpdateOAuthProvider function.

The imports for UpdateOAuthProviderForm type, schema, and the drizzle-orm functions eq and and support the new functionality for updating OAuth providers.

Also applies to: 38-39


186-221: Implementation of UpdateOAuthProvider function looks solid.

This function handles updating an existing OAuth provider's details. It properly:

  1. Extracts user information from JWT payload
  2. Validates user exists in the database
  3. Validates form input
  4. Verifies connector exists before updating
  5. Updates the provider data with proper database constraints

One minor improvement suggestion for line 188:

-  console.log("Full JWT Payload:", payload)

This debugging statement should be removed as it logs sensitive JWT information.

frontend/src/components/OAuthTab.tsx (6)

1-3: Updated imports to support new edit functionality.

Added necessary imports for React useState, Dispatch, SetStateAction, and the Pencil icon from lucide-react to support the new editing capability.


19-25: Props interface updated with proper typing.

Good improvements to the TypeScript interface:

  1. Changed setOAuthIntegrationStatus to use proper React state management types
  2. Made connectorId optional with the ? modifier

27-32: Component parameter destructuring updated.

The component now properly accepts the optional connectorId parameter.


56-59: Updated form properties to support edit mode.

The OAuthForm now receives:

  1. The handleFormSuccess callback for successful submissions
  2. The edit mode state
  3. The connectorId for the provider being edited

67-88: Added conditional rendering for edit mode.

This implementation nicely handles:

  1. Showing the edit form when in edit mode
  2. Showing the OAuth button with an edit icon when not in edit mode
  3. Providing the pencil icon to trigger edit mode

The UI now supports both viewing and editing the OAuth configuration.


97-102: Improved connection status display.

The connection status message is now displayed more clearly, using a paragraph element for the "Connected" status.

frontend/src/routes/_authenticated/admin/integrations/google.tsx (6)

99-124: Well-implemented updateOAuthForm function.

The function appropriately:

  1. Makes a PUT request to the update endpoint
  2. Handles form data including the connectorId
  3. Handles authentication and error cases
  4. Provides detailed error information

135-135: Updated OAuthFormData type to support editing.

Added optional connectorId field to the type definition, which is necessary for the update functionality.


138-142: Enhanced OAuthForm component with new props.

The component now accepts additional props:

  • isEditing: to determine the current mode
  • connectorId: to identify which provider to update

These props are properly documented with TypeScript types.


151-166: Updated form submission logic for edit mode.

The onSubmit handler now:

  1. Checks if in editing mode
  2. Calls the appropriate function (update or create)
  3. Shows a contextual toast message based on the action
  4. Calls the success callback on completion

255-257: Dynamic button text based on edit mode.

The submit button now displays "Update Integration" or "Create Integration" depending on whether the form is in editing mode, providing clear context to the user.


749-754: Pass connectorId to OAuthTab component.

Properly fetches the connector ID from the data array based on app type and auth type, enabling the edit functionality.

server/server.ts Outdated
@@ -210,6 +217,7 @@ app.get(
StartOAuth,
)

app.get("/oauth/")
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Added GET endpoint without handler implementation.

This GET endpoint at /oauth/ is missing a handler implementation, which could lead to runtime errors when accessed.

Either implement a handler for this endpoint or remove it if not needed. Example:

-app.get("/oauth/")
+app.get("/oauth/", async (c) => {
+  // Return a list of OAuth providers for the authenticated user
+  return c.json({ providers: await getOAuthProviders(c) })
+})

Alternatively, if this was added by mistake:

-app.get("/oauth/")
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
app.get("/oauth/")
app.get("/oauth/", async (c) => {
// Return a list of OAuth providers for the authenticated user
return c.json({ providers: await getOAuthProviders(c) })
})

Comment on lines 33 to 48
const [isEditing, setIsEditing] = useState(false)

const handleEdit = (connectorId: string) => {
if (!connectorId) {
setOAuthIntegrationStatus(OAuthIntegrationStatus.Provider)
setIsEditing(false)
} else {
setIsEditing(true)
}
}

const handleFormSuccess = () => {
// After updating, trigger the OAuth connection process
setOAuthIntegrationStatus(OAuthIntegrationStatus.OAuth)
setIsEditing(false)
}
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Added state management and handlers for edit mode.

The implementation adds:

  1. State tracking for edit mode with isEditing
  2. A handler to toggle edit mode based on connector presence
  3. A success handler to reset state after form submission

The logic in handleEdit on line 36 has a potential issue:

-  const handleEdit = (connectorId: string) => {
-    if (!connectorId) {
+  const handleEdit = (connectorId?: string) => {
+    if (!connectorId) {

The function should accept optional connectorId to match how it's used in the onClick handler at line 83 where connectorId could potentially be undefined.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const [isEditing, setIsEditing] = useState(false)
const handleEdit = (connectorId: string) => {
if (!connectorId) {
setOAuthIntegrationStatus(OAuthIntegrationStatus.Provider)
setIsEditing(false)
} else {
setIsEditing(true)
}
}
const handleFormSuccess = () => {
// After updating, trigger the OAuth connection process
setOAuthIntegrationStatus(OAuthIntegrationStatus.OAuth)
setIsEditing(false)
}
const [isEditing, setIsEditing] = useState(false)
const handleEdit = (connectorId?: string) => {
if (!connectorId) {
setOAuthIntegrationStatus(OAuthIntegrationStatus.Provider)
setIsEditing(false)
} else {
setIsEditing(true)
}
}
const handleFormSuccess = () => {
// After updating, trigger the OAuth connection process
setOAuthIntegrationStatus(OAuthIntegrationStatus.OAuth)
setIsEditing(false)
}

server/server.ts Outdated
@@ -210,6 +217,7 @@ app.get(
StartOAuth,
)

app.get("/oauth/")
Copy link
Contributor

Choose a reason for hiding this comment

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

this needs to be removed

@@ -134,6 +137,7 @@ export const CreateOAuthProvider = async (c: Context) => {
if (!userRes || !userRes.length) {
throw new NoUserFound({})
}
console.log(userRes)
Copy link
Contributor

Choose a reason for hiding this comment

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

remove this

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

🧹 Nitpick comments (3)
server/api/admin.ts (1)

185-220: Remove or Mask Sensitive Logging
Logging the entire JWT payload (console.log("Full JWT Payload:", payload)) might inadvertently expose sensitive user data in logs. Consider removing it or masking sensitive properties, especially in production.

Additionally, there's a // @ts-ignore before reading c.req.valid("form"). It’s best to avoid @ts-ignore if possible by properly typing the request or narrowing the form type safely. Otherwise, the update logic appears correct and well-restricted by the where clause.

   console.log("Full JWT Payload:", payload)
-  console.log("Full JWT Payload:", payload)
frontend/src/routes/_authenticated/admin/integrations/google.tsx (2)

99-124: Reduce Duplication Between submitOAuthForm and updateOAuthForm
This new updateOAuthForm function very closely mirrors submitOAuthForm; if both processes share significant logic, consider extracting the common logic into a helper function to adhere to DRY principles. Otherwise, this is a fine approach for clarity.


138-148: Strengthen Types for Form Props
The props onSuccess, refetch, and isEditing are typed loosely as any or optional. Consider explicitly typing them (e.g., (data?: unknown) => void or similar). This improves clarity and maintainability.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between b3e4caa and 7359441.

📒 Files selected for processing (5)
  • frontend/src/components/OAuthTab.tsx (4 hunks)
  • frontend/src/routes/_authenticated/admin/integrations/google.tsx (6 hunks)
  • frontend/src/routes/_authenticated/integrations/google.tsx (1 hunks)
  • server/api/admin.ts (3 hunks)
  • server/server.ts (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • server/server.ts
  • frontend/src/components/OAuthTab.tsx
🧰 Additional context used
🧬 Code Graph Analysis (1)
frontend/src/routes/_authenticated/integrations/google.tsx (1)
server/shared/types.ts (1)
  • Apps (25-25)
🔇 Additional comments (5)
frontend/src/routes/_authenticated/integrations/google.tsx (1)

122-134: Confirm Handling of Multiple Connectors
If a user has more than one Google Drive OAuth connector, the expression data?.find(...)?.id will select only the first match. This may be acceptable if only one connector is expected, but if multiple connectors can exist, consider handling that scenario more explicitly (e.g., filtering by an additional unique identifier). Otherwise, this approach looks good.

server/api/admin.ts (1)

19-19: Type Import Looks Good
You’ve introduced type UpdateOAuthProviderForm here. It appears to be used properly below without conflicts. No immediate issues.

frontend/src/routes/_authenticated/admin/integrations/google.tsx (3)

159-174: Editing Logic Looks Good
Switching between “add” and “update” paths based on isEditing is cleanly implemented. The toast messages also help guide the user. Nice work!


262-264: Clearer Button Label
Dynamically rendering “Update Integration” or “Create Integration” aligns with the isEditing state, improving user feedback. This is a neat improvement.


755-761: Prop Assignments Appear Correct
Passing connectorId and refetch={refetch} ensures the component can re-fetch data and distinguish which connector is being edited. This is straightforward and aligns with the existing logic.

Comment on lines +460 to +464
// console.log(stats.,stats.totalMail);
useEffect(() => {
console.log("Fetched stats:", stats)
}, [stats])
const totalCount: number = stats.totalDrive + stats.totalMail
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Avoid Hooks Inside a Loop
Calling useEffect within a .map can break React’s “Rules of Hooks,” causing unexpected behavior when the number or order of items changes. Consider moving this logging into a parent-level effect or outside the loop.

Example fix:

- {Object.entries(userStats).map(([email, stats]) => {
-   useEffect(() => {
-     console.log("Fetched stats:", stats)
-   }, [stats])
-   ...
- })}
+ useEffect(() => {
+   Object.entries(userStats).forEach(([email, stats]) => {
+     console.log("Fetched stats:", stats)
+   })
+ }, [userStats])

+ {Object.entries(userStats).map(([email, stats]) => {
+   ...
+ })}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
// console.log(stats.,stats.totalMail);
useEffect(() => {
console.log("Fetched stats:", stats)
}, [stats])
const totalCount: number = stats.totalDrive + stats.totalMail
// Place the logging effect outside of the map
useEffect(() => {
Object.entries(userStats).forEach(([email, stats]) => {
console.log("Fetched stats:", stats)
})
}, [userStats])
{Object.entries(userStats).map(([email, stats]) => {
// Removed the inline useEffect hook:
// useEffect(() => {
// console.log("Fetched stats:", stats)
// }, [stats])
// Existing logic remains
const totalCount: number = stats.totalDrive + stats.totalMail
// ... Other component rendering logic for each user
return (
<YourComponent key={email} totalCount={totalCount} /* other props */ />
)
})}

@zereraz zereraz requested review from kalpadhwaryu and junaid-shirur and removed request for junaid-shirur April 21, 2025 11:21
updateStatus: string
connectorId?: string
refetch: any
Copy link
Contributor

Choose a reason for hiding this comment

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

Remove any. Can we type this?

: "Connecting"}
{oauthIntegrationStatus ===
OAuthIntegrationStatus.OAuthConnected ? (
<p className="mb-4">Connected</p>
Copy link
Contributor

Choose a reason for hiding this comment

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

Why have we added bottom margin here?

}
const errorText = await response.text()
throw new Error(
`Failed to upload file: ${response.status} ${response.statusText} - ${errorText}`,
Copy link
Contributor

Choose a reason for hiding this comment

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

Error should be Failed to update provider.

@@ -409,10 +457,15 @@ const UserStatsTable = ({
</TableHeader>
<TableBody>
{Object.entries(userStats).map(([email, stats]) => {
// console.log(stats.,stats.totalMail);
useEffect(() => {
Copy link
Contributor

Choose a reason for hiding this comment

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

Remove the log comment as well as the useEffect with the log.

@@ -179,6 +182,43 @@ export const CreateOAuthProvider = async (c: Context) => {
})
}

export const UpdateOAuthProvider = async (c: Context) => {
const payload = c.get(JwtPayloadKey)
console.log("Full JWT Payload:", payload)
Copy link
Contributor

Choose a reason for hiding this comment

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

remove this log

@@ -11,6 +11,8 @@ import {
type PublicUserWorkspace,
type SelectUser,
} from "./schema"
import { connectors } from "./schema"
import { type Apps } from "@/shared/types"
Copy link
Contributor

Choose a reason for hiding this comment

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

Remove both of these unused imports.

if (!connector) {
throw new HTTPException(404, { message: "Connector not found" })
}
await db
Copy link
Contributor

Choose a reason for hiding this comment

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

Create a function called updateOAuthProvider in oauthProvider.ts with this code, import and then use it here.

)
return c.json({
success: true,
message: "Connection and Provider updated",
Copy link
Contributor

Choose a reason for hiding this comment

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

Only provider updated.

onSuccess()
refetch()
Copy link
Contributor

Choose a reason for hiding this comment

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

refetch is already called via onSuccess in handleFormSuccess, check if it can be removed here.

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.

3 participants