Skip to content

Feat add clerk auth#8724

Closed
Bharani0012 wants to merge 10 commits into
langflow-ai:mainfrom
SaravanakumarR2018:feat_add_clerk_auth
Closed

Feat add clerk auth#8724
Bharani0012 wants to merge 10 commits into
langflow-ai:mainfrom
SaravanakumarR2018:feat_add_clerk_auth

Conversation

@Bharani0012
Copy link
Copy Markdown

@Bharani0012 Bharani0012 commented Jun 25, 2025

✨ Clerk Authentication Integration (Feature Request)

This PR adds optional support for Clerk authentication to Langflow, controlled via a toggle using the new environment variable LANGFLOW_CLERK_AUTH_ENABLED and VITE_CLERK_AUTH_ENABLED. When set to true, Clerk handles all frontend and backend authentication flows (including GitHub, Google, etc.). When false, the existing legacy login remains fully functional.


✅ Key Features

  • 🔀 Clerk toggle-based integration:
    • Set LANGFLOW_CLERK_AUTH_ENABLED=true and VITE_CLERK_AUTH_ENABLED=true to activate Clerk login
    • Uses Authorization: Bearer <token> to authenticate
  • 🔐 Backend token verification:
    • Validates Clerk JWT via public JWKs
    • Auto-creates users on first login using Clerk claims
  • 🧠 Frontend Clerk handling:
    • Automatically uses Clerk UI (<SignIn />, <SignUp />) when enabled
    • Preserves all routing and auto-login behavior when disabled

🛠️ Modified Files

🔁 Backend

modified: src/backend/base/langflow/api/router.py
modified: src/backend/base/langflow/api/utils.py
modified: src/backend/base/langflow/api/v1/chat.py
modified: src/backend/base/langflow/api/v1/login.py
modified: src/backend/base/langflow/api/v1/users.py
modified: src/backend/base/langflow/services/auth/utils.py

🖼️ Frontend

modified: src/frontend/package-lock.json
modified: src/frontend/src/components/ClerkSessionSync.ts
modified: src/frontend/src/contexts/authContext.tsx
modified: src/frontend/src/controllers/API/queries/auth/use-get-user.ts
modified: src/frontend/src/controllers/API/queries/auth/use-post-logout.ts
modified: src/frontend/src/pages/AppInitPage/index.tsx
modified: src/frontend/src/pages/LoginPage/index.tsx

Additional Changes:

  • Added authGuard.tsx, authAdminGuard.tsx, useClerkAccessToken.ts, api.tsx modifications
  • Replaced legacy login with Clerk <SignIn /> UI in Clerk mode
  • Removed redundant /me fetch in AppInitPage

⚙️ Environment Setup

📁 .env.example

# To enable Clerk login
LANGFLOW_CLERK_AUTH_ENABLED=true
CLERK_SECRET_KEY=sk_...

# Frontend-only
VITE_CLERK_AUTH_ENABLED=true
VITE_CLERK_PUBLISHABLE_KEY=pk_...

To use legacy auth:

LANGFLOW_CLERK_AUTH_ENABLED=false
VITE_CLERK_AUTH_ENABLED=false
LANGFLOW_AUTO_LOGIN=false

⚠️ Known Issues / Bug to Fix

  • Bug: When CLERK_AUTH_ENABLED=true, an unwanted call to /api/v1/users/undefined occurs.
    • 🔍 Root cause: frontend state not fully synced before initial API calls (likely authContext or a stale whoami call).
    • 🧩 Temporary fix: guard whoami call behind Clerk session isSignedIn.

🧪 How to Run

🧰 Backend

make init
make backend
# Visit http://0.0.0.0:7860/

🌐 Frontend

make frontend
# Opens http://localhost:3000/

Summary by CodeRabbit

  • New Features

    • Added support for Clerk authentication, enabling seamless sign-in and sign-up using Clerk across the app.
    • Users can now log in, sign up, and manage sessions via Clerk when enabled, with legacy authentication as a fallback.
  • Improvements

    • Authentication flows are now dynamically selected based on environment configuration, supporting both Clerk and legacy modes.
    • Enhanced user session management and logout handling for both Clerk and legacy authentication.
    • Cleaner and more concise environment configuration example with explicit default values.
  • Bug Fixes

    • Corrected query refetch syntax to ensure proper cache updates after flow changes.
    • Improved guard clauses to prevent rendering components with missing required identifiers.
  • Documentation

    • Added detailed documentation for Clerk authentication integration and updated general documentation for clarity.
  • Chores

    • Added a CODEOWNERS file for repository management.
    • Updated dependencies to include Clerk React SDK.

@dosubot dosubot Bot added the size:XXL This PR changes 1000+ lines, ignoring generated files. label Jun 25, 2025
@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Jun 25, 2025

Caution

Review failed

The pull request is closed.

Walkthrough

This update introduces Clerk authentication support to both the backend and frontend, enabling JWT-based SSO via Clerk. It adds new configuration options, utility modules, and conditional control flows to support Clerk or legacy authentication. The frontend integrates Clerk components and adapts routing, login, and logout logic accordingly. Documentation and environment examples are updated.

Changes

File(s) Change Summary
.env.example Simplified and updated with explicit default values, added Clerk-related variables, removed all comments.
.github/CODEOWNERS Added new CODEOWNERS file assigning repository ownership to @SaravanakumarR2018.
CLERK_AUTH.MD Added documentation describing Clerk and legacy authentication flows, comparison table, and relevant environment variables.
README.md Revised to remove badges/logo, update product description, simplify quickstart, and clarify deployment options.
src/backend/base/langflow/api/utils.py Replaced get_current_active_user_mcp with get_current_user_flexible and updated dependency annotation.
src/backend/base/langflow/api/v1/chat.py, src/backend/base/langflow/api/v1/users.py Switched dependency injection from CurrentActiveUser to CurrentActiveUserFlexible for endpoints requiring user authentication.
src/backend/base/langflow/api/v1/login.py Added conditional route definitions: disables legacy login/refresh endpoints when Clerk auth is enabled, returns 403 errors; preserves logout with simplified response.
src/backend/base/langflow/services/auth/clerk_utils.py New module for Clerk JWT verification, JWKS fetching, and user claim extraction.
src/backend/base/langflow/services/auth/utils.py Updated get_current_user_by_jwt to support Clerk auth, added get_current_user_flexible for unified user retrieval, reorganized error handling and imports.
src/backend/base/langflow/services/database/models/user/model.py Made password field nullable and default to empty string.
src/backend/base/langflow/services/settings/auth.py Added CLERK_AUTH_ENABLED and CLERK_SECRET_KEY fields; changed AUTO_LOGIN default from True to False.
src/frontend/package.json Added @clerk/clerk-react dependency.
src/frontend/src/components/ClerkSessionSync.ts New component to sync Clerk session state with local auth store.
src/frontend/src/components/authorization/authGuard/index.tsx, src/frontend/src/components/authorization/authLoginGuard/index.tsx Enhanced to short-circuit to Clerk authentication when enabled, fallback to legacy otherwise.
src/frontend/src/contexts/authContext.tsx Integrated Clerk hooks, added async getUser, unified login/logout logic, added logout to context, renders ClerkSessionSync when enabled.
src/frontend/src/controllers/API/api.tsx Integrated Clerk token retrieval, updated request and error handling logic for Clerk/legacy auth, improved retry and header logic.
src/frontend/src/controllers/API/clerk-access-token.ts New module exporting useClerkAccessToken hook for safe Clerk token retrieval.
src/frontend/src/controllers/API/helpers/constants.ts Defined Clerk config constants, updated API base URL definitions, disables legacy login/refresh endpoints under Clerk, improved URL construction logic.
src/frontend/src/controllers/API/queries/auth/use-get-user.ts Added debug logging for user data fetch.
src/frontend/src/controllers/API/queries/auth/use-post-logout.ts Added Clerk-aware logout logic: uses Clerk signOut if enabled, legacy otherwise.
src/frontend/src/controllers/API/queries/flows/use-patch-update-flow.ts Fixed parentheses in mutation onSettled callback for query refetching.
src/frontend/src/index.tsx Wrapped app in ClerkProvider with publishable key and redirect URLs.
src/frontend/src/pages/AppInitPage/index.tsx Refactored to support Clerk and legacy auth flows, split data loading and routing logic accordingly.
src/frontend/src/pages/LoginPage/index.tsx, src/frontend/src/pages/SignUpPage/index.tsx Added conditional rendering of Clerk <SignIn> and <SignUp> components when Clerk auth is enabled.
src/frontend/src/pages/MainPage/pages/homePage/components/McpServerTab.tsx Added guard clause to prevent rendering if projectId is falsy.
src/frontend/src/types/api/index.ts Added optional email to Users type, added new MeResponse type.
src/frontend/src/types/contexts/auth.ts Added logout: () => void method to AuthContextType.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant Frontend
    participant Clerk
    participant Backend
    participant Database

    User->>Frontend: Visits app
    Frontend->>Clerk: Check if Clerk auth enabled
    alt Clerk auth enabled
        Frontend->>Clerk: Is user signed in?
        alt Signed in
            Frontend->>Clerk: Get JWT token
            Frontend->>Backend: Send request with Clerk JWT
            Backend->>Clerk: Fetch JWKS
            Backend->>Backend: Verify JWT, extract user info
            Backend->>Database: Find or create user by Clerk ID
            Database-->>Backend: User record
            Backend-->>Frontend: API response
        else Not signed in
            Frontend->>Clerk: Show SignIn/SignUp UI
        end
    else Legacy auth
        Frontend->>Backend: Show login form or auto-login
        User->>Frontend: Enter credentials
        Frontend->>Backend: Send credentials
        Backend->>Database: Validate user/password
        Database-->>Backend: User record
        Backend-->>Frontend: JWT token, set cookies
        Frontend->>Backend: Use JWT for API requests
        Backend->>Backend: Validate JWT, fetch user
        Backend-->>Frontend: API response
    end
Loading

Possibly related PRs

  • langflow-ai/langflow#8600: Both PRs modify the README to add or remove the CVE alert note, indicating a direct connection in documentation changes.
  • langflow-ai/langflow#8388: Both PRs involve backend API updates related to MCP server management and share modifications to MCP-related components and routes.
  • langflow-ai/langflow#8271: Both PRs update backend API endpoints for MCP server management and database session handling, showing strong code-level overlap.

Suggested labels

size:XL, lgtm


📜 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 8ae85ab and 20985e6.

⛔ Files ignored due to path filters (1)
  • src/frontend/package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (30)
  • .env.example (1 hunks)
  • .github/CODEOWNERS (1 hunks)
  • CLERK_AUTH.MD (1 hunks)
  • README.md (1 hunks)
  • src/backend/base/langflow/api/utils.py (2 hunks)
  • src/backend/base/langflow/api/v1/chat.py (3 hunks)
  • src/backend/base/langflow/api/v1/login.py (1 hunks)
  • src/backend/base/langflow/api/v1/users.py (4 hunks)
  • src/backend/base/langflow/services/auth/clerk_utils.py (1 hunks)
  • src/backend/base/langflow/services/auth/utils.py (3 hunks)
  • src/backend/base/langflow/services/database/models/user/model.py (1 hunks)
  • src/backend/base/langflow/services/settings/auth.py (1 hunks)
  • src/frontend/package.json (1 hunks)
  • src/frontend/src/components/ClerkSessionSync.ts (1 hunks)
  • src/frontend/src/components/authorization/authGuard/index.tsx (3 hunks)
  • src/frontend/src/components/authorization/authLoginGuard/index.tsx (1 hunks)
  • src/frontend/src/contexts/authContext.tsx (3 hunks)
  • src/frontend/src/controllers/API/api.tsx (8 hunks)
  • src/frontend/src/controllers/API/clerk-access-token.ts (1 hunks)
  • src/frontend/src/controllers/API/helpers/constants.ts (3 hunks)
  • src/frontend/src/controllers/API/queries/auth/use-get-user.ts (1 hunks)
  • src/frontend/src/controllers/API/queries/auth/use-post-logout.ts (2 hunks)
  • src/frontend/src/controllers/API/queries/flows/use-patch-update-flow.ts (1 hunks)
  • src/frontend/src/index.tsx (2 hunks)
  • src/frontend/src/pages/AppInitPage/index.tsx (1 hunks)
  • src/frontend/src/pages/LoginPage/index.tsx (3 hunks)
  • src/frontend/src/pages/MainPage/pages/homePage/components/McpServerTab.tsx (1 hunks)
  • src/frontend/src/pages/SignUpPage/index.tsx (2 hunks)
  • src/frontend/src/types/api/index.ts (2 hunks)
  • src/frontend/src/types/contexts/auth.ts (1 hunks)
✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate Unit Tests
  • Create PR with Unit Tests
  • Post Copyable Unit Tests in Comment

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
🪧 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 auto-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.

@dosubot dosubot Bot added the enhancement New feature or request label Jun 25, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request size:XXL This PR changes 1000+ lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants