página de login

This commit is contained in:
igferne
2026-01-07 13:03:10 +01:00
parent d7fcf2b416
commit e4f985e6aa
8 changed files with 333 additions and 26 deletions

View File

@@ -0,0 +1,26 @@
# beyond_api/api/auth.py
from __future__ import annotations
from fastapi import APIRouter, Depends
from fastapi.responses import JSONResponse
from beyond_api.security import get_current_user
router = APIRouter(
prefix="/auth",
tags=["auth"],
)
@router.get("/check")
def check_auth(current_user: str = Depends(get_current_user)):
"""
Endpoint muy simple: si las credenciales Basic son correctas,
devuelve 200 con el usuario. Si no, get_current_user lanza 401.
"""
return JSONResponse(
content={
"user": current_user,
"status": "ok",
}
)

View File

@@ -2,9 +2,9 @@ import logging
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
# importa tus routers
from beyond_api.api.analysis import router as analysis_router
from beyond_api.api.auth import router as auth_router # 👈 nuevo
def setup_basic_logging() -> None:
logging.basicConfig(
@@ -29,4 +29,5 @@ app.add_middleware(
allow_headers=["*"],
)
app.include_router(analysis_router)
app.include_router(analysis_router)
app.include_router(auth_router) # 👈 registrar el router de auth

View File

@@ -1,12 +1,32 @@
// App.tsx
import React from 'react';
import { Toaster } from 'react-hot-toast';
import SinglePageDataRequestIntegrated from './components/SinglePageDataRequestIntegrated';
import { AuthProvider, useAuth } from './utils/AuthContext';
import LoginPage from './components/LoginPage';
const AppContent: React.FC = () => {
const { isAuthenticated } = useAuth();
return (
<>
{isAuthenticated ? (
<SinglePageDataRequestIntegrated />
) : (
<LoginPage />
)}
</>
);
};
const App: React.FC = () => {
return (
<main className="min-h-screen">
<SinglePageDataRequestIntegrated />
</main>
<AuthProvider>
<Toaster position="top-right" />
<AppContent />
</AuthProvider>
);
};
export default App;

View File

@@ -0,0 +1,109 @@
// components/LoginPage.tsx
import React, { useState } from 'react';
import { motion } from 'framer-motion';
import { Lock, User } from 'lucide-react';
import toast from 'react-hot-toast';
import { useAuth } from '../utils/AuthContext';
const LoginPage: React.FC = () => {
const { login } = useAuth();
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
const [isSubmitting, setIsSubmitting] = useState(false);
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
if (!username || !password) {
toast.error('Introduce usuario y contraseña');
return;
}
setIsSubmitting(true);
try {
await login(username, password);
toast.success('Sesión iniciada');
} catch (err) {
console.error('Error en login', err);
const msg =
err instanceof Error ? err.message : 'Error al iniciar sesión';
toast.error(msg);
} finally {
setIsSubmitting(false);
}
};
return (
<div className="min-h-screen bg-gradient-to-br from-indigo-500 via-sky-500 to-slate-900 flex items-center justify-center px-4">
<motion.div
initial={{ opacity: 0, y: 24 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.5 }}
className="w-full max-w-md bg-white/95 rounded-3xl shadow-2xl p-8 space-y-6"
>
<div className="space-y-2 text-center">
<div className="inline-flex items-center justify-center w-12 h-12 rounded-2xl bg-indigo-100 text-indigo-600 mb-1">
<Lock className="w-6 h-6" />
</div>
<h1 className="text-2xl font-semibold text-slate-900">
Beyond Diagnostic
</h1>
<p className="text-sm text-slate-500">
Inicia sesión para acceder al análisis
</p>
</div>
<form onSubmit={handleSubmit} className="space-y-4">
<div className="space-y-1">
<label className="block text-sm font-medium text-slate-700">
Usuario
</label>
<div className="relative">
<span className="absolute inset-y-0 left-0 pl-3 flex items-center text-slate-400">
<User className="w-4 h-4" />
</span>
<input
type="text"
autoComplete="username"
className="block w-full rounded-2xl border border-slate-200 pl-9 pr-3 py-2 text-sm shadow-sm focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:border-transparent"
value={username}
onChange={(e) => setUsername(e.target.value)}
/>
</div>
</div>
<div className="space-y-1">
<label className="block text-sm font-medium text-slate-700">
Contraseña
</label>
<div className="relative">
<span className="absolute inset-y-0 left-0 pl-3 flex items-center text-slate-400">
<Lock className="w-4 h-4" />
</span>
<input
type="password"
autoComplete="current-password"
className="block w-full rounded-2xl border border-slate-200 pl-9 pr-3 py-2 text-sm shadow-sm focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:border-transparent"
value={password}
onChange={(e) => setPassword(e.target.value)}
/>
</div>
</div>
<button
type="submit"
disabled={isSubmitting}
className="w-full inline-flex items-center justify-center rounded-2xl bg-indigo-600 text-white text-sm font-medium py-2.5 shadow-sm hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 disabled:opacity-60 disabled:cursor-not-allowed"
>
{isSubmitting ? 'Entrando…' : 'Entrar'}
</button>
<p className="text-[11px] text-slate-400 text-center mt-2">
La sesión permanecerá activa durante 1 hora.
</p>
</form>
</motion.div>
</div>
);
};
export default LoginPage;

View File

@@ -10,6 +10,7 @@ import DataInputRedesigned from './DataInputRedesigned';
import DashboardReorganized from './DashboardReorganized';
import { generateAnalysis } from '../utils/analysisGenerator';
import toast from 'react-hot-toast';
import { useAuth } from '../utils/AuthContext';
const SinglePageDataRequestIntegrated: React.FC = () => {
const [selectedTier, setSelectedTier] = useState<TierKey>('silver');
@@ -21,6 +22,9 @@ const SinglePageDataRequestIntegrated: React.FC = () => {
setSelectedTier(tier);
};
const { authHeader, logout } = useAuth();
const handleAnalyze = (config: {
costPerHour: number;
avgCsat: number;
@@ -44,6 +48,12 @@ const SinglePageDataRequestIntegrated: React.FC = () => {
toast.error('Por favor, sube un archivo, introduce una URL o genera datos sintéticos.');
return;
}
// 🔐 Si usamos CSV real, exigir estar logado
if (config.file && !config.useSynthetic && !authHeader) {
toast.error('Debes iniciar sesión para analizar datos reales.');
return;
}
setIsAnalyzing(true);
toast.loading('Generando análisis...', { id: 'analyzing' });
@@ -58,7 +68,8 @@ const SinglePageDataRequestIntegrated: React.FC = () => {
config.segmentMapping,
config.file,
config.sheetUrl,
config.useSynthetic
config.useSynthetic,
authHeader || undefined
);
console.log('✅ Analysis generated successfully');
@@ -74,7 +85,15 @@ const SinglePageDataRequestIntegrated: React.FC = () => {
console.error('❌ Error generating analysis:', error);
setIsAnalyzing(false);
toast.dismiss('analyzing');
toast.error('Error al generar el análisis: ' + (error as Error).message);
const msg = (error as Error).message || '';
if (msg.includes('401')) {
toast.error('Sesión caducada o credenciales incorrectas. Vuelve a iniciar sesión.');
logout();
} else {
toast.error('Error al generar el análisis: ' + msg);
}
}
}, 1500);
};
@@ -131,6 +150,12 @@ const SinglePageDataRequestIntegrated: React.FC = () => {
<p className="text-lg text-slate-600">
Análisis de Readiness Agéntico para Contact Centers
</p>
<button
onClick={logout}
className="text-xs text-slate-500 hover:text-slate-800 underline mt-1"
>
Cerrar sesión
</button>
</motion.div>
{/* Tier Selection */}

View File

@@ -0,0 +1,111 @@
// utils/AuthContext.tsx
import React, { createContext, useContext, useEffect, useState } from 'react';
const API_BASE_URL =
import.meta.env.VITE_API_BASE_URL || 'http://localhost:8000';
type AuthContextValue = {
authHeader: string | null;
isAuthenticated: boolean;
login: (username: string, password: string) => Promise<void>; // 👈 async
logout: () => void;
};
const AuthContext = createContext<AuthContextValue | undefined>(undefined);
const STORAGE_KEY = 'bd_auth_v1';
const SESSION_DURATION_MS = 60 * 60 * 1000; // 1 hora
type StoredAuth = {
authHeader: string;
expiresAt: number;
};
export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
const [authHeader, setAuthHeader] = useState<string | null>(null);
const [expiresAt, setExpiresAt] = useState<number | null>(null);
useEffect(() => {
try {
const raw = window.localStorage.getItem(STORAGE_KEY);
if (!raw) return;
const parsed: StoredAuth = JSON.parse(raw);
if (parsed.authHeader && parsed.expiresAt && parsed.expiresAt > Date.now()) {
setAuthHeader(parsed.authHeader);
setExpiresAt(parsed.expiresAt);
} else {
window.localStorage.removeItem(STORAGE_KEY);
}
} catch (err) {
console.error('Error leyendo auth de localStorage', err);
}
}, []);
const logout = () => {
setAuthHeader(null);
setExpiresAt(null);
try {
window.localStorage.removeItem(STORAGE_KEY);
} catch {
/* no-op */
}
};
const login = async (username: string, password: string): Promise<void> => {
const basic = 'Basic ' + btoa(`${username}:${password}`);
// 1) Validar contra /auth/check
let resp: Response;
try {
resp = await fetch(`${API_BASE_URL}/auth/check`, {
method: 'GET',
headers: {
Authorization: basic,
},
});
} catch (err) {
console.error('Error llamando a /auth/check', err);
throw new Error('No se ha podido contactar con el servidor.');
}
if (resp.status === 401) {
throw new Error('Credenciales inválidas');
}
if (!resp.ok) {
throw new Error(`No se ha podido validar las credenciales (status ${resp.status}).`);
}
// 2) Si hemos llegado aquí, las credenciales son válidas -> guardamos sesión
const exp = Date.now() + SESSION_DURATION_MS;
setAuthHeader(basic);
setExpiresAt(exp);
try {
const toStore: StoredAuth = { authHeader: basic, expiresAt: exp };
window.localStorage.setItem(STORAGE_KEY, JSON.stringify(toStore));
} catch (err) {
console.error('Error guardando auth en localStorage', err);
}
};
const isAuthenticated = !!authHeader && !!expiresAt && expiresAt > Date.now();
const value: AuthContextValue = {
authHeader: isAuthenticated ? authHeader : null,
isAuthenticated,
login,
logout,
};
return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;
};
export function useAuth(): AuthContextValue {
const ctx = useContext(AuthContext);
if (!ctx) {
throw new Error('useAuth debe usarse dentro de un AuthProvider');
}
return ctx;
}

View File

@@ -905,7 +905,8 @@ export const generateAnalysis = async (
segmentMapping?: { high_value_queues: string[]; medium_value_queues: string[]; low_value_queues: string[] },
file?: File,
sheetUrl?: string,
useSynthetic?: boolean
useSynthetic?: boolean,
authHeaderOverride?: string
): Promise<AnalysisData> => {
// Si hay archivo, procesarlo
// Si hay archivo, primero intentamos usar el backend
@@ -920,6 +921,7 @@ export const generateAnalysis = async (
avgCsat,
segmentMapping,
file,
authHeaderOverride,
});
const mapped = mapBackendResultsToAnalysisData(raw, tier);
@@ -952,7 +954,18 @@ export const generateAnalysis = async (
return mapped;
} catch (apiError) {
} catch (apiError: any) {
const status = apiError?.status;
const msg = (apiError as Error).message || '';
// 🔐 Si es un error de autenticación (401), NO hacemos fallback
if (status === 401 || msg.includes('401')) {
console.error(
'❌ Error de autenticación en backend, abortando análisis (sin fallback).'
);
throw apiError;
}
console.error(
'❌ Backend /analysis no disponible o mapeo incompleto, fallback a lógica local:',
apiError

View File

@@ -36,8 +36,9 @@ export async function callAnalysisApiRaw(params: {
avgCsat: number;
segmentMapping?: SegmentMapping;
file: File;
authHeaderOverride?: string;
}): Promise<BackendRawResults> {
const { costPerHour, segmentMapping, file } = params;
const { costPerHour, segmentMapping, file, authHeaderOverride } = params;
if (!file) {
throw new Error('No se ha proporcionado ningún archivo CSV');
@@ -73,31 +74,32 @@ export async function callAnalysisApiRaw(params: {
formData.append('economy_json', JSON.stringify(economyData));
}
// Si nos pasan un Authorization desde el login, lo usamos.
// Si no, caemos al getAuthHeader() basado en variables de entorno (útil en dev).
const authHeaders: Record<string, string> = authHeaderOverride
? { Authorization: authHeaderOverride }
: getAuthHeader();
const response = await fetch(`${API_BASE_URL}/analysis`, {
method: 'POST',
body: formData,
headers: {
...getAuthHeader(),
...authHeaders,
},
});
if (!response.ok) {
let errorText = `Error API (${response.status})`;
try {
const errorBody = await response.json();
if (errorBody?.detail) {
errorText = String(errorBody.detail);
}
} catch {
// ignoramos si no es JSON
}
throw new Error(errorText);
const error = new Error(
`Error en API /analysis: ${response.status} ${response.statusText}`
);
(error as any).status = response.status;
throw error;
}
const data = await response.json();
const rawResults = data.results ?? data;
// ⬇️ IMPORTANTE: nos quedamos solo con `results`
const json = await response.json();
const results = (json as any)?.results ?? json;
console.debug('🔍 Backend /analysis raw results:', rawResults);
return rawResults;
return results as BackendRawResults;
}