All files / client/src/components KompassiLoginCallback.tsx

88% Statements 22/25
90% Branches 9/10
100% Functions 3/3
88% Lines 22/25

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                            520x 27x 27x   27x   27x 27x 27x   27x 27x       27x 27x   27x       24x 6x     6x     18x 18x         21x 3x 3x   18x     27x          
import { ReactElement, useEffect } from "react";
import { useNavigate, useSearchParams } from "react-router";
import { AppRoute } from "client/app/routes";
import { Loading } from "client/components/Loading";
import { useAppDispatch } from "client/utils/hooks";
import {
  clearKompassiLoginState,
  getKompassiLoginState,
} from "client/utils/sessionStorage";
import {
  LoginErrorMessage,
  submitKompassiLogin,
} from "client/views/login/loginThunks";
 
export const KompassiLoginCallback = (): ReactElement => {
  const dispatch = useAppDispatch();
  const navigate = useNavigate();
 
  const [searchParams] = useSearchParams();
 
  const code = searchParams.get("code");
  const error = searchParams.get("error");
  const state = searchParams.get("state");
 
  useEffect(() => {
    const fetchData = async (): Promise<void> => {
      // Read and drop the state before branching: it has to be single use, so
      // a denied or abandoned login must not leave one behind that a later
      // callback could satisfy
      const expectedState = getKompassiLoginState();
      clearKompassiLoginState();
 
      if (code) {
        // The state is session-scoped, so only the tab that started the login
        // holds it: a mismatch means this callback answers a request we did
        // not make
        if (!expectedState || state !== expectedState) {
          await navigate(
            `${AppRoute.LOGIN}?error=${LoginErrorMessage.LOGIN_FAILED}`,
          );
          return;
        }
 
        const errorMessage = await dispatch(submitKompassiLogin(code));
        Iif (errorMessage) {
          await navigate(`${AppRoute.LOGIN}?error=${errorMessage}`);
          return;
        }
      }
      if (error) {
        await navigate(AppRoute.LOGIN);
        return;
      }
      await navigate(AppRoute.ROOT);
    };
    // eslint-disable-next-line @typescript-eslint/no-floating-promises
    fetchData();
  }, [code, error, state, dispatch, navigate]);
 
  return <Loading />;
};