Files
dyolink/frontend/src/lib/hooks/useAuth.tsx

216 lines
5.4 KiB
TypeScript
Raw Normal View History

'use client';
import React, { createContext, useContext, useEffect, useState } from 'react';
import { useRouter } from 'next/navigation';
import { authApi } from '@/lib/api/auth';
import { User, Organization } from '@/types';
interface AuthContextType {
user: User | null;
organizations: Organization[];
currentOrganization: Organization | null;
isLoading: boolean;
isAuthReady: boolean; // ✅ NEW
error: string | null;
registerTrial: (
email: string,
password: string,
name: string,
organizationName: string,
organizationType: 'CLINIC' | 'LAB'
) => Promise<void>;
login: (email: string, password: string) => Promise<void>;
logout: () => Promise<void>;
selectOrganization: (orgId: string) => Promise<void>;
clearError: () => void;
}
const AuthContext = createContext<AuthContextType | undefined>(undefined);
export function AuthProvider({ children }: { children: React.ReactNode }) {
const [user, setUser] = useState<User | null>(null);
const [organizations, setOrganizations] = useState<Organization[]>([]);
const [currentOrganization, setCurrentOrganization] = useState<Organization | null>(null);
const [isLoading, setIsLoading] = useState(false);
const [isAuthReady, setIsAuthReady] = useState(false); // ✅ KEY FIX
const [error, setError] = useState<string | null>(null);
const router = useRouter();
useEffect(() => {
checkAuth();
}, []);
const checkAuth = async () => {
try {
setIsLoading(true);
const hasSession = document.cookie.includes('accessToken');
if (!hasSession) {
console.log('No session → skipping auth check');
return;
}
const response = await authApi.getProfile();
if (response.success) {
const userData = response.data.user;
const orgs = response.data.organizations || [];
setUser(userData);
setOrganizations(orgs);
const storedOrgId = localStorage.getItem('currentOrganizationId');
if (storedOrgId && orgs.length > 0) {
const org = orgs.find(o => o.id === storedOrgId);
if (org) setCurrentOrganization(org);
} else if (orgs.length === 1) {
setCurrentOrganization(orgs[0]);
localStorage.setItem('currentOrganizationId', orgs[0].id);
}
}
} catch (err) {
console.error('Auth check failed:', err);
// Only clear state — DO NOT redirect here
setUser(null);
setOrganizations([]);
setCurrentOrganization(null);
} finally {
setIsLoading(false);
setIsAuthReady(true);
}
};
// ✅ REGISTER
const registerTrial = async (
email: string,
password: string,
name: string,
organizationName: string,
organizationType: 'CLINIC' | 'LAB'
) => {
try {
setIsLoading(true);
setError(null);
const response = await authApi.registerTrial({
email,
password,
name,
organizationName,
organizationType,
});
setUser(response.data.user);
setOrganizations(response.data.organizations);
const orgs = response.data.organizations;
if (orgs.length === 1) {
const org = orgs[0];
setCurrentOrganization(org);
localStorage.setItem('currentOrganizationId', org.id);
router.push('/today');
} else {
router.push('/select-organization');
}
} catch (err: any) {
setError(err.message || 'Registration failed');
throw err;
} finally {
setIsLoading(false);
}
};
// ✅ LOGIN
const login = async (email: string, password: string) => {
try {
setIsLoading(true);
setError(null);
const response = await authApi.login({ email, password });
setUser(response.data.user);
setOrganizations(response.data.organizations);
const orgs = response.data.organizations;
if (orgs.length === 1) {
const org = orgs[0];
setCurrentOrganization(org);
localStorage.setItem('currentOrganizationId', org.id);
router.push('/today');
} else {
router.push('/select-organization');
}
} catch (err: any) {
setError(err.message || 'Login failed');
throw err;
} finally {
setIsLoading(false);
}
};
const logout = async () => {
localStorage.clear();
setUser(null);
setOrganizations([]);
setCurrentOrganization(null);
router.push('/');
};
const selectOrganization = async (orgId: string) => {
try {
setIsLoading(true);
const response = await authApi.selectOrganization(orgId);
const { organization } = response.data;
localStorage.setItem('currentOrganizationId', organization.id);
setCurrentOrganization(organization);
router.push('/today');
} catch (err: any) {
setError(err.message);
throw err;
} finally {
setIsLoading(false);
}
};
const clearError = () => setError(null);
return (
<AuthContext.Provider
value={{
user,
organizations,
currentOrganization,
isLoading,
isAuthReady, // ✅ expose it
error,
registerTrial,
login,
logout,
selectOrganization,
clearError,
}}
>
{children}
</AuthContext.Provider>
);
}
export const useAuth = () => {
const context = useContext(AuthContext);
if (!context) throw new Error('useAuth must be used within AuthProvider');
return context;
};