2026-04-23 15:33:11 +03:30
|
|
|
'use client';
|
|
|
|
|
|
2026-04-29 14:02:42 +03:30
|
|
|
import React, { createContext, useCallback, useContext, useEffect, useMemo, useState } from 'react';
|
2026-04-23 15:33:11 +03:30
|
|
|
import { useRouter } from 'next/navigation';
|
|
|
|
|
import { authApi } from '@/lib/api/auth';
|
2026-04-30 14:05:44 +03:30
|
|
|
import { User, Organization } from '@/types/organization';
|
2026-04-23 15:33:11 +03:30
|
|
|
|
|
|
|
|
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,
|
2026-04-29 20:19:40 +03:30
|
|
|
organizationEmail: string,
|
2026-04-23 15:33:11 +03:30
|
|
|
organizationType: 'CLINIC' | 'LAB'
|
|
|
|
|
) => Promise<void>;
|
|
|
|
|
login: (email: string, password: string) => Promise<void>;
|
|
|
|
|
logout: () => Promise<void>;
|
|
|
|
|
selectOrganization: (orgId: string) => Promise<void>;
|
2026-04-29 20:19:40 +03:30
|
|
|
createOrganization: (
|
|
|
|
|
organizationName: string,
|
|
|
|
|
organizationEmail: string,
|
|
|
|
|
organizationType: 'CLINIC' | 'LAB',
|
|
|
|
|
planName?: string,
|
|
|
|
|
) => Promise<string>;
|
2026-04-23 15:33:11 +03:30
|
|
|
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();
|
|
|
|
|
|
2026-04-29 14:02:42 +03:30
|
|
|
const normalizeProfilePayload = useCallback((payload: any): { user: User | null; organizations: Organization[] } => {
|
2026-04-28 11:57:29 +03:30
|
|
|
const organizations = payload?.organizations || [];
|
|
|
|
|
|
|
|
|
|
if (payload?.user) {
|
|
|
|
|
return { user: payload.user as User, organizations };
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (payload?.id && payload?.email && payload?.name) {
|
|
|
|
|
return {
|
|
|
|
|
user: {
|
|
|
|
|
id: payload.id,
|
|
|
|
|
email: payload.email,
|
|
|
|
|
name: payload.name,
|
|
|
|
|
},
|
|
|
|
|
organizations,
|
|
|
|
|
};
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return { user: null, organizations };
|
2026-04-29 14:02:42 +03:30
|
|
|
}, []);
|
2026-04-28 11:57:29 +03:30
|
|
|
|
2026-04-29 14:02:42 +03:30
|
|
|
const checkAuth = useCallback(async () => {
|
2026-04-23 15:33:11 +03:30
|
|
|
try {
|
|
|
|
|
setIsLoading(true);
|
|
|
|
|
|
|
|
|
|
const response = await authApi.getProfile();
|
|
|
|
|
|
|
|
|
|
if (response.success) {
|
2026-04-28 11:57:29 +03:30
|
|
|
const { user: userData, organizations: orgs } = normalizeProfilePayload(response.data);
|
2026-04-23 15:33:11 +03:30
|
|
|
|
|
|
|
|
setUser(userData);
|
|
|
|
|
setOrganizations(orgs);
|
|
|
|
|
|
|
|
|
|
const storedOrgId = localStorage.getItem('currentOrganizationId');
|
|
|
|
|
if (storedOrgId && orgs.length > 0) {
|
|
|
|
|
const org = orgs.find(o => o.id === storedOrgId);
|
2026-04-29 13:32:22 +03:30
|
|
|
if (org) {
|
|
|
|
|
setCurrentOrganization(org);
|
|
|
|
|
// Ensure cookie token carries organizationId for org-scoped APIs.
|
|
|
|
|
await authApi.selectOrganization(org.id);
|
|
|
|
|
} else {
|
|
|
|
|
setCurrentOrganization(null);
|
|
|
|
|
}
|
2026-04-28 11:57:29 +03:30
|
|
|
} else if (orgs.length === 1 && userData) {
|
2026-04-23 15:33:11 +03:30
|
|
|
setCurrentOrganization(orgs[0]);
|
|
|
|
|
localStorage.setItem('currentOrganizationId', orgs[0].id);
|
2026-04-29 13:32:22 +03:30
|
|
|
// Keep JWT in sync with selected org even for single-org users.
|
|
|
|
|
await authApi.selectOrganization(orgs[0].id);
|
2026-04-28 11:57:29 +03:30
|
|
|
} else {
|
|
|
|
|
setCurrentOrganization(null);
|
2026-04-23 15:33:11 +03:30
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
} 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);
|
|
|
|
|
}
|
2026-04-29 14:02:42 +03:30
|
|
|
}, [normalizeProfilePayload]);
|
|
|
|
|
|
|
|
|
|
useEffect(() => {
|
|
|
|
|
void checkAuth();
|
|
|
|
|
}, [checkAuth]);
|
2026-04-23 15:33:11 +03:30
|
|
|
|
|
|
|
|
// ✅ REGISTER
|
2026-04-29 14:02:42 +03:30
|
|
|
const registerTrial = useCallback(async (
|
2026-04-23 15:33:11 +03:30
|
|
|
email: string,
|
|
|
|
|
password: string,
|
|
|
|
|
name: string,
|
|
|
|
|
organizationName: string,
|
2026-04-29 20:19:40 +03:30
|
|
|
organizationEmail: string,
|
2026-04-23 15:33:11 +03:30
|
|
|
organizationType: 'CLINIC' | 'LAB'
|
|
|
|
|
) => {
|
|
|
|
|
try {
|
|
|
|
|
setIsLoading(true);
|
|
|
|
|
setError(null);
|
|
|
|
|
|
|
|
|
|
const response = await authApi.registerTrial({
|
|
|
|
|
email,
|
|
|
|
|
password,
|
|
|
|
|
name,
|
|
|
|
|
organizationName,
|
2026-04-29 20:19:40 +03:30
|
|
|
organizationEmail,
|
2026-04-23 15:33:11 +03:30
|
|
|
organizationType,
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
setUser(response.data.user);
|
|
|
|
|
setOrganizations(response.data.organizations);
|
|
|
|
|
|
|
|
|
|
const orgs = response.data.organizations;
|
|
|
|
|
|
|
|
|
|
if (orgs.length === 1) {
|
|
|
|
|
const org = orgs[0];
|
2026-04-29 13:32:22 +03:30
|
|
|
await authApi.selectOrganization(org.id);
|
2026-04-23 15:33:11 +03:30
|
|
|
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);
|
|
|
|
|
}
|
2026-04-29 14:02:42 +03:30
|
|
|
}, [router]);
|
2026-04-23 15:33:11 +03:30
|
|
|
|
|
|
|
|
// ✅ LOGIN
|
2026-04-29 14:02:42 +03:30
|
|
|
const login = useCallback(async (email: string, password: string) => {
|
2026-04-23 15:33:11 +03:30
|
|
|
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];
|
2026-04-29 13:32:22 +03:30
|
|
|
await authApi.selectOrganization(org.id);
|
2026-04-23 15:33:11 +03:30
|
|
|
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);
|
|
|
|
|
}
|
2026-04-29 14:02:42 +03:30
|
|
|
}, [router]);
|
2026-04-23 15:33:11 +03:30
|
|
|
|
2026-04-29 14:02:42 +03:30
|
|
|
const logout = useCallback(async () => {
|
2026-04-29 15:55:58 +03:30
|
|
|
try {
|
|
|
|
|
// Important: clear auth cookies/session on the server first,
|
|
|
|
|
// otherwise middleware may still treat the user as authenticated.
|
|
|
|
|
await authApi.logout();
|
|
|
|
|
} catch (err) {
|
|
|
|
|
console.error('Logout API failed:', err);
|
|
|
|
|
} finally {
|
|
|
|
|
localStorage.clear();
|
|
|
|
|
setUser(null);
|
|
|
|
|
setOrganizations([]);
|
|
|
|
|
setCurrentOrganization(null);
|
|
|
|
|
setError(null);
|
|
|
|
|
setIsAuthReady(true);
|
|
|
|
|
router.replace('/');
|
|
|
|
|
router.refresh();
|
|
|
|
|
}
|
2026-04-29 14:02:42 +03:30
|
|
|
}, [router]);
|
2026-04-23 15:33:11 +03:30
|
|
|
|
2026-04-29 14:02:42 +03:30
|
|
|
const selectOrganization = useCallback(async (orgId: string) => {
|
2026-04-23 15:33:11 +03:30
|
|
|
try {
|
|
|
|
|
setIsLoading(true);
|
|
|
|
|
|
|
|
|
|
const response = await authApi.selectOrganization(orgId);
|
|
|
|
|
|
|
|
|
|
const { organization } = response.data;
|
|
|
|
|
|
|
|
|
|
localStorage.setItem('currentOrganizationId', organization.id);
|
|
|
|
|
|
2026-04-29 21:55:46 +03:30
|
|
|
setCurrentOrganization({
|
|
|
|
|
id: organization.id,
|
|
|
|
|
name: organization.name,
|
|
|
|
|
type: organization.type as Organization['type'],
|
|
|
|
|
isOwner: Boolean((organization as { isOwner?: boolean }).isOwner),
|
2026-04-30 00:52:05 +03:30
|
|
|
permissions: (organization as { permissions?: string[] }).permissions,
|
2026-04-29 21:55:46 +03:30
|
|
|
plan: (organization as { plan?: Organization['plan'] }).plan,
|
|
|
|
|
});
|
2026-04-23 15:33:11 +03:30
|
|
|
|
|
|
|
|
router.push('/today');
|
|
|
|
|
|
|
|
|
|
} catch (err: any) {
|
|
|
|
|
setError(err.message);
|
|
|
|
|
throw err;
|
|
|
|
|
} finally {
|
|
|
|
|
setIsLoading(false);
|
|
|
|
|
}
|
2026-04-29 14:02:42 +03:30
|
|
|
}, [router]);
|
2026-04-23 15:33:11 +03:30
|
|
|
|
2026-04-29 20:19:40 +03:30
|
|
|
const createOrganization = useCallback(async (
|
|
|
|
|
organizationName: string,
|
|
|
|
|
organizationEmail: string,
|
|
|
|
|
organizationType: 'CLINIC' | 'LAB',
|
|
|
|
|
planName?: string,
|
|
|
|
|
) => {
|
|
|
|
|
try {
|
|
|
|
|
setIsLoading(true);
|
|
|
|
|
setError(null);
|
|
|
|
|
|
|
|
|
|
const createResponse = await authApi.createOrganization({
|
|
|
|
|
organizationName,
|
|
|
|
|
organizationEmail,
|
|
|
|
|
organizationType,
|
|
|
|
|
planName,
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
const profileResponse = await authApi.getProfile();
|
|
|
|
|
if (profileResponse.success) {
|
|
|
|
|
const { user: userData, organizations: orgs } = normalizeProfilePayload(profileResponse.data);
|
|
|
|
|
setUser(userData);
|
|
|
|
|
setOrganizations(orgs);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return createResponse.data.organization.id as string;
|
|
|
|
|
} catch (err: any) {
|
|
|
|
|
setError(err.message || 'Failed to create organization');
|
|
|
|
|
throw err;
|
|
|
|
|
} finally {
|
|
|
|
|
setIsLoading(false);
|
|
|
|
|
}
|
|
|
|
|
}, [normalizeProfilePayload]);
|
|
|
|
|
|
2026-04-29 14:02:42 +03:30
|
|
|
const clearError = useCallback(() => setError(null), []);
|
|
|
|
|
|
|
|
|
|
const contextValue = useMemo(
|
|
|
|
|
() => ({
|
|
|
|
|
user,
|
|
|
|
|
organizations,
|
|
|
|
|
currentOrganization,
|
|
|
|
|
isLoading,
|
|
|
|
|
isAuthReady,
|
|
|
|
|
error,
|
|
|
|
|
registerTrial,
|
|
|
|
|
login,
|
|
|
|
|
logout,
|
|
|
|
|
selectOrganization,
|
2026-04-29 20:19:40 +03:30
|
|
|
createOrganization,
|
2026-04-29 14:02:42 +03:30
|
|
|
clearError,
|
|
|
|
|
}),
|
|
|
|
|
[
|
|
|
|
|
user,
|
|
|
|
|
organizations,
|
|
|
|
|
currentOrganization,
|
|
|
|
|
isLoading,
|
|
|
|
|
isAuthReady,
|
|
|
|
|
error,
|
|
|
|
|
registerTrial,
|
|
|
|
|
login,
|
|
|
|
|
logout,
|
|
|
|
|
selectOrganization,
|
2026-04-29 20:19:40 +03:30
|
|
|
createOrganization,
|
2026-04-29 14:02:42 +03:30
|
|
|
clearError,
|
|
|
|
|
],
|
|
|
|
|
);
|
2026-04-23 15:33:11 +03:30
|
|
|
|
|
|
|
|
return (
|
2026-04-29 14:02:42 +03:30
|
|
|
<AuthContext.Provider value={contextValue}>
|
2026-04-23 15:33:11 +03:30
|
|
|
{children}
|
|
|
|
|
</AuthContext.Provider>
|
|
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export const useAuth = () => {
|
|
|
|
|
const context = useContext(AuthContext);
|
|
|
|
|
if (!context) throw new Error('useAuth must be used within AuthProvider');
|
|
|
|
|
return context;
|
|
|
|
|
};
|