All files / src/hooks useAuth.ts

98% Statements 98/100
80.95% Branches 34/42
100% Functions 15/15
98% Lines 98/100

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 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258                                          4x 2x   2x 1x 1x     2x           4x 22x       9x   9x 3x   6x 6x       2x 2x                         4x 894x   894x       25x 25x     25x     25x               4x 20x   20x       5x 5x     5x     5x 5x     5x 5x 5x 5x               4x 4x 4x           4x 29x   29x     8x 8x     8x       7x 7x     7x 7x 7x 7x   7x   7x 1x 6x 6x     7x   7x     6x 6x 6x                 6x 6x   6x 6x       1x 1x 1x 1x               4x 17x   17x     8x 8x   8x 1x       7x       6x 1x     5x     6x 6x 6x 6x   6x   6x 6x         6x   6x   1x 1x 1x                 1x 1x   1x 1x       5x 5x 5x 5x        
/**
 * Authentication Hooks
 */
 
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import {
  login,
  logout,
  getCurrentUser,
  masquerade,
  stopMasquerade,
  LoginCredentials,
  User,
  MasqueradeStackEntry
} from '../api/auth';
import { getCookie, setCookie, deleteCookie } from '../utils/cookies';
import { getBaseDomain, buildSubdomainUrl } from '../utils/domain';
 
/**
 * Helper hook to set auth tokens (used by invitation acceptance)
 */
export const useAuth = () => {
  const queryClient = useQueryClient();
 
  const setTokens = (accessToken: string, refreshToken: string) => {
    setCookie('access_token', accessToken, 7);
    setCookie('refresh_token', refreshToken, 7);
  };
 
  return { setTokens };
};
 
/**
 * Hook to get current user
 */
export const useCurrentUser = () => {
  return useQuery<User | null, Error>({
    queryKey: ['currentUser'],
    queryFn: async () => {
      // Check if token exists before making request (from cookie)
      const token = getCookie('access_token');
 
      if (!token) {
        return null; // No token, return null instead of making request
      }
      try {
        return await getCurrentUser();
      } catch (error) {
        // If getCurrentUser fails (e.g., 401), return null
        // The API client interceptor will handle token refresh
        console.error('Failed to get current user:', error);
        return null;
      }
    },
    retry: 1, // Retry once in case of token refresh
    staleTime: 5 * 60 * 1000, // 5 minutes
    refetchOnMount: true, // Always refetch when component mounts
    refetchOnWindowFocus: false,
  });
};
 
/**
 * Hook to login
 */
export const useLogin = () => {
  const queryClient = useQueryClient();
 
  return useMutation({
    mutationFn: login,
    onSuccess: (data) => {
      // Store tokens in cookies for cross-subdomain access
      setCookie('access_token', data.access, 7);
      setCookie('refresh_token', data.refresh, 7);
 
      // Clear any existing masquerade stack - this is a fresh login
      localStorage.removeItem('masquerade_stack');
 
      // Set user in cache
      queryClient.setQueryData(['currentUser'], data.user);
    },
  });
};
 
/**
 * Hook to logout
 */
export const useLogout = () => {
  const queryClient = useQueryClient();
 
  return useMutation({
    mutationFn: logout,
    onSuccess: () => {
      // Clear tokens (from cookies)
      deleteCookie('access_token');
      deleteCookie('refresh_token');
 
      // Clear masquerade stack
      localStorage.removeItem('masquerade_stack');
 
      // Clear user cache
      queryClient.removeQueries({ queryKey: ['currentUser'] });
      queryClient.clear();
 
      // Redirect to login page on root domain
      const protocol = window.location.protocol;
      const baseDomain = getBaseDomain();
      const port = window.location.port ? `:${window.location.port}` : '';
      window.location.href = `${protocol}//${baseDomain}${port}/login`;
    },
  });
};
 
/**
 * Check if user is authenticated
 */
export const useIsAuthenticated = (): boolean => {
  const { data: user, isLoading } = useCurrentUser();
  return !isLoading && !!user;
};
 
/**
 * Hook to masquerade as another user
 */
export const useMasquerade = () => {
  const queryClient = useQueryClient();
 
  return useMutation({
    mutationFn: async (user_pk: number) => {
      // Get current masquerading stack from localStorage
      const stackJson = localStorage.getItem('masquerade_stack');
      const currentStack: MasqueradeStackEntry[] = stackJson ? JSON.parse(stackJson) : [];
 
      // Call masquerade API with current stack
      return masquerade(user_pk, currentStack);
    },
    onSuccess: async (data) => {
      // Store the updated masquerading stack
      Eif (data.masquerade_stack) {
        localStorage.setItem('masquerade_stack', JSON.stringify(data.masquerade_stack));
      }
 
      const user = data.user;
      const currentHostname = window.location.hostname;
      const currentPort = window.location.port;
      const baseDomain = getBaseDomain();
 
      let targetSubdomain: string | null = null;
 
      if (['superuser', 'platform_manager', 'platform_support'].includes(user.role)) {
        targetSubdomain = 'platform';
      E} else if (user.business_subdomain) {
        targetSubdomain = user.business_subdomain;
      }
 
      const needsRedirect = targetSubdomain && currentHostname !== `${targetSubdomain}.${baseDomain}`;
 
      if (needsRedirect) {
        // CRITICAL: Clear the session cookie BEFORE redirect
        // Call logout API to clear HttpOnly sessionid cookie
        try {
          const apiUrl = import.meta.env.VITE_API_URL || `${window.location.protocol}//${baseDomain}`;
          await fetch(`${apiUrl}/auth/logout/`, {
            method: 'POST',
            credentials: 'include',
          });
        } catch (e) {
          // Continue anyway
        }
 
        // Pass tokens AND masquerading stack in URL (for cross-domain transfer)
        const stackEncoded = encodeURIComponent(JSON.stringify(data.masquerade_stack || []));
        const redirectUrl = buildSubdomainUrl(targetSubdomain, `/?access_token=${data.access}&refresh_token=${data.refresh}&masquerade_stack=${stackEncoded}`);
 
        window.location.href = redirectUrl;
        return;
      }
 
      // If no redirect needed (same subdomain), we can just set cookies and reload
      setCookie('access_token', data.access, 7);
      setCookie('refresh_token', data.refresh, 7);
      queryClient.setQueryData(['currentUser'], data.user);
      window.location.reload();
    },
  });
};
 
/**
 * Hook to stop masquerading and return to previous user
 */
export const useStopMasquerade = () => {
  const queryClient = useQueryClient();
 
  return useMutation({
    mutationFn: async () => {
      // Get current masquerading stack from localStorage
      const stackJson = localStorage.getItem('masquerade_stack');
      const currentStack: MasqueradeStackEntry[] = stackJson ? JSON.parse(stackJson) : [];
 
      if (currentStack.length === 0) {
        throw new Error('No masquerading session to stop');
      }
 
      // Call stop_masquerade API with current stack
      return stopMasquerade(currentStack);
    },
    onSuccess: async (data) => {
      // Update the masquerading stack
      if (data.masquerade_stack && data.masquerade_stack.length > 0) {
        localStorage.setItem('masquerade_stack', JSON.stringify(data.masquerade_stack));
      } else {
        // Clear the stack if empty
        localStorage.removeItem('masquerade_stack');
      }
 
      const user = data.user;
      const currentHostname = window.location.hostname;
      const currentPort = window.location.port;
      const baseDomain = getBaseDomain();
 
      let targetSubdomain: string | null = null;
 
      if (['superuser', 'platform_manager', 'platform_support'].includes(user.role)) {
        targetSubdomain = 'platform';
      E} else if (user.business_subdomain) {
        targetSubdomain = user.business_subdomain;
      }
 
      const needsRedirect = targetSubdomain && currentHostname !== `${targetSubdomain}.${baseDomain}`;
 
      if (needsRedirect) {
        // CRITICAL: Clear the session cookie BEFORE redirect
        try {
          const apiUrl = import.meta.env.VITE_API_URL || `${window.location.protocol}//${baseDomain}`;
          await fetch(`${apiUrl}/auth/logout/`, {
            method: 'POST',
            credentials: 'include',
          });
        } catch (e) {
          // Continue anyway
        }
 
        // Pass tokens AND masquerading stack in URL (for cross-domain transfer)
        const stackEncoded = encodeURIComponent(JSON.stringify(data.masquerade_stack || []));
        const redirectUrl = buildSubdomainUrl(targetSubdomain, `/?access_token=${data.access}&refresh_token=${data.refresh}&masquerade_stack=${stackEncoded}`);
 
        window.location.href = redirectUrl;
        return;
      }
 
      // If no redirect needed (same subdomain), we can just set cookies and reload
      setCookie('access_token', data.access, 7);
      setCookie('refresh_token', data.refresh, 7);
      queryClient.setQueryData(['currentUser'], data.user);
      window.location.reload();
    },
  });
};