All files / utils useCurrentUser.js

100% Statements 19/19
100% Branches 10/10
100% Functions 4/4
100% Lines 17/17

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        77x     34x 34x 32x 1x   31x 1x   130x 30x 30x   2x 1x   1x 1x           77x       119x   117x    
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);
}