convex
Version:
Client for the Convex Cloud
87 lines (86 loc) • 2.37 kB
JavaScript
;
import { Auth0Provider, useAuth0 } from "@auth0/auth0-react";
import React, { useEffect, useState } from "react";
import { ConvexProvider } from "../react/index.js";
export const ConvexProviderWithAuth0 = ({ children, client, authInfo, loading, loggedOut }) => {
if (!authInfo) {
throw new Error(
"ConvexProviderWithAuth0 component requires authInfo. Run `npx convex auth add` to register your auth provider and pass config.authInfo[0] as the authInfo prop."
);
}
let domain = authInfo.domain;
if (domain.startsWith("https://")) {
domain = domain.slice(8);
}
if (domain.endsWith("/")) {
domain = domain.slice(0, -1);
}
return React.createElement(
Auth0Provider,
{
domain,
clientId: authInfo.applicationID,
redirectUri: typeof window === "undefined" ? void 0 : window.location.origin,
cacheLocation: "localstorage"
},
React.createElement(
ConvexProviderUsingAuth0,
{
client,
loading,
loggedOut
},
children
)
);
};
function ConvexProviderUsingAuth0({
children,
client,
loading,
loggedOut
}) {
const {
isAuthenticated,
isLoading,
getAccessTokenSilently,
loginWithRedirect
} = useAuth0();
const [clientAuthSynced, setClientAuthSynced] = useState(false);
loggedOut = loggedOut || React.createElement("button", { onClick: loginWithRedirect }, "Log in");
loading = loading || React.createElement(React.Fragment, null, null);
useEffect(() => {
async function setToken() {
await client.setAuth(async () => {
try {
const response = await getAccessTokenSilently({
detailedResponse: true
});
return response.id_token;
} catch (_error) {
return null;
}
});
setClientAuthSynced(true);
}
if (isAuthenticated) {
void setToken();
return () => client.clearAuth();
}
}, [isAuthenticated, getAccessTokenSilently, isLoading, client]);
if (isLoading || isAuthenticated && !clientAuthSynced) {
return loading;
} else if (!isAuthenticated) {
return React.createElement(
ConvexProvider,
{ client },
loggedOut
);
}
return React.createElement(
ConvexProvider,
{ client },
children
);
}
//# sourceMappingURL=ConvexProviderWithAuth0.js.map