All files / src RequireAuth.tsx

0% Statements 0/33
0% Branches 0/30
0% Functions 0/4
0% Lines 0/32

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                                                                                                                                                                                                                                                                                                                                                                                                                                         
/**
 * RequireAuth Component
 *
 * Unified route protection component that handles:
 * 1. Authentication state (loading, authenticated, unauthenticated)
 * 2. Role-based authorization (requiredRoles)
 * 3. Custom authorization logic (authorize function)
 * 4. Graceful fallbacks vs strict redirects
 *
 * This component replaces 8+ duplicate implementations found across features
 * with a single, comprehensive, type-safe solution.
 *
 * @example
 * Basic authentication:
 * ```tsx
 * <RequireAuth
 *   authState={useAuth()}
 *   unauthenticatedRedirect="/login"
 * >
 *   <PrivateContent />
 * </RequireAuth>
 * ```
 *
 * @example
 * Role-based access control:
 * ```tsx
 * <RequireAuth
 *   authState={useAuth()}
 *   requiredRoles={['admin', 'moderator']}
 *   unauthenticatedRedirect="/login"
 *   unauthorizedRedirect="/access-denied"
 * >
 *   <AdminPanel />
 * </RequireAuth>
 * ```
 *
 * @example
 * Custom authorization with fallback:
 * ```tsx
 * <RequireAuth
 *   authState={useAuth()}
 *   authorize={(auth) => auth.user?.isPremium === true}
 *   unauthorizedFallback={<UpgradePrompt />}
 * >
 *   <PremiumFeature />
 * </RequireAuth>
 * ```
 */
 
import type { ReactNode } from 'react';
import { Navigate } from 'react-router-dom';
import type {
  ProtectedRouteProps,
  AuthState,
  AuthorizationFunction,
} from './types';
import { ProtectedRouteValidation, PROTECTED_ROUTE_DEFAULTS } from './types';
 
/**
 * Check if user has at least one of the required roles.
 *
 * @param authState - Current authentication state
 * @param requiredRoles - Array of roles to check against
 * @returns true if user has at least one required role, false otherwise
 */
function hasRequiredRole(authState: AuthState, requiredRoles: string[]): boolean {
  if (!authState.roles || authState.roles.length === 0) {
    return false;
  }
 
  return requiredRoles.some((role) => authState.roles!.includes(role));
}
 
/**
 * Determine if user is authorized based on role requirements or custom function.
 *
 * @param authState - Current authentication state
 * @param requiredRoles - Optional array of required roles
 * @param authorizeFunc - Optional custom authorization function
 * @returns true if user is authorized, false otherwise
 */
function checkAuthorization(
  authState: AuthState,
  requiredRoles?: string[],
  authorizeFunc?: AuthorizationFunction
): boolean {
  // Custom authorization takes precedence
  if (authorizeFunc) {
    return authorizeFunc(authState);
  }
 
  // Role-based authorization
  if (requiredRoles && requiredRoles.length > 0) {
    return hasRequiredRole(authState, requiredRoles);
  }
 
  // No authorization checks - only authentication required
  return true;
}
 
/**
 * RequireAuth Component
 *
 * Protects routes with authentication and optional authorization checks.
 * Supports both graceful fallbacks (inline prompts) and strict redirects.
 *
 * Phase 1: Loading State
 * - Shows loadingFallback while authState.isLoading === true
 * - Prevents flash of unauthenticated content
 *
 * Phase 2: Authentication Check
 * - If not authenticated → redirect or show fallback
 * - Redirects are replace-mode by default (no back button to protected page)
 *
 * Phase 3: Authorization Check (optional)
 * - Only runs if user is authenticated
 * - Checks requiredRoles or runs authorize function
 * - If unauthorized → redirect or show fallback
 *
 * Phase 4: Render Protected Content
 * - All checks passed → render children
 *
 * @param props - RequireAuth component props
 * @returns Protected route content or redirect/fallback
 */
export function RequireAuth(props: ProtectedRouteProps): ReactNode {
  const {
    authState,
    children,
    unauthenticatedRedirect,
    unauthenticatedFallback,
    requiredRoles,
    authorize,
    unauthorizedRedirect,
    unauthorizedFallback,
    loadingFallback = PROTECTED_ROUTE_DEFAULTS.loadingFallback,
    replace = PROTECTED_ROUTE_DEFAULTS.replace,
    redirectState,
    buildRedirectPath,
  } = props;
 
  // Validate props on mount (throws if invalid)
  ProtectedRouteValidation.validateProps(props);
 
  // ===== Phase 1: Loading State =====
  if (authState.isLoading) {
    return <>{loadingFallback}</>;
  }
 
  // ===== Phase 2: Authentication Check =====
  if (!authState.isAuthenticated) {
    // Use custom redirect builder if provided
    if (buildRedirectPath) {
      const redirectPath = buildRedirectPath(authState, false);
      return <Navigate to={redirectPath} replace={replace} state={redirectState} />;
    }
 
    // Fallback takes precedence over redirect (more graceful UX)
    if (unauthenticatedFallback !== undefined) {
      return <>{unauthenticatedFallback}</>;
    }
 
    // Redirect to login/auth page
    if (unauthenticatedRedirect) {
      return <Navigate to={unauthenticatedRedirect} replace={replace} state={redirectState} />;
    }
 
    // No redirect or fallback configured - fail safe by rendering nothing
    // This prevents rendering protected content but is not ideal.
    // Developers should configure either unauthenticatedRedirect or unauthenticatedFallback.
    return null;
  }
 
  // ===== Phase 3: Authorization Check (Optional) =====
  const isAuthorized = checkAuthorization(authState, requiredRoles, authorize);
 
  if (!isAuthorized) {
    // Use custom redirect builder if provided
    if (buildRedirectPath) {
      const redirectPath = buildRedirectPath(authState, false);
      return <Navigate to={redirectPath} replace={replace} state={redirectState} />;
    }
 
    // Fallback takes precedence over redirect (more graceful UX)
    if (unauthorizedFallback !== undefined) {
      return <>{unauthorizedFallback}</>;
    }
 
    // Redirect to unauthorized/access-denied page
    if (unauthorizedRedirect) {
      return <Navigate to={unauthorizedRedirect} replace={replace} state={redirectState} />;
    }
 
    // No redirect or fallback configured - fail safe by rendering nothing
    // This prevents rendering unauthorized content but is not ideal.
    // Developers should configure either unauthorizedRedirect or unauthorizedFallback.
    return null;
  }
 
  // ===== Phase 4: Render Protected Content =====
  return <>{children}</>;
}
 
// Named export for the component
export default RequireAuth;
 
/**
 * Type-safe props for RequireAuth component.
 * Re-exported from types.ts for convenience.
 */
export type { ProtectedRouteProps as RequireAuthProps };
export type { AuthState, AuthorizationFunction };