|
1 | | -import { useAuth } from "@clerk/clerk-react"; |
2 | | -import { useEffect } from "react"; |
| 1 | +import { useAuth, useUser } from "@clerk/clerk-react"; |
| 2 | +import { useEffect, useContext } from "react"; |
3 | 3 | import { Cookies } from "react-cookie"; |
4 | 4 | import useAuthStore from "@/stores/authStore"; |
5 | 5 | import { LANGFLOW_ACCESS_TOKEN } from "@/constants/constants"; |
| 6 | +import { AuthContext } from "@/contexts/authContext"; |
| 7 | +import { ensureLangflowUser, backendLogin } from "./langflow-sync"; |
6 | 8 |
|
7 | 9 | export default function ClerkAuthAdapter() { |
8 | 10 | const { getToken, isSignedIn, sessionId } = useAuth(); |
| 11 | + const { user } = useUser(); |
| 12 | + const { login } = useContext(AuthContext); |
9 | 13 |
|
10 | 14 | useEffect(() => { |
11 | 15 | const cookies = new Cookies(); |
12 | 16 | async function syncToken() { |
13 | 17 | if (isSignedIn) { |
14 | 18 | const token = await getToken(); |
15 | 19 | if (token) { |
16 | | - cookies.set(LANGFLOW_ACCESS_TOKEN, token, { path: "/" }); |
17 | | - useAuthStore.getState().setAccessToken(token); |
18 | | - useAuthStore.getState().setIsAuthenticated(true); |
| 20 | + const username = |
| 21 | + user?.username || |
| 22 | + user?.primaryEmailAddress?.emailAddress || |
| 23 | + user?.id || |
| 24 | + "clerk_user"; |
| 25 | + try { |
| 26 | + await ensureLangflowUser(token, username); |
| 27 | + const data = await backendLogin(username); |
| 28 | + // use the Clerk token for frontend state but still |
| 29 | + // rely on /login to set refresh and API key cookies |
| 30 | + login(token, "login", data.refresh_token); |
| 31 | + } catch { |
| 32 | + // ignore errors and continue login |
| 33 | + } |
19 | 34 | } |
20 | 35 | } else { |
21 | 36 | cookies.remove(LANGFLOW_ACCESS_TOKEN, { path: "/" }); |
22 | 37 | useAuthStore.getState().logout(); |
23 | 38 | } |
24 | 39 | } |
25 | 40 | syncToken(); |
26 | | - }, [isSignedIn, getToken, sessionId]); |
| 41 | + }, [isSignedIn, getToken, sessionId, user, login]); |
27 | 42 |
|
28 | 43 | return null; |
29 | 44 | } |
0 commit comments