-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathConvexProviderWithAuth0.tsx
60 lines (56 loc) · 1.72 KB
/
ConvexProviderWithAuth0.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
import { useAuth0 } from "@auth0/auth0-react";
import React from "react";
import { ReactNode, useCallback, useMemo } from "react";
import { AuthTokenFetcher } from "../browser/sync/client.js";
import { ConvexProviderWithAuth } from "../react/ConvexAuthState.js";
// Until we can import from our own entry points (requires TypeScript 4.7),
// just describe the interface enough to help users pass the right type.
type IConvexReactClient = {
setAuth(fetchToken: AuthTokenFetcher): void;
clearAuth(): void;
};
/**
* A wrapper React component which provides a {@link react.ConvexReactClient}
* authenticated with Auth0.
*
* It must be wrapped by a configured `Auth0Provider` from `@auth0/auth0-react`.
*
* See [Convex Auth0](https://docs.convex.dev/auth/auth0) on how to set up
* Convex with Auth0.
*
* @public
*/
export function ConvexProviderWithAuth0({
children,
client,
}: {
children: ReactNode;
client: IConvexReactClient;
}) {
return (
<ConvexProviderWithAuth client={client} useAuth={useAuthFromAuth0}>
{children}
</ConvexProviderWithAuth>
);
}
function useAuthFromAuth0() {
const { isLoading, isAuthenticated, getAccessTokenSilently } = useAuth0();
const fetchAccessToken = useCallback(
async ({ forceRefreshToken }: { forceRefreshToken: boolean }) => {
try {
const response = await getAccessTokenSilently({
detailedResponse: true,
cacheMode: forceRefreshToken ? "off" : "on",
});
return response.id_token as string;
} catch (error) {
return null;
}
},
[getAccessTokenSilently],
);
return useMemo(
() => ({ isLoading, isAuthenticated, fetchAccessToken }),
[isLoading, isAuthenticated, fetchAccessToken],
);
}