async function configurePortal()

in src/hooks/useKnockoutExplorer.ts [670:810]


async function configurePortal(): Promise<Explorer> {
  updateUserContext({
    authType: AuthType.AAD,
  });

  let explorer: Explorer;
  return new Promise((resolve) => {
    // In development mode, try to load the iframe message from session storage.
    // This allows webpack hot reload to function properly in the portal
    if (process.env.NODE_ENV === "development" && !window.location.search.includes("disablePortalInitCache")) {
      const initMessage = sessionStorage.getItem("portalDataExplorerInitMessage");
      if (initMessage) {
        const message = JSON.parse(initMessage) as DataExplorerInputsFrame;
        console.warn(
          "Loaded cached portal iframe message from session storage. Do a full page refresh to get a new message",
        );
        console.dir(message);
        updateContextsFromPortalMessage(message);
        explorer = new Explorer();

        // In development mode, save the iframe message from the portal in session storage.
        // This allows webpack hot reload to funciton properly
        if (process.env.NODE_ENV === "development") {
          sessionStorage.setItem("portalDataExplorerInitMessage", JSON.stringify(message));
        }
        resolve(explorer);
      }
    }

    // In the Portal, configuration of Explorer happens via iframe message
    window.addEventListener(
      "message",
      async (event) => {
        if (isInvalidParentFrameOrigin(event)) {
          return;
        }

        if (!shouldProcessMessage(event)) {
          return;
        }

        // Check for init message
        const message: PortalMessage = event.data?.data;
        const inputs = message?.inputs;
        const openAction = message?.openAction;
        if (inputs) {
          updateContextsFromPortalMessage(inputs);

          const { databaseAccount: account, subscriptionId, resourceGroup } = userContext;

          if (userContext.apiType === "SQL") {
            checkAndUpdateSelectedRegionalEndpoint();
          }

          let dataPlaneRbacEnabled;
          if (isDataplaneRbacSupported(userContext.apiType)) {
            if (LocalStorageUtility.hasItem(StorageKey.DataPlaneRbacEnabled)) {
              const isDataPlaneRbacSetting = LocalStorageUtility.getEntryString(StorageKey.DataPlaneRbacEnabled);
              Logger.logInfo(
                `Local storage RBAC setting for ${userContext.apiType} account ${account.name} is ${isDataPlaneRbacSetting}`,
                "Explorer/configurePortal",
              );

              if (isDataPlaneRbacSetting === Constants.RBACOptions.setAutomaticRBACOption) {
                dataPlaneRbacEnabled = account.properties.disableLocalAuth;
              } else {
                dataPlaneRbacEnabled = isDataPlaneRbacSetting === Constants.RBACOptions.setTrueRBACOption;
              }
            } else {
              Logger.logInfo(
                `Local storage does not exist for ${userContext.apiType} account ${account.name} with disable local auth set to ${account.properties.disableLocalAuth} is ${dataPlaneRbacEnabled}`,
                "Explorer/configurePortal",
              );
              dataPlaneRbacEnabled = account.properties.disableLocalAuth;
            }
            Logger.logInfo(
              `Data Plane RBAC value for ${userContext.apiType} account ${account.name} with disable local auth set to ${account.properties.disableLocalAuth} is ${dataPlaneRbacEnabled}`,
              "Explorer/configurePortal",
            );

            if (!dataPlaneRbacEnabled) {
              Logger.logInfo(
                `Calling fetch keys for ${userContext.apiType} account ${account.name}`,
                "Explorer/configurePortal",
              );
              await fetchAndUpdateKeys(subscriptionId, resourceGroup, account.name);
            } else {
              Logger.logInfo(
                `Trying to silently acquire MSAL token for ${userContext.apiType} account ${account.name}`,
                "Explorer/configurePortal",
              );
              try {
                const aadToken = await acquireMsalTokenForAccount(userContext.databaseAccount, true);
                updateUserContext({ aadToken: aadToken });
                useDataPlaneRbac.setState({ aadTokenUpdated: true });
              } catch (authError) {
                Logger.logWarning(
                  `Failed to silently acquire authorization token from MSAL: ${authError} for ${userContext.apiType} account ${account}`,
                  "Explorer/configurePortal",
                );
                logConsoleError("Failed to silently acquire authorization token: " + authError);
              }
            }

            updateUserContext({ dataPlaneRbacEnabled });
            useDataPlaneRbac.setState({ dataPlaneRbacEnabled: dataPlaneRbacEnabled });
          } else if (userContext.apiType !== "Postgres" && userContext.apiType !== "VCoreMongo") {
            Logger.logInfo(
              `Calling fetch keys for ${userContext.apiType} account ${account.name}`,
              "Explorer/configurePortal",
            );
            await fetchAndUpdateKeys(subscriptionId, resourceGroup, account.name);
          }

          explorer = new Explorer();
          resolve(explorer);

          if (openAction) {
            handleOpenAction(openAction, useDatabases.getState().databases, explorer);
          }
        } else if (shouldForwardMessage(message, event.origin)) {
          sendMessage(message);
        } else if (event.data?.type === MessageTypes.CloseTab) {
          if (
            event.data?.data?.tabId === "QuickstartPSQLShell" ||
            event.data?.data?.tabId === "QuickstartVcoreMongoShell"
          ) {
            useTabs.getState().closeReactTab(ReactTabKind.Quickstart);
          } else {
            useTabs.getState().closeTabsByComparator((tab) => tab.tabId === event.data?.data?.tabId);
          }
        } else if (message?.type === MessageTypes.RefreshResources) {
          explorer.onRefreshResourcesClick();
        }
      },
      false,
    );

    sendReadyMessage();
  });
}