All files / src/context AuthContext.tsx

7.5% Statements 3/40
8.33% Branches 2/24
10% Functions 1/10
7.89% Lines 3/38

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              3x                                                       3x                                                                                                                                                                                                                               18x                    
import React, { createContext, useContext, useEffect, useState } from "react";
import { useAuth } from "@/hooks/useAuth";
import { CoreUser } from "@/objects/CoreUser";
import { APIHandler } from "@/services/api/ApiHandler";
import Onboarding from "@/pages/Onboarding";
import { IS_STANDALONE } from "@/util/standalone";
 
const MOCK_CORE_USER: CoreUser = {
  id: "standalone-user",
  auth0_id: "standalone|dev",
  email: "dev@chain-r.local",
  email_verified: true,
  name: "Standalone Dev",
  picture: null,
  is_active: true,
  is_superuser: true,
  created_at: new Date().toISOString(),
  updated_at: new Date().toISOString(),
};
 
interface AuthUser {
  user_id: string;
  email: string;
  name: string;
  picture?: string;
}
 
interface AuthContextType {
  user: AuthUser;
  coreUser: CoreUser;
  loading: boolean;
  logout: () => void;
  refetchUser: () => void;
}
 
const AuthContext = createContext<AuthContextType | undefined>(undefined);
 
function makeApiHandler(): APIHandler {
  return new APIHandler(import.meta.env.VITE_API_URL as string, null, {
    withCredentials: true,
    headers: { "Content-Type": "application/json" },
  });
}
 
export function AuthProvider({ children }: { children: React.ReactNode }) {
  const { user, loading: authLoading, logout, refetchUser } = useAuth();
 
  const [coreUser, setCoreUser] = useState<CoreUser | null>(null);
  const [provisioningChecked, setProvisioningChecked] = useState(false);
 
  // Once the Auth0 session resolves, check if the user is provisioned in svc-core
  useEffect(() => {
    // Standalone mode: skip the svc-core round-trip and use a mock user.
    if (IS_STANDALONE) {
      setCoreUser(MOCK_CORE_USER);
      setProvisioningChecked(true);
      return;
    }
 
    if (authLoading || !user) return;
 
    let cancelled = false;
    const api = makeApiHandler();
 
    api.user_router.me().then((result) => {
      if (cancelled) return;
      setCoreUser(result);
      setProvisioningChecked(true);
    });
 
    return () => {
      cancelled = true;
    };
  }, [authLoading, user]);
 
  // --- Loading states ---
 
  if (authLoading) {
    return (
      <div className="flex items-center justify-center min-h-screen">
        <div className="text-center">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-gray-800 dark:border-gray-200 mx-auto" />
          <p className="mt-4 text-sm text-gray-500 dark:text-gray-400">Loading...</p>
        </div>
      </div>
    );
  }
 
  if (!user) {
    return (
      <div className="flex items-center justify-center min-h-screen">
        <div className="text-center">
          <p className="text-xl mb-2 text-gray-900 dark:text-white">Not authenticated</p>
          <p className="text-sm text-gray-500 dark:text-gray-400">Redirecting to login...</p>
        </div>
      </div>
    );
  }
 
  // Auth0 session is valid but provisioning check is still in flight
  if (!provisioningChecked) {
    return (
      <div className="flex items-center justify-center min-h-screen">
        <div className="text-center">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-gray-800 dark:border-gray-200 mx-auto" />
          <p className="mt-4 text-sm text-gray-500 dark:text-gray-400">Setting up your account...</p>
        </div>
      </div>
    );
  }
 
  // User authenticated but not yet provisioned — show onboarding
  if (!coreUser) {
    const api = makeApiHandler();
 
    return (
      <Onboarding
        defaultName={user.name ?? ""}
        onProvision={(name) => api.user_router.provision(name)}
        onComplete={(provisioned) => setCoreUser(provisioned)}
      />
    );
  }
 
  return (
    <AuthContext.Provider value={{ user, coreUser, loading: authLoading, logout, refetchUser }}>
      {children}
    </AuthContext.Provider>
  );
}
 
/**
 * The signed-in person's svc-core id, or null outside an `AuthProvider` —
 * for a page that only adjusts what it offers by whose a row is (a link to
 * a record only its owner can open), and so should still render in a test
 * or a standalone build without one.
 */
export function useCurrentUserId(): string | null {
  return useContext(AuthContext)?.coreUser?.id ?? null;
}
 
/**
 * The signed-in person's svc-core user, or null outside an `AuthProvider` —
 * for a page that shows something only to some people (a platform role's
 * tools, `util/platformRoles.ts`) and should still render without one.
 */
export function useCurrentUser(): CoreUser | null {
  return useContext(AuthContext)?.coreUser ?? null;
}
 
export function useAuthContext() {
  const context = useContext(AuthContext);
  if (!context) {
    throw new Error("useAuthContext must be used within AuthProvider");
  }
  return context;
}