All files / utils currentUser.ts

100% Statements 20/20
87.5% Branches 7/8
100% Functions 6/6
100% Lines 18/18

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          12x     10x 10x   1x   10x   2x 2x 1x   1x         12x       9x 9x 9x   1x 1x 1x                 10x 8x          
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import axios from "axios";
import { useNavigate } from "react-router-dom";
 
export function useCurrentUser() {
  const queryResults = useQuery({
    queryKey: ["current user"],
    queryFn: async () => {
      try {
        const response = await axios.get("/api/currentUser");
        const rolesList: string[] =
          response.data.roles?.map((r: { authority: string }) => r.authority) ??
          [];
        return { loggedIn: true, root: { ...response.data, rolesList } };
      } catch (e: unknown) {
        const err = e as { status?: number };
        if (err.status === 403) {
          return { loggedIn: false, root: {} };
        }
        throw e;
      }
    },
    initialData: { loggedIn: false, root: null },
  });
  return queryResults.data;
}
 
export function useLogout() {
  const queryClient = useQueryClient();
  const navigate = useNavigate();
  return useMutation({
    mutationFn: async () => {
      await axios.post("/logout");
      await queryClient.resetQueries({ queryKey: ["current user"] });
      navigate("/");
    },
  });
}
 
export function hasRole(
  currentUser: ReturnType<typeof useCurrentUser>,
  role: string,
): boolean {
  if (currentUser == null) return false;
  return (
    (currentUser.root as { rolesList?: string[] })?.rolesList?.includes(role) ??
    false
  );
}