All files / utils useCurrentUser.js

100% Statements 34/34
100% Branches 16/16
100% Functions 3/3
100% Lines 34/34

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 381x 1x   1x 236x 236x 236x 92x 92x 92x 1x 1x 92x 1x 1x 88x 88x 88x 92x 2x 1x 1x 1x 1x 1x 2x 236x 236x 236x 236x 236x   1x 355x   355x 355x  
import { useQuery } from "@tanstack/react-query";
import axios from "axios";
 
export function useCurrentUser() {
  const queryResults = useQuery({
    queryKey: ["current user"],
    queryFn: async () => {
      try {
        const response = await axios.get("/api/currentUser");
        if (response.data == null) {
          return { loggedIn: false, root: {} };
        }
        if (!(response.data instanceof Object) || !("roles" in response.data)) {
          return { loggedIn: false, root: response.data };
        }
        let rolesList = response.data.roles.map((r) => r.authority);
        response.data = { ...response.data, rolesList: rolesList };
        return { loggedIn: true, root: response.data };
      } catch (e) {
        if (e.status === 403) {
          return { loggedIn: false, root: {} };
        } else {
          console.error("Error invoking axios.get: ", e);
          throw e;
        }
      }
    },
    initialData: { loggedIn: false, root: null, initialData: true },
  });
  return queryResults.data;
}
 
export function hasRole(currentUser, role) {
  if (currentUser == null) return false;
 
  return currentUser.root?.rolesList?.includes(role);
}