2026-05-18 19:11:01 -03:00
|
|
|
import { useEffect, useState } from 'react';
|
2026-03-19 18:22:18 -03:00
|
|
|
import { useNavigate } from 'react-router-dom';
|
2026-05-18 19:11:01 -03:00
|
|
|
import {
|
|
|
|
|
getAuthConfig,
|
|
|
|
|
loginWithAd,
|
|
|
|
|
startMicrosoftLogin,
|
|
|
|
|
storeAuthSession,
|
|
|
|
|
} from '../services/authService';
|
2026-03-19 18:22:18 -03:00
|
|
|
|
|
|
|
|
export function useLogin() {
|
|
|
|
|
const navigate = useNavigate();
|
|
|
|
|
const [isSubmitting, setIsSubmitting] = useState(false);
|
2026-05-18 19:11:01 -03:00
|
|
|
const [error, setError] = useState('');
|
|
|
|
|
const [providers, setProviders] = useState({ ldap: true, microsoft: false });
|
2026-03-19 18:22:18 -03:00
|
|
|
|
2026-05-18 19:11:01 -03:00
|
|
|
useEffect(() => {
|
|
|
|
|
getAuthConfig()
|
|
|
|
|
.then((config) => setProviders(config.providers || { ldap: true, microsoft: false }))
|
|
|
|
|
.catch(() => setProviders({ ldap: true, microsoft: false }));
|
|
|
|
|
}, []);
|
|
|
|
|
|
|
|
|
|
useEffect(() => {
|
|
|
|
|
const params = new URLSearchParams(window.location.search);
|
|
|
|
|
const token = params.get('token');
|
|
|
|
|
const rawUser = params.get('user');
|
|
|
|
|
|
|
|
|
|
if (!token || !rawUser) return;
|
|
|
|
|
|
|
|
|
|
try {
|
|
|
|
|
const user = JSON.parse(rawUser);
|
|
|
|
|
storeAuthSession({ token, user });
|
|
|
|
|
window.history.replaceState({}, document.title, window.location.pathname);
|
|
|
|
|
navigate('/home', { replace: true });
|
|
|
|
|
} catch {
|
2026-05-21 15:50:55 -03:00
|
|
|
setError('Não foi possível concluir o login Microsoft.');
|
2026-05-18 19:11:01 -03:00
|
|
|
}
|
|
|
|
|
}, [navigate]);
|
|
|
|
|
|
|
|
|
|
async function login(credentials) {
|
2026-03-19 18:22:18 -03:00
|
|
|
setIsSubmitting(true);
|
2026-05-18 19:11:01 -03:00
|
|
|
setError('');
|
2026-03-19 18:22:18 -03:00
|
|
|
|
|
|
|
|
try {
|
2026-05-18 19:11:01 -03:00
|
|
|
const authResult = await loginWithAd(credentials);
|
|
|
|
|
storeAuthSession(authResult);
|
2026-03-19 18:22:18 -03:00
|
|
|
navigate('/home');
|
2026-05-18 19:11:01 -03:00
|
|
|
} catch (loginError) {
|
|
|
|
|
setError(loginError.message || 'Falha ao autenticar.');
|
2026-03-19 18:22:18 -03:00
|
|
|
} finally {
|
|
|
|
|
setIsSubmitting(false);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return {
|
|
|
|
|
isSubmitting,
|
2026-05-18 19:11:01 -03:00
|
|
|
error,
|
|
|
|
|
providers,
|
2026-03-19 18:22:18 -03:00
|
|
|
login,
|
2026-05-18 19:11:01 -03:00
|
|
|
startMicrosoftLogin,
|
2026-03-19 18:22:18 -03:00
|
|
|
};
|
|
|
|
|
}
|