Auth dialog Events


Auth dialog is used to capture new auths from your end users. The dialog window posts some events to the global window object that can be captures to take further actions.

You can attach a message event listener to the window where user's click on create auth button.

window.addEventListener("message", onmessage);

By doing this, you will be able to capture the messages sent by the auth popup window.

The three events you would want to capture from the window are:

  • tray.authPopup.error This event is fired when the auth dialog runs into unexpected errors (ex. mismatched service environment ID and service ID)
  • tray.authpopup.close This event is fired when the auth dialog is closed by the user abruptly
  • tray.authpopup.finish This event is fired when the user provides the auth details and the popup window closes by itself. This event would contain the authId of the newly created auth. Here's how this event's data would look:
Copy
Copied
{
  "type": "tray.authpopup.finish",
  "authType": "oauth",
  "authId": "1209xxxx-xxxx-xxxx-xxxx-xxxxxx8d3779"
}

Here is a sample code on how you could structure your authWindow function:

Copy
Copied
export const openAuthWindow = (url) => {
  // Must open window from user interaction code otherwise it is likely
  // to be blocked by a popup blocker:
  const authWindow = window.open(
    undefined,
    "_blank",
    "width=500,height=500,scrollbars=no"
  );
  const onmessage = (e) => {
    console.log("message", e.data.type, e.data);
    if (e.data.type === "tray.authPopup.error") {
      // Handle popup error message
      alert(`Error: ${e.data.error}`);
      authWindow.close();
    }
    if (
      e.data.type === "tray.authpopup.close" ||
      e.data.type === "tray.authpopup.finish"
    ) {
      authWindow.close();
    }
  };
  window.addEventListener("message", onmessage);

  // Check if popup window has been closed
  const CHECK_TIMEOUT = 1000;
  const checkClosedWindow = () => {
    if (authWindow.closed) {
      window.removeEventListener("message", onmessage);
    } else {
      setTimeout(checkClosedWindow, CHECK_TIMEOUT);
    }
  };

  checkClosedWindow();
  authWindow.location = url;
};

const authDialogURL = `https://${AUTH_DIALOG_URL}/external/auth/create/${PARTNER_NAME}?code=${json.data?.generateAuthorizationCode?.authorizationCode}&serviceId=${serviceId.current}&serviceEnvironmentId=${selectedServiceEnvironment.id}&scopes[]=${scopes}`;

openAuthWindow(authDialogURL);

You can also check the code of the form builder app to see how it's implemented there.