omnichannel-frontend/src/modules/auth/hooks/useLogin.js

62 lines
1.6 KiB
JavaScript
Raw Normal View History

import { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import {
getAuthConfig,
loginWithAd,
startMicrosoftLogin,
storeAuthSession,
} from '../services/authService';
export function useLogin() {
const navigate = useNavigate();
const [isSubmitting, setIsSubmitting] = useState(false);
const [error, setError] = useState('');
const [providers, setProviders] = useState({ ldap: true, microsoft: false });
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 {
setError('Não foi possível concluir o login Microsoft.');
}
}, [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,
};
}