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-06-20 14:51:43 +03:30
|
|
|
import { useTranslations } from 'next-intl';
|
2026-06-20 12:37:38 +03:30
|
|
|
import { useRouter } from '@/i18n/navigation';
|
2026-04-23 15:33:11 +03:30
|
|
|
import { authApi } from '@/lib/api/auth';
|
2026-07-02 17:59:49 +03:30
|
|
|
import {
|
|
|
|
|
clearRememberedEmail,
|
|
|
|
|
getRememberedEmail,
|
|
|
|
|
setRememberedEmail,
|
|
|
|
|
} from '@/lib/auth/rememberMe';
|
2026-04-30 14:05:44 +03:30
|
|
|
import { User, Organization } from '@/types/organization';
|
2026-06-20 14:51:43 +03:30
|
|
|
import { isAppLocale, getLocaleFromPathname } from '@/i18n/routing';
|
2026-07-12 17:51:31 +03:30
|
|
|
import {
|
|
|
|
|
clearAccessTokenExpiresAt,
|
|
|
|
|
rememberAccessTokenExpiresAt,
|
|
|
|
|
startProactiveSessionRefresh,
|
|
|
|
|
} from '@/lib/auth/proactiveRefresh';
|
2026-07-18 16:57:13 +03:30
|
|
|
import { notifyAccessTokenRefreshed } from '@/lib/auth/accessTokenEvents';
|
2026-07-12 18:27:38 +03:30
|
|
|
import { asApiError, legacyStatusCode, type ApiError } from '@/types/api';
|
2026-07-14 21:07:05 +03:30
|
|
|
import { consumeAuthRedirect } from '@/lib/auth/postAuthRedirect';
|
2026-07-12 18:27:38 +03:30
|
|
|
|
|
|
|
|
function toApiError(err: unknown): ApiError {
|
|
|
|
|
return (
|
|
|
|
|
asApiError(err) ?? {
|
|
|
|
|
statusCode: legacyStatusCode(err) ?? 500,
|
|
|
|
|
code:
|
|
|
|
|
legacyStatusCode(err) === 401
|
|
|
|
|
? 'AUTH_UNAUTHORIZED'
|
|
|
|
|
: legacyStatusCode(err) === 403
|
|
|
|
|
? 'PERMISSION_DENIED'
|
|
|
|
|
: 'INTERNAL_ERROR',
|
|
|
|
|
}
|
|
|
|
|
);
|
|
|
|
|
}
|
2026-04-23 15:33:11 +03:30
|
|
|
|
|
|
|
|
interface AuthContextType {
|
|
|
|
|
user: User | null;
|
|
|
|
|
organizations: Organization[];
|
|
|
|
|
currentOrganization: Organization | null;
|
|
|
|
|
isLoading: boolean;
|
2026-06-20 12:37:38 +03:30
|
|
|
isAuthReady: boolean;
|
2026-07-12 18:27:38 +03:30
|
|
|
apiError: ApiError | null;
|
2026-04-23 15:33:11 +03:30
|
|
|
registerTrial: (
|
|
|
|
|
email: string,
|
|
|
|
|
password: string,
|
|
|
|
|
name: string,
|
2026-07-04 00:01:58 +03:30
|
|
|
mobile: string,
|
2026-04-23 15:33:11 +03:30
|
|
|
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>;
|
2026-07-02 17:59:49 +03:30
|
|
|
login: (email: string, password: string, rememberMe?: boolean) => Promise<void>;
|
2026-04-23 15:33:11 +03:30
|
|
|
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-06-20 12:37:38 +03:30
|
|
|
setUserLanguage: (language: string) => void;
|
2026-07-04 00:01:58 +03:30
|
|
|
refreshSession: () => Promise<void>;
|
2026-04-23 15:33:11 +03:30
|
|
|
clearError: () => void;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const AuthContext = createContext<AuthContextType | undefined>(undefined);
|
|
|
|
|
|
|
|
|
|
export function AuthProvider({ children }: { children: React.ReactNode }) {
|
2026-06-20 14:51:43 +03:30
|
|
|
const t = useTranslations('auth');
|
2026-04-23 15:33:11 +03:30
|
|
|
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
|
2026-07-12 18:27:38 +03:30
|
|
|
const [apiError, setApiError] = useState<ApiError | null>(null);
|
2026-04-23 15:33:11 +03:30
|
|
|
|
|
|
|
|
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) {
|
2026-06-20 12:37:38 +03:30
|
|
|
return {
|
|
|
|
|
user: {
|
|
|
|
|
...(payload.user as User),
|
|
|
|
|
language: (payload.user as User).language ?? 'en',
|
|
|
|
|
},
|
|
|
|
|
organizations,
|
|
|
|
|
};
|
2026-04-28 11:57:29 +03:30
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (payload?.id && payload?.email && payload?.name) {
|
|
|
|
|
return {
|
|
|
|
|
user: {
|
|
|
|
|
id: payload.id,
|
|
|
|
|
email: payload.email,
|
|
|
|
|
name: payload.name,
|
2026-06-20 12:37:38 +03:30
|
|
|
language: payload.language ?? 'en',
|
2026-04-28 11:57:29 +03:30
|
|
|
},
|
|
|
|
|
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-07-12 17:51:31 +03:30
|
|
|
rememberAccessTokenExpiresAt(
|
|
|
|
|
(response.data as { accessTokenExpiresAt?: string }).accessTokenExpiresAt,
|
|
|
|
|
);
|
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) {
|
2026-07-12 17:51:31 +03:30
|
|
|
const selected = await authApi.selectOrganization(org.id);
|
|
|
|
|
setCurrentOrganization({
|
|
|
|
|
id: selected.data.organization.id,
|
|
|
|
|
name: selected.data.organization.name,
|
|
|
|
|
type: selected.data.organization.type as Organization['type'],
|
|
|
|
|
isOwner: Boolean(selected.data.organization.isOwner),
|
|
|
|
|
permissions: selected.data.organization.permissions,
|
|
|
|
|
plan: selected.data.organization.plan,
|
|
|
|
|
});
|
2026-04-29 13:32:22 +03:30
|
|
|
} else {
|
|
|
|
|
setCurrentOrganization(null);
|
|
|
|
|
}
|
2026-04-28 11:57:29 +03:30
|
|
|
} else if (orgs.length === 1 && userData) {
|
2026-07-12 17:51:31 +03:30
|
|
|
const selected = await authApi.selectOrganization(orgs[0].id);
|
2026-04-23 15:33:11 +03:30
|
|
|
localStorage.setItem('currentOrganizationId', orgs[0].id);
|
2026-07-12 17:51:31 +03:30
|
|
|
setCurrentOrganization({
|
|
|
|
|
id: selected.data.organization.id,
|
|
|
|
|
name: selected.data.organization.name,
|
|
|
|
|
type: selected.data.organization.type as Organization['type'],
|
|
|
|
|
isOwner: Boolean(selected.data.organization.isOwner),
|
|
|
|
|
permissions: selected.data.organization.permissions,
|
|
|
|
|
plan: selected.data.organization.plan,
|
|
|
|
|
});
|
2026-04-28 11:57:29 +03:30
|
|
|
} else {
|
|
|
|
|
setCurrentOrganization(null);
|
2026-04-23 15:33:11 +03:30
|
|
|
}
|
|
|
|
|
}
|
2026-06-26 13:23:03 +03:30
|
|
|
} catch (err: unknown) {
|
2026-07-12 18:27:38 +03:30
|
|
|
const status = legacyStatusCode(err);
|
2026-06-26 13:23:03 +03:30
|
|
|
|
2026-07-12 17:51:31 +03:30
|
|
|
// Access token may have expired while refresh cookie is still valid (e.g. JWT_EXPIRES_IN=15m).
|
|
|
|
|
if (status === 401) {
|
|
|
|
|
try {
|
|
|
|
|
const refreshResult = await authApi.refreshSessionFromCookies();
|
|
|
|
|
rememberAccessTokenExpiresAt(refreshResult.data?.accessTokenExpiresAt);
|
|
|
|
|
const orgId = localStorage.getItem('currentOrganizationId');
|
|
|
|
|
if (orgId) {
|
|
|
|
|
await authApi.selectOrganization(orgId);
|
|
|
|
|
}
|
2026-07-18 16:57:13 +03:30
|
|
|
notifyAccessTokenRefreshed();
|
2026-07-12 17:51:31 +03:30
|
|
|
const retry = await authApi.getProfile();
|
|
|
|
|
if (retry.success) {
|
|
|
|
|
const { user: userData, organizations: orgs } = normalizeProfilePayload(retry.data);
|
|
|
|
|
rememberAccessTokenExpiresAt(
|
|
|
|
|
(retry.data as { accessTokenExpiresAt?: string }).accessTokenExpiresAt,
|
|
|
|
|
);
|
|
|
|
|
setUser(userData);
|
|
|
|
|
setOrganizations(orgs);
|
|
|
|
|
|
|
|
|
|
const storedOrgId = localStorage.getItem('currentOrganizationId');
|
|
|
|
|
if (storedOrgId && orgs.length > 0) {
|
|
|
|
|
const org = orgs.find((o) => o.id === storedOrgId);
|
|
|
|
|
if (org) {
|
|
|
|
|
const selected = await authApi.selectOrganization(org.id);
|
|
|
|
|
setCurrentOrganization({
|
|
|
|
|
id: selected.data.organization.id,
|
|
|
|
|
name: selected.data.organization.name,
|
|
|
|
|
type: selected.data.organization.type as Organization['type'],
|
|
|
|
|
isOwner: Boolean(selected.data.organization.isOwner),
|
|
|
|
|
permissions: selected.data.organization.permissions,
|
|
|
|
|
plan: selected.data.organization.plan,
|
|
|
|
|
});
|
|
|
|
|
} else {
|
|
|
|
|
setCurrentOrganization(null);
|
|
|
|
|
}
|
|
|
|
|
} else if (orgs.length === 1 && userData) {
|
|
|
|
|
const selected = await authApi.selectOrganization(orgs[0].id);
|
|
|
|
|
localStorage.setItem('currentOrganizationId', orgs[0].id);
|
|
|
|
|
setCurrentOrganization({
|
|
|
|
|
id: selected.data.organization.id,
|
|
|
|
|
name: selected.data.organization.name,
|
|
|
|
|
type: selected.data.organization.type as Organization['type'],
|
|
|
|
|
isOwner: Boolean(selected.data.organization.isOwner),
|
|
|
|
|
permissions: selected.data.organization.permissions,
|
|
|
|
|
plan: selected.data.organization.plan,
|
|
|
|
|
});
|
|
|
|
|
} else {
|
|
|
|
|
setCurrentOrganization(null);
|
|
|
|
|
}
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
} catch {
|
|
|
|
|
/* fall through to logged-out state */
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-06-26 13:23:03 +03:30
|
|
|
// 401 on profile is expected when there is no session — not an application error.
|
|
|
|
|
if (status !== 401) {
|
|
|
|
|
console.error('Auth check failed:', err);
|
|
|
|
|
}
|
|
|
|
|
|
2026-04-23 15:33:11 +03:30
|
|
|
// Only clear state — DO NOT redirect here
|
|
|
|
|
setUser(null);
|
|
|
|
|
setOrganizations([]);
|
|
|
|
|
setCurrentOrganization(null);
|
2026-07-12 17:51:31 +03:30
|
|
|
clearAccessTokenExpiresAt();
|
2026-04-23 15:33:11 +03:30
|
|
|
} 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
|
|
|
|
2026-07-12 17:51:31 +03:30
|
|
|
useEffect(() => {
|
|
|
|
|
if (!user || !isAuthReady) {
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return startProactiveSessionRefresh();
|
|
|
|
|
}, [user, isAuthReady]);
|
|
|
|
|
|
2026-06-20 14:51:43 +03:30
|
|
|
const applyUrlLocaleToUser = useCallback(async (user: User): Promise<User> => {
|
|
|
|
|
if (typeof window === 'undefined') return user;
|
|
|
|
|
|
|
|
|
|
const urlLocale = getLocaleFromPathname(window.location.pathname);
|
|
|
|
|
if (!isAppLocale(urlLocale) || user.language === urlLocale) {
|
|
|
|
|
return user;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
try {
|
|
|
|
|
await authApi.updateLanguage(urlLocale);
|
|
|
|
|
} catch {
|
|
|
|
|
/* keep URL locale in client state even if persistence fails */
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return { ...user, language: urlLocale };
|
|
|
|
|
}, []);
|
|
|
|
|
|
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,
|
2026-07-04 00:01:58 +03:30
|
|
|
mobile: string,
|
2026-04-23 15:33:11 +03:30
|
|
|
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);
|
2026-07-12 18:27:38 +03:30
|
|
|
setApiError(null);
|
2026-04-23 15:33:11 +03:30
|
|
|
|
|
|
|
|
const response = await authApi.registerTrial({
|
|
|
|
|
email,
|
2026-07-04 00:01:58 +03:30
|
|
|
mobile,
|
2026-04-23 15:33:11 +03:30
|
|
|
password,
|
|
|
|
|
name,
|
|
|
|
|
organizationName,
|
2026-04-29 20:19:40 +03:30
|
|
|
organizationEmail,
|
2026-04-23 15:33:11 +03:30
|
|
|
organizationType,
|
|
|
|
|
});
|
|
|
|
|
|
2026-06-20 14:51:43 +03:30
|
|
|
const userData = await applyUrlLocaleToUser(response.data.user);
|
2026-07-12 17:51:31 +03:30
|
|
|
rememberAccessTokenExpiresAt(response.data.accessTokenExpiresAt);
|
2026-06-20 14:51:43 +03:30
|
|
|
setUser(userData);
|
2026-04-23 15:33:11 +03:30
|
|
|
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);
|
|
|
|
|
} else {
|
|
|
|
|
router.push('/select-organization');
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
} catch (err: any) {
|
2026-07-12 18:27:38 +03:30
|
|
|
setApiError(toApiError(err));
|
2026-04-23 15:33:11 +03:30
|
|
|
throw err;
|
|
|
|
|
} finally {
|
|
|
|
|
setIsLoading(false);
|
|
|
|
|
}
|
2026-06-20 14:51:43 +03:30
|
|
|
}, [applyUrlLocaleToUser, router, t]);
|
2026-04-23 15:33:11 +03:30
|
|
|
|
|
|
|
|
// ✅ LOGIN
|
2026-07-02 17:59:49 +03:30
|
|
|
const login = useCallback(async (
|
|
|
|
|
email: string,
|
|
|
|
|
password: string,
|
|
|
|
|
rememberMe = false,
|
|
|
|
|
) => {
|
2026-04-23 15:33:11 +03:30
|
|
|
try {
|
|
|
|
|
setIsLoading(true);
|
2026-07-12 18:27:38 +03:30
|
|
|
setApiError(null);
|
2026-04-23 15:33:11 +03:30
|
|
|
|
2026-07-02 17:59:49 +03:30
|
|
|
const response = await authApi.login({ email, password, rememberMe });
|
|
|
|
|
|
|
|
|
|
if (rememberMe) {
|
|
|
|
|
setRememberedEmail(email);
|
|
|
|
|
} else {
|
|
|
|
|
clearRememberedEmail();
|
|
|
|
|
}
|
2026-04-23 15:33:11 +03:30
|
|
|
|
2026-06-20 14:51:43 +03:30
|
|
|
const userData = await applyUrlLocaleToUser(response.data.user);
|
2026-07-12 17:51:31 +03:30
|
|
|
rememberAccessTokenExpiresAt(response.data.accessTokenExpiresAt);
|
2026-06-20 14:51:43 +03:30
|
|
|
setUser(userData);
|
2026-04-23 15:33:11 +03:30
|
|
|
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);
|
|
|
|
|
} else {
|
|
|
|
|
router.push('/select-organization');
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
} catch (err: any) {
|
2026-07-12 18:27:38 +03:30
|
|
|
setApiError(toApiError(err));
|
2026-04-23 15:33:11 +03:30
|
|
|
throw err;
|
|
|
|
|
} finally {
|
|
|
|
|
setIsLoading(false);
|
|
|
|
|
}
|
2026-06-20 14:51:43 +03:30
|
|
|
}, [applyUrlLocaleToUser, router, t]);
|
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,
|
2026-06-20 14:51:43 +03:30
|
|
|
// otherwise proxy may still treat the user as authenticated.
|
2026-04-29 15:55:58 +03:30
|
|
|
await authApi.logout();
|
|
|
|
|
} catch (err) {
|
|
|
|
|
console.error('Logout API failed:', err);
|
|
|
|
|
} finally {
|
2026-07-02 17:59:49 +03:30
|
|
|
const rememberedEmail = getRememberedEmail();
|
2026-04-29 15:55:58 +03:30
|
|
|
localStorage.clear();
|
2026-07-02 17:59:49 +03:30
|
|
|
if (rememberedEmail) {
|
|
|
|
|
setRememberedEmail(rememberedEmail);
|
|
|
|
|
}
|
2026-04-29 15:55:58 +03:30
|
|
|
setUser(null);
|
|
|
|
|
setOrganizations([]);
|
|
|
|
|
setCurrentOrganization(null);
|
2026-07-12 18:27:38 +03:30
|
|
|
setApiError(null);
|
2026-07-12 17:51:31 +03:30
|
|
|
clearAccessTokenExpiresAt();
|
2026-04-29 15:55:58 +03:30
|
|
|
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
|
|
|
|
2026-07-14 21:07:05 +03:30
|
|
|
const redirectPath = consumeAuthRedirect();
|
2026-07-04 00:01:58 +03:30
|
|
|
if (redirectPath) {
|
|
|
|
|
router.push(redirectPath);
|
|
|
|
|
} else {
|
|
|
|
|
router.push('/today');
|
|
|
|
|
}
|
2026-04-23 15:33:11 +03:30
|
|
|
|
|
|
|
|
} catch (err: any) {
|
2026-07-12 18:27:38 +03:30
|
|
|
setApiError(toApiError(err));
|
2026-04-23 15:33:11 +03:30
|
|
|
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);
|
2026-07-12 18:27:38 +03:30
|
|
|
setApiError(null);
|
2026-04-29 20:19:40 +03:30
|
|
|
|
|
|
|
|
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) {
|
2026-07-12 18:27:38 +03:30
|
|
|
setApiError(toApiError(err));
|
2026-04-29 20:19:40 +03:30
|
|
|
throw err;
|
|
|
|
|
} finally {
|
|
|
|
|
setIsLoading(false);
|
|
|
|
|
}
|
2026-06-20 14:51:43 +03:30
|
|
|
}, [normalizeProfilePayload, t]);
|
2026-04-29 20:19:40 +03:30
|
|
|
|
2026-07-04 00:01:58 +03:30
|
|
|
const refreshSession = useCallback(async () => {
|
|
|
|
|
await checkAuth();
|
|
|
|
|
}, [checkAuth]);
|
|
|
|
|
|
2026-07-12 18:27:38 +03:30
|
|
|
const clearError = useCallback(() => setApiError(null), []);
|
2026-04-29 14:02:42 +03:30
|
|
|
|
2026-06-20 12:37:38 +03:30
|
|
|
const setUserLanguage = useCallback((language: string) => {
|
|
|
|
|
const normalized = isAppLocale(language) ? language : 'en';
|
|
|
|
|
setUser((current) => (current ? { ...current, language: normalized } : current));
|
|
|
|
|
}, []);
|
|
|
|
|
|
2026-04-29 14:02:42 +03:30
|
|
|
const contextValue = useMemo(
|
|
|
|
|
() => ({
|
|
|
|
|
user,
|
|
|
|
|
organizations,
|
|
|
|
|
currentOrganization,
|
|
|
|
|
isLoading,
|
|
|
|
|
isAuthReady,
|
2026-07-12 18:27:38 +03:30
|
|
|
apiError,
|
2026-04-29 14:02:42 +03:30
|
|
|
registerTrial,
|
|
|
|
|
login,
|
|
|
|
|
logout,
|
|
|
|
|
selectOrganization,
|
2026-04-29 20:19:40 +03:30
|
|
|
createOrganization,
|
2026-06-20 12:37:38 +03:30
|
|
|
setUserLanguage,
|
2026-07-04 00:01:58 +03:30
|
|
|
refreshSession,
|
2026-04-29 14:02:42 +03:30
|
|
|
clearError,
|
|
|
|
|
}),
|
|
|
|
|
[
|
|
|
|
|
user,
|
|
|
|
|
organizations,
|
|
|
|
|
currentOrganization,
|
|
|
|
|
isLoading,
|
|
|
|
|
isAuthReady,
|
2026-07-12 18:27:38 +03:30
|
|
|
apiError,
|
2026-04-29 14:02:42 +03:30
|
|
|
registerTrial,
|
|
|
|
|
login,
|
|
|
|
|
logout,
|
|
|
|
|
selectOrganization,
|
2026-04-29 20:19:40 +03:30
|
|
|
createOrganization,
|
2026-06-20 12:37:38 +03:30
|
|
|
setUserLanguage,
|
2026-07-04 00:01:58 +03:30
|
|
|
refreshSession,
|
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;
|
|
|
|
|
};
|