|
| 1 | +import React, { ReactNode, useEffect, useContext, useState } from "react"; |
| 2 | +import App from "../customization/custom-App"; |
| 3 | +import { ClerkProvider, useAuth, useUser, useClerk } from "@clerk/clerk-react"; |
| 4 | +import { Cookies } from "react-cookie"; |
| 5 | +import useAuthStore from "@/stores/authStore"; |
| 6 | +import { LANGFLOW_ACCESS_TOKEN } from "@/constants/constants"; |
| 7 | +import { AuthContext } from "@/contexts/authContext"; |
| 8 | +import { api } from "@/controllers/API/api"; |
| 9 | +import { getURL } from "@/controllers/API/helpers/constants"; |
| 10 | +import { useLogout as useLogoutMutation } from "@/controllers/API/queries/auth"; |
| 11 | + |
| 12 | +// Clerk constants |
| 13 | +export const IS_CLERK_AUTH = |
| 14 | + String(process.env.CLERK_AUTH_ENABLED).toLowerCase() === "true"; |
| 15 | +export const CLERK_PUBLISHABLE_KEY = process.env.CLERK_PUBLISHABLE_KEY || ""; |
| 16 | +export const CLERK_DUMMY_PASSWORD = "clerk_dummy_password"; |
| 17 | + |
| 18 | +// Backend synchronization helpers |
| 19 | +export async function ensureLangflowUser(token: string, username: string) { |
| 20 | + try { |
| 21 | + await api.get(`${getURL("USERS")}/whoami`, { |
| 22 | + headers: { Authorization: `Bearer ${token}` }, |
| 23 | + }); |
| 24 | + } catch (err: any) { |
| 25 | + if (err?.response?.status === 404) { |
| 26 | + await api.post( |
| 27 | + `${getURL("USERS")}/`, |
| 28 | + { username, password: CLERK_DUMMY_PASSWORD }, |
| 29 | + { headers: { Authorization: `Bearer ${token}` } }, |
| 30 | + ); |
| 31 | + } else { |
| 32 | + throw err; |
| 33 | + } |
| 34 | + } |
| 35 | +} |
| 36 | + |
| 37 | +export async function backendLogin(username: string) { |
| 38 | + const res = await api.post( |
| 39 | + `${getURL("LOGIN")}`, |
| 40 | + new URLSearchParams({ |
| 41 | + username, |
| 42 | + password: CLERK_DUMMY_PASSWORD, |
| 43 | + }).toString(), |
| 44 | + { |
| 45 | + headers: { |
| 46 | + "Content-Type": "application/x-www-form-urlencoded", |
| 47 | + }, |
| 48 | + }, |
| 49 | + ); |
| 50 | + return res.data; |
| 51 | +} |
| 52 | + |
| 53 | +// Component that syncs Clerk session with backend |
| 54 | +export function ClerkAuthAdapter() { |
| 55 | + const { getToken, isSignedIn, sessionId } = useAuth(); |
| 56 | + const { user } = useUser(); |
| 57 | + const { login } = useContext(AuthContext); |
| 58 | + |
| 59 | + useEffect(() => { |
| 60 | + const cookies = new Cookies(); |
| 61 | + async function syncToken() { |
| 62 | + if (isSignedIn) { |
| 63 | + const token = await getToken(); |
| 64 | + if (token) { |
| 65 | + const username = |
| 66 | + user?.username || |
| 67 | + user?.primaryEmailAddress?.emailAddress || |
| 68 | + user?.id || |
| 69 | + "clerk_user"; |
| 70 | + try { |
| 71 | + await ensureLangflowUser(token, username); |
| 72 | + const data = await backendLogin(username); |
| 73 | + login(token, "login", data.refresh_token); |
| 74 | + } catch { |
| 75 | + // ignore errors and continue login |
| 76 | + } |
| 77 | + } |
| 78 | + } else { |
| 79 | + cookies.remove(LANGFLOW_ACCESS_TOKEN, { path: "/" }); |
| 80 | + useAuthStore.getState().logout(); |
| 81 | + } |
| 82 | + } |
| 83 | + syncToken(); |
| 84 | + }, [isSignedIn, getToken, sessionId, user, login]); |
| 85 | + |
| 86 | + return null; |
| 87 | +} |
| 88 | + |
| 89 | +// Provider that wraps the app with Clerk when enabled |
| 90 | +export function ClerkAuthProvider({ children }: { children: ReactNode }) { |
| 91 | + return ( |
| 92 | + <ClerkProvider publishableKey={CLERK_PUBLISHABLE_KEY}> |
| 93 | + <ClerkAuthAdapter /> |
| 94 | + {children} |
| 95 | + </ClerkProvider> |
| 96 | + ); |
| 97 | +} |
| 98 | + |
| 99 | +// Logout hook that also signs out from Clerk |
| 100 | +export function useLogout(options?: Parameters<typeof useLogoutMutation>[0]) { |
| 101 | + const { mutate, mutateAsync, ...rest } = useLogoutMutation(options); |
| 102 | + const { signOut } = IS_CLERK_AUTH ? useClerk() : { signOut: async () => {} }; |
| 103 | + |
| 104 | + const clerkSignOut = async () => { |
| 105 | + if (IS_CLERK_AUTH) { |
| 106 | + try { |
| 107 | + await signOut(); |
| 108 | + } catch (err) { |
| 109 | + console.error("Clerk signOut failed:", err); |
| 110 | + } |
| 111 | + } |
| 112 | + }; |
| 113 | + |
| 114 | + const wrappedMutate: typeof mutate = (...args) => { |
| 115 | + clerkSignOut().finally(() => mutate(...args)); |
| 116 | + }; |
| 117 | + |
| 118 | + const wrappedMutateAsync: typeof mutateAsync = async (...args) => { |
| 119 | + await clerkSignOut(); |
| 120 | + return mutateAsync(...args); |
| 121 | + }; |
| 122 | + |
| 123 | + return { mutate: wrappedMutate, mutateAsync: wrappedMutateAsync, clerkSignOut, ...rest }; |
| 124 | +} |
| 125 | + |
| 126 | +// App wrapper that conditionally enables Clerk |
| 127 | +export function AppWithProvider() { |
| 128 | + return IS_CLERK_AUTH ? ( |
| 129 | + <ClerkAuthProvider> |
| 130 | + <App /> |
| 131 | + </ClerkAuthProvider> |
| 132 | + ) : ( |
| 133 | + <App /> |
| 134 | + ); |
| 135 | +} |
| 136 | + |
| 137 | +// Mock mutation used when Clerk auth is enabled |
| 138 | +export const mockClerkMutation = { |
| 139 | + mutate: () => {}, |
| 140 | + mutateAsync: async () => undefined, |
| 141 | + isError: false, |
| 142 | + isIdle: true, |
| 143 | + isPending: false, |
| 144 | + isSuccess: true, |
| 145 | + reset: () => {}, |
| 146 | + status: "success", |
| 147 | + variables: undefined, |
| 148 | + data: undefined, |
| 149 | + error: null, |
| 150 | +} as any; |
| 151 | + |
| 152 | +export default AppWithProvider; |
0 commit comments