export function AccountProvider()

in packages/app/src/account-provider.tsx [35:104]


export function AccountProvider({ children }: { children: React.ReactNode }) {
  const [authenticated, setAuthenticated] =  React.useState<any>(false);
  const [registryHref, setRegistryHref] =  React.useState<any>(null);
  const [login, setLogin] = React.useState<any>(null);
  const [loading, setLoading] = React.useState<any>(true);
  const [initialLoad, setInitialLoad] = React.useState<boolean>(true);
  const [ott, setOtt] = React.useState<any>(undefined);
  const flash = useFlashMessage();

  const logout = async () => {
    await fetch('/logout', {
      method: 'POST'
    });
    setLogin(null);
    setAuthenticated(false);
    setRegistryHref(null);
    setOtt(false);
  };

  const value = { authenticated, registryHref, login, ott, setOtt, logout };

  React.useEffect(() => {
    if (!initialLoad) return;
    setInitialLoad(false);

    // Store ott used during authentication:
    let tempOtt;
    if (window.location.search) {
      const match = window.location.search.match(/ott=(?<ott>[^&]+)/);
      if (match && match.groups) {
        tempOtt = match.groups.ott;
      }
    }

    // Check if user is logged in, if so allow protected routes
    // to be accessed:
    async function fetchAccount() {
      const resp = await fetch(tempOtt ? `/_/account?ott=${tempOtt}` : '/_/account');
      const json = await resp.json();
      if (json.authenticated) {
        setLogin(json.login);
        setAuthenticated(json.authenticated);
        setRegistryHref(json.registryHref);
      }
      if (json.ott) {
        setOtt(json.ott);
      }
      if (json.flash) {
        const flashObject = JSON.parse(json.flash);
        flash.set(flashObject.severity, flashObject.message);   
      }
      setLoading(false);
    }

    fetchAccount();
  }, [flash, initialLoad]);

  if (!loading) {
    return <AccountContext.Provider value={value}>{children}</AccountContext.Provider>;
  } else {
    return (
      <Backdrop
        sx={{ color: '#fff', zIndex: (theme) => theme.zIndex.drawer + 1 }}
        open={true}
      >
        <CircularProgress color="inherit" />
      </Backdrop>
    );
  }
}