107 lines
2.8 KiB
TypeScript
107 lines
2.8 KiB
TypeScript
/**
|
|
* Authentication hooks: login, logout, current user, password reset, tenant switching.
|
|
*/
|
|
|
|
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
|
|
import { apiPost, apiGet, setCsrfToken } from './client';
|
|
import { useAuthStore } from '@/store/authStore';
|
|
|
|
export interface LoginPayload {
|
|
email: string;
|
|
password: string;
|
|
}
|
|
|
|
export interface PasswordResetRequestPayload {
|
|
email: string;
|
|
}
|
|
|
|
export interface PasswordResetConfirmPayload {
|
|
token: string;
|
|
password: string;
|
|
}
|
|
|
|
export function useLogin() {
|
|
const { setUser, setError } = useAuthStore();
|
|
return useMutation({
|
|
mutationFn: (payload: LoginPayload) =>
|
|
apiPost('/auth/login', payload),
|
|
onSuccess: (data: any) => {
|
|
// Map flat login response to User interface
|
|
const user = data.user || {
|
|
id: data.user_id,
|
|
email: data.email,
|
|
first_name: data.name?.split(' ')[0] || '',
|
|
last_name: data.name?.split(' ').slice(1).join(' ') || '',
|
|
role: data.role,
|
|
is_system_admin: data.is_system_admin,
|
|
tenants: [{ id: data.tenant_id, name: data.tenant_name, slug: '' }],
|
|
avatar_url: null,
|
|
};
|
|
setUser(user);
|
|
setError(null);
|
|
// Store CSRF token for subsequent unsafe requests
|
|
if (data.csrf_token) {
|
|
setCsrfToken(data.csrf_token);
|
|
}
|
|
},
|
|
onError: (error: any) => {
|
|
setError(error.message || 'Login failed');
|
|
},
|
|
});
|
|
}
|
|
|
|
export function useLogout() {
|
|
const { logout } = useAuthStore();
|
|
const queryClient = useQueryClient();
|
|
return useMutation({
|
|
mutationFn: () => apiPost('/auth/logout'),
|
|
onSettled: () => {
|
|
logout();
|
|
setCsrfToken(null);
|
|
queryClient.clear();
|
|
},
|
|
});
|
|
}
|
|
|
|
export function useCurrentUser() {
|
|
const { setUser, setAuthenticated } = useAuthStore();
|
|
return useQuery({
|
|
queryKey: ['currentUser'],
|
|
queryFn: async () => {
|
|
const data = await apiGet<any>('/auth/me');
|
|
setUser(data.user || data);
|
|
setAuthenticated(true);
|
|
return data;
|
|
},
|
|
retry: false,
|
|
staleTime: 5 * 60 * 1000,
|
|
});
|
|
}
|
|
|
|
export function usePasswordResetRequest() {
|
|
return useMutation({
|
|
mutationFn: (payload: PasswordResetRequestPayload) =>
|
|
apiPost('/auth/password-reset/request', payload),
|
|
});
|
|
}
|
|
|
|
export function usePasswordResetConfirm() {
|
|
return useMutation({
|
|
mutationFn: (payload: PasswordResetConfirmPayload) =>
|
|
apiPost('/auth/password-reset/confirm', payload),
|
|
});
|
|
}
|
|
|
|
export function useSwitchTenant() {
|
|
const { setTenant } = useAuthStore();
|
|
const queryClient = useQueryClient();
|
|
return useMutation({
|
|
mutationFn: (tenantId: string) =>
|
|
apiPost('/auth/switch-tenant', { tenant_id: tenantId }),
|
|
onSuccess: (data: any) => {
|
|
setTenant(data.tenant || data);
|
|
queryClient.invalidateQueries();
|
|
},
|
|
});
|
|
}
|