import { useEffect, useState } from 'react'; import { useNavigate } from 'react-router-dom'; import { getAuthConfig, loginWithAd, startMicrosoftLogin, storeAuthSession, } from '../services/authService'; import { isAuthenticated } from '../services/sessionService'; function decodeAuthPayload(payload) { const base64 = payload.replace(/-/g, '+').replace(/_/g, '/'); const paddedBase64 = base64.padEnd(base64.length + ((4 - (base64.length % 4)) % 4), '='); return JSON.parse(atob(paddedBase64)); } export function useLogin() { const navigate = useNavigate(); const [isSubmitting, setIsSubmitting] = useState(false); const [error, setError] = useState(''); const [providers, setProviders] = useState({ ldap: true, microsoft: false }); useEffect(() => { if (!window.location.hash.includes('auth=') && isAuthenticated()) { navigate('/home', { replace: true }); return; } getAuthConfig() .then((config) => setProviders(config.providers || { ldap: true, microsoft: false })) .catch(() => setProviders({ ldap: true, microsoft: false })); }, [navigate]); useEffect(() => { const hashParams = new URLSearchParams(window.location.hash.replace(/^#/, '')); const authPayload = hashParams.get('auth'); if (authPayload) { try { storeAuthSession(decodeAuthPayload(authPayload)); window.history.replaceState({}, document.title, window.location.pathname); navigate('/home', { replace: true }); return; } catch { window.history.replaceState({}, document.title, window.location.pathname); setError('Nao foi possivel concluir o login Microsoft.'); } } if (window.location.search.includes('token=') || window.location.search.includes('user=')) { window.history.replaceState({}, document.title, window.location.pathname); setError('Fluxo de login expirado. Tente novamente.'); } }, [navigate]); async function login(credentials) { setIsSubmitting(true); setError(''); try { const authResult = await loginWithAd(credentials); storeAuthSession(authResult); navigate('/home'); } catch (loginError) { setError(loginError.message || 'Falha ao autenticar.'); } finally { setIsSubmitting(false); } } return { isSubmitting, error, providers, login, startMicrosoftLogin, }; }