página de login
This commit is contained in:
111
frontend/utils/AuthContext.tsx
Normal file
111
frontend/utils/AuthContext.tsx
Normal 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;
|
||||
}
|
||||
@@ -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
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user