55 lines
1.2 KiB
TypeScript
55 lines
1.2 KiB
TypeScript
import { useState, useEffect } from 'react';
|
|
import { authService, type AuthStatus } from '@/lib/services/auth';
|
|
|
|
export const useAuth = () => {
|
|
const [authStatus, setAuthStatus] = useState<AuthStatus>({
|
|
isAuthenticated: false,
|
|
});
|
|
const [isLoading, setIsLoading] = useState(true);
|
|
const [error, setError] = useState<string | null>(null);
|
|
|
|
const checkAuth = async () => {
|
|
try {
|
|
setIsLoading(true);
|
|
setError(null);
|
|
const status = await authService.checkAuthStatus();
|
|
setAuthStatus(status);
|
|
} catch (err) {
|
|
setError('Erreur lors de la vérification de l\'authentification');
|
|
console.error('Auth check error:', err);
|
|
} finally {
|
|
setIsLoading(false);
|
|
}
|
|
};
|
|
|
|
useEffect(() => {
|
|
checkAuth();
|
|
}, []);
|
|
|
|
const login = () => {
|
|
authService.login();
|
|
};
|
|
|
|
const logout = async () => {
|
|
try {
|
|
await authService.logout();
|
|
setAuthStatus({ isAuthenticated: false });
|
|
} catch (err) {
|
|
setError('Erreur lors de la déconnexion');
|
|
console.error('Logout error:', err);
|
|
}
|
|
};
|
|
|
|
const refreshAuth = () => {
|
|
checkAuth();
|
|
};
|
|
|
|
return {
|
|
...authStatus,
|
|
isLoading,
|
|
error,
|
|
login,
|
|
logout,
|
|
refreshAuth,
|
|
};
|
|
}; |