All files / utils currentUser.js

100% Statements 22/22
100% Branches 8/8
100% Functions 6/6
100% Lines 20/20

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          165x     77x 77x 324x 67x 67x 67x   9x 9x                   125x 125x 125x 1x 1x 1x   125x                   305x   296x           3x     293x    
import { useMutation, useQuery, useQueryClient } from "react-query";
import axios from "axios";
import { useNavigate } from "react-router-dom";
 
export function useCurrentUser() {
  return useQuery(
    "current user",
    async () => {
      try {
        const response = await axios.get("/api/currentUser");
        const rolesList = response.data.roles.map((r) => r.authority);
        response.data = { ...response.data, rolesList: rolesList };
        const returnValue = { loggedIn: true, root: response.data };
        return returnValue;
      } catch (e) {
        console.error("Error invoking axios.get: ", e);
        return { loggedIn: false, root: null, initialData: true };
      }
    },
    {
      initialData: { loggedIn: false, root: null, initialData: true },
    },
  );
}
 
export function useLogout() {
  const queryClient = useQueryClient();
  const navigate = useNavigate();
  const mutation = useMutation(async () => {
    await axios.post("/logout");
    await queryClient.resetQueries("current user", { exact: true });
    navigate("/");
  });
  return mutation;
}
 
export function hasRole(currentUser, role) {
  // The following hack is because there is some bug in terms of the
  // shape of the data returned by useCurrentUser.  Is there a separate
  // data level, or not?
 
  // We will file an issue to track that down and then remove this hack
 
  if (currentUser == null) return false;
 
  if (
    "data" in currentUser &&
    "root" in currentUser.data &&
    currentUser.data.root != null &&
    "rolesList" in currentUser.data.root
  ) {
    return currentUser.data.root.rolesList.includes(role);
  }
 
  return currentUser.root?.rolesList?.includes(role);
}