/** * Receptor del relay token del Hub. * Maneja dos flujos: * - SSO entre productos: Hub redirige a /auth/sso?relay= * - Login con Microsoft: Hub redirige al mismo endpoint tras OAuth */ import { useEffect, useState } from 'react'; const API_URL = import.meta.env.VITE_EFC_API_URL; export default function SSOCallback() { const [error, setError] = useState(null); useEffect(() => { const params = new URLSearchParams(window.location.search); const relay = params.get('relay'); if (!relay) { setError('No se recibió relay token. Acceso denegado.'); return; } (async () => { try { const res = await fetch(`${API_URL}/auth/sso/exchange/`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, credentials: 'include', body: JSON.stringify({ relay_token: relay }), }); if (!res.ok) { const body = await res.json().catch(() => ({})); throw new Error(body.detail || 'Error al iniciar sesión SSO'); } const data = await res.json(); // Guardar tokens en localStorage para fetchWithAuth if (data.access_token) { localStorage.setItem('access', data.access_token); } if (data.refresh_token) { localStorage.setItem('refresh', data.refresh_token); } // Sincronizar datos de usuario const apiUrl = import.meta.env.VITE_EFC_API_URL || ''; try { const [resUser, resPerms] = await Promise.all([ fetch(`${apiUrl}/user/users/me/`, { headers: { Authorization: `Bearer ${data.access_token}` }, credentials: 'include' }), fetch(`${apiUrl}/rbac/my-permissions/`, { headers: { Authorization: `Bearer ${data.access_token}` }, credentials: 'include' }), ]); if (resUser.ok) { const user = await resUser.json(); if (user?.username) { localStorage.setItem('username', user.username); if (user.email) localStorage.setItem('user_email', user.email); if (user.id) localStorage.setItem('user_id', String(user.id)); if (user.first_name) localStorage.setItem('user_first_name', user.first_name); if (user.last_name) localStorage.setItem('user_last_name', user.last_name); if (typeof user.is_importador !== 'undefined') localStorage.setItem('user_is_importador', String(user.is_importador)); } } if (resPerms.ok) { const permsData = await resPerms.json(); if (permsData?.permissions) localStorage.setItem('user_permissions', JSON.stringify(permsData.permissions)); } } catch (_) {} window.dispatchEvent(new CustomEvent('authStateChanged')); window.location.href = '/admin'; } catch (err) { setError(err.message || 'Error al iniciar sesión vía workspace'); } })(); }, []); if (error) { return (

Error de inicio de sesión

{error}

Volver al login
); } return (

Iniciando sesión…

); }