convex
Version:
Client for the Convex Cloud
71 lines (70 loc) • 2.09 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, getIdTokenClaims, loginWithRedirect } = useAuth0();
const [clientAuthed, setClientAuthed] = useState(false);
loggedOut = loggedOut || React.createElement("button", { onClick: loginWithRedirect }, "Log in");
loading = loading || React.createElement(React.Fragment, null, null);
useEffect(() => {
async function setAuth() {
const claims = await getIdTokenClaims();
const token = claims.__raw;
client.setAuth(token);
setClientAuthed(true);
}
if (isAuthenticated) {
void setAuth();
return () => client.clearAuth();
}
}, [isAuthenticated, getIdTokenClaims, isLoading, client]);
if (isLoading || isAuthenticated && !clientAuthed) {
return loading;
} else if (!isAuthenticated) {
return loggedOut;
}
return React.createElement(
ConvexProvider,
{ client },
children
);
}
//# sourceMappingURL=ConvexProviderWithAuth0.js.map