import { useState, useEffect, useRef } from 'react'; import { Link, useNavigate, useSearchParams } from 'react-router-dom'; import { useAuth } from '../context/AuthContext'; import { authService } from '../services/authService'; import { FiEye, FiEyeOff } from 'react-icons/fi'; export default function Login() { const [email, setEmail] = useState(''); const [password, setPassword] = useState(''); const [showPassword, setShowPassword] = useState(false); const [error, setError] = useState(''); const navigate = useNavigate(); const { login } = useAuth(); const [searchParams] = useSearchParams(); const googleLoginProcessed = useRef(false); useEffect(() => { const token = searchParams.get('token'); if (token && !googleLoginProcessed.current) { googleLoginProcessed.current = true; const url = new URL(window.location); url.searchParams.delete('token'); window.history.replaceState({}, '', url); try { const base64Url = token.split('.')[1]; const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/'); const jsonPayload = decodeURIComponent(window.atob(base64).split('').map(function(c) { return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2); }).join('')); const decodedToken = JSON.parse(jsonPayload); const googleUser = { _id: decodedToken.sub || decodedToken.user_id || "google_id", username: decodedToken.email ? decodedToken.email.split('@')[0] : "Usuario Google", email: decodedToken.email || "" }; login({ user: googleUser, access_token: token }); navigate('/', { replace: true }); } catch (err) { console.error("Error al decodificar el token de Google:", err); setTimeout(() => { setError("Error al procesar el login con Google. El token está corrupto."); }, 0); } } }, [searchParams, login, navigate]); const handleSubmit = async (e) => { e.preventDefault(); setError(''); try { const data = await authService.login(email, password); login(data); navigate('/'); } catch (err) { setError('Credenciales incorrectas.'); } }; const handleGoogleLogin = () => { window.location.href = "http://localhost:8000/api/auth/google/login"; }; return (
Accede a tu historial y gráficas guardadas
¿Nuevo por aquí? Crea una cuenta