omnichannel-frontend/src/modules/auth/hooks/useLogin.js
Rafael Lopes eb6e4faf2c FEAT: Integrada autenticação segura no frontend
- Token passa de localStorage para sessionStorage
- Removido fallback de perfis demo
- Fetch passa a enviar Bearer Token automaticamente
- Socket.IO do WhatsApp envia token no handshake
- Login Microsoft lê payload por fragmento #auth e limpa a URL
- Acesso a /home sem autenticação redireciona para /login
- Rotas protegidas com componente ProtectedRoute
2026-05-29 12:27:37 -03:00

84 lines
2.4 KiB
JavaScript

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