All files / src/components DBSLoginWebcomponentPlugin.ts

0% Statements 0/37
0% Branches 0/1
0% Functions 0/1
0% Lines 0/37

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64                                                                                                                               
import { onMounted, ref } from "vue";
 
import AuthorizationEventDetails from "@/types/AuthorizationEventDetails";
 
/**
 * Event from the Login-Webcomponent which notifies when the
 * oauth2-token changes.
 */
const AUTH_REFRESH_EVENT_NAME = "authorization-event";
 
/**
 * Plugin to use for webcomponents which rely on the `dbs-login`-Webcomponent
 * This Plugin registers necessary event-handlers to get notified of authentication-changes
 * and checks predefined cookies of the active domain for access tokens to use.
 *
 * It exposes two properties to be used by the parent component:
 *
 * @param loginCallback Callback-Method which is called after the user is successfully signed in.
 * @param logoutCallback Callback-Method which is called after the user is logged out.
 *
 * @return loading By default true, until authentication fails. Should be set to false after successfull loading of data.
 * @return loggedIn default false, turns true after a successfull authentification.
 */
export function useDBSLoginWebcomponentPlugin(
  loginCallback: (accessToken: AuthorizationEventDetails) => void = () => {},
  logoutCallback: () => void = () => {}
) {
  const loading = ref(true);
  const loggedIn = ref(false);
  let prevAuthDetails: AuthorizationEventDetails | undefined = undefined;
 
  onMounted(() => {
    document.addEventListener(AUTH_REFRESH_EVENT_NAME, (ev: any) => {
      loading.value = true;
      console.debug(
        "Event-Handler " + AUTH_REFRESH_EVENT_NAME + " triggered.",
        ev
      );
      authChanged(ev.detail);
    });
  });
 
  function authChanged(newAuthDetails: AuthorizationEventDetails | undefined) {
    loading.value = false;
    if (newAuthDetails) {
      loggedIn.value = true;
      if (JSON.stringify(newAuthDetails) !== JSON.stringify(prevAuthDetails)) {
        console.debug("#authChanged calling loginCallback");
        loginCallback(newAuthDetails);
        prevAuthDetails = newAuthDetails;
      } else {
        // details unchanged, do nothing.
      }
    } else {
      loggedIn.value = false;
      console.debug("#authChanged calling logoutCallback");
      logoutCallback();
    }
  }
 
  // expose managed state as return value
  return { loading, loggedIn };
}