All files / src/features/auth/components protected-route.tsx

100% Statements 10/10
100% Branches 4/4
100% Functions 1/1
100% Lines 10/10

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              3x 58x   58x 58x 58x 10x     1x     58x   48x         10x    
import { Navigate, useLocation } from 'react-router-dom';
import { authService } from '../services/auth.service';
import { AUTH_ROUTES } from '@/constants/route';
import { AUTH_STATES } from '@/constants/auth';
 
import type { PropsWithChildren } from 'react';
 
export const ProtectedRoute = ({ children }: PropsWithChildren) => {
  const location = useLocation();
 
  let authState = AUTH_STATES.UNAUTHENTICATED;
  try {
    if (authService.isAuthenticated()) {
      authState = AUTH_STATES.AUTHENTICATED;
    }
  } catch (error) {
    console.error('Error checking authentication status:', error);
  }
 
  if (authState !== AUTH_STATES.AUTHENTICATED) {
    // Redirect to auth page with return url
    return (
      <Navigate to={AUTH_ROUTES.LOGIN} state={{ from: location }} replace />
    );
  }
 
  return <>{children}</>;
};