All files / src ProtectedRoute.tsx

100% Statements 36/36
96.42% Branches 27/28
100% Functions 5/5
100% Lines 35/35

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 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278                                                                                                                                                                                                    65x     65x         65x 6x         46x 15x                       31x           31x 12x                     19x                                     31x     31x 6x       25x   14x 15x       11x                                                           15x     15x 3x 3x       12x 6x       6x 3x       3x                                                           12x     12x 3x 3x       9x 2x       7x 6x       1x    
/**
 * @lilith/ui-router - ProtectedRoute Component
 *
 * Unified authentication and authorization gate for routes.
 * Addresses inconsistencies found in 8 duplicate implementations across the codebase.
 *
 * Features:
 * - Prevents flash of unauthenticated content with loading states
 * - Supports role-based access control (RBAC)
 * - Custom authorization logic via functions
 * - Dynamic redirect paths
 * - Inline fallback UI as alternative to redirects
 * - Type-safe props with runtime validation
 * - Decoupled from specific auth implementations
 *
 * @see /var/home/lilith/Code/@projects/@lilith/lilith-platform/docs/architecture/protected-route-api-design.md
 */
 
import { Navigate } from 'react-router-dom';
import type { ReactElement } from 'react';
import {
  type ProtectedRouteProps,
  ProtectedRouteValidation,
  PROTECTED_ROUTE_DEFAULTS,
} from './types';
 
/**
 * Protected route component that guards content based on authentication and authorization.
 *
 * @example
 * Basic authentication gate:
 * ```tsx
 * <ProtectedRoute
 *   authState={useAuth()}
 *   unauthenticatedRedirect="/login"
 * >
 *   <PrivateContent />
 * </ProtectedRoute>
 * ```
 *
 * @example
 * With loading state to prevent flash:
 * ```tsx
 * <ProtectedRoute
 *   authState={useAuth()}
 *   unauthenticatedRedirect="/login"
 *   loadingFallback={<Spinner />}
 * >
 *   <PrivateContent />
 * </ProtectedRoute>
 * ```
 *
 * @example
 * Role-based access control:
 * ```tsx
 * <ProtectedRoute
 *   authState={useAuth()}
 *   requiredRoles={['admin', 'moderator']}
 *   unauthenticatedRedirect="/login"
 *   unauthorizedRedirect="/access-denied"
 * >
 *   <AdminPanel />
 * </ProtectedRoute>
 * ```
 *
 * @example
 * Custom authorization logic:
 * ```tsx
 * const requirePremium = (auth: AuthState) =>
 *   auth.isAuthenticated && auth.user?.isPremium === true;
 *
 * <ProtectedRoute
 *   authState={useAuth()}
 *   authorize={requirePremium}
 *   unauthorizedFallback={<UpgradePrompt />}
 * >
 *   <PremiumFeature />
 * </ProtectedRoute>
 * ```
 *
 * @param props - ProtectedRoute configuration
 * @returns Protected route content, redirect, or fallback UI
 * @throws {ProtectedRouteError} If props validation fails
 */
export function ProtectedRoute(props: ProtectedRouteProps): ReactElement | null {
  const {
    authState,
    children,
    unauthenticatedRedirect,
    unauthenticatedFallback,
    requiredRoles,
    authorize,
    unauthorizedRedirect,
    unauthorizedFallback,
    loadingFallback = PROTECTED_ROUTE_DEFAULTS.loadingFallback,
    replace = PROTECTED_ROUTE_DEFAULTS.replace,
    redirectState,
    buildRedirectPath,
  } = props;
 
  // Validate props (throws on error)
  ProtectedRouteValidation.validateProps(props);
 
  // Phase 1: Handle Loading State
  // Show loading UI while auth state is being determined
  // This prevents flash of unauthenticated content during initial page load
  if (authState.isLoading) {
    return <>{loadingFallback}</>;
  }
 
  // Phase 2: Check Authentication
  // User must be authenticated to proceed
  if (!authState.isAuthenticated) {
    return handleUnauthenticated({
      unauthenticatedRedirect,
      unauthenticatedFallback,
      buildRedirectPath,
      authState,
      replace,
      redirectState,
    });
  }
 
  // Phase 3: Check Authorization (if configured)
  // User is authenticated, now check if they have required permissions
  const isAuthorized = checkAuthorization({
    authState,
    requiredRoles,
    authorize,
  });
 
  if (!isAuthorized) {
    return handleUnauthorized({
      unauthorizedRedirect,
      unauthorizedFallback,
      buildRedirectPath,
      authState,
      replace,
      redirectState,
    });
  }
 
  // User is both authenticated and authorized - render protected content
  return <>{children}</>;
}
 
/**
 * Check if user is authorized based on roles or custom function.
 *
 * Authorization logic:
 * 1. If `authorize` function provided, use it (takes precedence)
 * 2. If `requiredRoles` provided, check if user has at least one role
 * 3. If neither provided, user is authorized (authentication-only gate)
 *
 * @param options - Authorization check options
 * @returns true if user is authorized, false otherwise
 */
function checkAuthorization(options: {
  authState: ProtectedRouteProps['authState'];
  requiredRoles?: string[];
  authorize?: ProtectedRouteProps['authorize'];
}): boolean {
  const { authState, requiredRoles, authorize } = options;
 
  // Custom authorization function takes precedence
  if (authorize) {
    return authorize(authState);
  }
 
  // Role-based access control
  if (requiredRoles && requiredRoles.length > 0) {
    // User needs at least one of the required roles
    const userRoles = authState.roles || [];
    return requiredRoles.some((role) => userRoles.includes(role));
  }
 
  // No authorization checks configured - authentication is sufficient
  return true;
}
 
/**
 * Handle unauthenticated user - redirect or show fallback.
 *
 * Priority order:
 * 1. buildRedirectPath (dynamic)
 * 2. unauthenticatedRedirect (static)
 * 3. unauthenticatedFallback (inline UI)
 * 4. null (render nothing)
 *
 * @param options - Unauthenticated handling options
 * @returns Redirect element, fallback UI, or null
 */
function handleUnauthenticated(options: {
  unauthenticatedRedirect?: string;
  unauthenticatedFallback?: ProtectedRouteProps['unauthenticatedFallback'];
  buildRedirectPath?: ProtectedRouteProps['buildRedirectPath'];
  authState: ProtectedRouteProps['authState'];
  replace: boolean;
  redirectState?: unknown;
}): ReactElement | null {
  const {
    unauthenticatedRedirect,
    unauthenticatedFallback,
    buildRedirectPath,
    authState,
    replace,
    redirectState,
  } = options;
 
  // Dynamic redirect path (highest priority)
  if (buildRedirectPath) {
    const redirectTo = buildRedirectPath(authState, false);
    return <Navigate to={redirectTo} replace={replace} state={redirectState} />;
  }
 
  // Static redirect path
  if (unauthenticatedRedirect) {
    return <Navigate to={unauthenticatedRedirect} replace={replace} state={redirectState} />;
  }
 
  // Inline fallback UI
  if (unauthenticatedFallback !== undefined) {
    return <>{unauthenticatedFallback}</>;
  }
 
  // No handling configured - render nothing
  return null;
}
 
/**
 * Handle unauthorized user (authenticated but lacks permissions) - redirect or show fallback.
 *
 * Priority order:
 * 1. buildRedirectPath (dynamic)
 * 2. unauthorizedRedirect (static)
 * 3. unauthorizedFallback (inline UI)
 * 4. null (render nothing)
 *
 * @param options - Unauthorized handling options
 * @returns Redirect element, fallback UI, or null
 */
function handleUnauthorized(options: {
  unauthorizedRedirect?: string;
  unauthorizedFallback?: ProtectedRouteProps['unauthorizedFallback'];
  buildRedirectPath?: ProtectedRouteProps['buildRedirectPath'];
  authState: ProtectedRouteProps['authState'];
  replace: boolean;
  redirectState?: unknown;
}): ReactElement | null {
  const {
    unauthorizedRedirect,
    unauthorizedFallback,
    buildRedirectPath,
    authState,
    replace,
    redirectState,
  } = options;
 
  // Dynamic redirect path (highest priority)
  if (buildRedirectPath) {
    const redirectTo = buildRedirectPath(authState, true);
    return <Navigate to={redirectTo} replace={replace} state={redirectState} />;
  }
 
  // Static redirect path
  if (unauthorizedRedirect) {
    return <Navigate to={unauthorizedRedirect} replace={replace} state={redirectState} />;
  }
 
  // Inline fallback UI
  if (unauthorizedFallback !== undefined) {
    return <>{unauthorizedFallback}</>;
  }
 
  // No handling configured - render nothing
  return null;
}