-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprueba_api.html
More file actions
651 lines (592 loc) · 26.6 KB
/
Copy pathprueba_api.html
File metadata and controls
651 lines (592 loc) · 26.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>🧪 Prueba de API Keys - Sistema Genérico</title>
<link rel="stylesheet" href="static/css/styles.css">
<style>
.test-container {
max-width: 1200px;
margin: 0 auto;
padding: 20px;
}
.test-section {
background: var(--bg-white);
border: 1px solid var(--border-color);
border-radius: 8px;
padding: 20px;
margin-bottom: 20px;
}
.dark-mode .test-section {
background: var(--bg-dark-secondary);
border-color: var(--border-dark);
}
.provider-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
gap: 20px;
margin-top: 20px;
}
.provider-card {
border: 1px solid var(--border-color);
border-radius: 8px;
padding: 15px;
background: var(--bg-white);
}
.dark-mode .provider-card {
background: var(--bg-dark-secondary);
border-color: var(--border-dark);
}
.provider-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 15px;
}
.provider-name {
font-weight: 600;
font-size: 1.1rem;
}
.provider-type {
background: var(--primary-color);
color: white;
padding: 4px 8px;
border-radius: 4px;
font-size: 0.8rem;
}
.test-form {
display: flex;
gap: 10px;
align-items: end;
}
.form-group {
flex: 1;
}
.form-label {
display: block;
margin-bottom: 5px;
font-weight: 500;
}
.form-input, .form-select {
width: 100%;
padding: 8px 12px;
border: 1px solid var(--border-color);
border-radius: 4px;
background: var(--bg-white);
color: var(--text-primary);
}
.dark-mode .form-input,
.dark-mode .form-select {
background: var(--bg-dark);
border-color: var(--border-dark);
color: var(--text-dark-primary);
}
.btn-test {
background: var(--success-color);
color: white;
border: none;
padding: 8px 16px;
border-radius: 4px;
cursor: pointer;
font-weight: 500;
}
.btn-test:hover {
opacity: 0.9;
}
.btn-test:disabled {
background: var(--gray-color);
cursor: not-allowed;
}
.result-section {
margin-top: 20px;
padding: 15px;
border-radius: 8px;
display: none;
}
.result-success {
background: #dcfce7;
border: 1px solid #bbf7d0;
color: #166534;
}
.dark-mode .result-success {
background: #064e3b;
border-color: #065f46;
color: #10b981;
}
.result-error {
background: #fee2e2;
border: 1px solid #fecaca;
color: #991b1b;
}
.dark-mode .result-error {
background: #7f1d1d;
border-color: #991b1b;
color: #ef4444;
}
.result-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 10px;
}
.result-status {
font-weight: 600;
}
.result-duration {
font-size: 0.9rem;
opacity: 0.8;
}
.result-details {
font-family: monospace;
font-size: 0.9rem;
background: rgba(0,0,0,0.1);
padding: 10px;
border-radius: 4px;
margin-top: 10px;
white-space: pre-wrap;
max-height: 200px;
overflow-y: auto;
}
.dark-mode .result-details {
background: rgba(255,255,255,0.1);
}
.logs-section {
background: #c3cedd;
color: #f9fafb;
padding: 15px;
border-radius: 8px;
font-family: monospace;
font-size: 0.9rem;
max-height: 400px;
overflow-y: auto;
margin-top: 20px;
}
.log-entry {
margin-bottom: 5px;
padding: 2px 0;
}
.log-timestamp {
color: #9ca3af;
}
.log-level-info { color: #60a5fa; }
.log-level-error { color: #f87171; }
.log-level-success { color: #34d399; }
</style>
</head>
<body>
<div class="test-container">
<!-- Header -->
<div class="test-section">
<h1>🧪 Prueba de API Keys - Sistema Genérico</h1>
<p>Esta página permite probar el sistema genérico de prueba de API keys usando configuración declarativa desde la base de datos.</p>
<div class="test-form">
<div class="form-group">
<label class="form-label">Tipo de Proveedor:</label>
<select id="provider-type" class="form-select">
<option value="data">Datos Financieros</option>
<option value="ai">IA</option>
<option value="news">Noticias</option>
<option value="trade">Trade</option>
</select>
</div>
<button id="load-providers" class="btn-test">Cargar Proveedores</button>
<button id="refresh-token" class="btn-test" style="background: var(--warning-color);">🔄 Refrescar Token</button>
</div>
</div>
<!-- Proveedores -->
<div class="test-section">
<h2>📋 Proveedores Disponibles</h2>
<div id="providers-container">
<p>Carga los proveedores seleccionando un tipo y haciendo clic en "Cargar Proveedores".</p>
</div>
</div>
<!-- Logs -->
<div class="test-section">
<h2>📊 Logs de Debug</h2>
<div id="logs-container" class="logs-section">
<div class="log-entry">
<span class="log-timestamp">[Sistema]</span>
<span class="log-level-info">Página cargada. Listo para pruebas.</span>
</div>
</div>
<button id="clear-logs" class="btn-test" style="margin-top: 10px; background: var(--gray-color);">Limpiar Logs</button>
</div>
</div>
<script>
// Variables globales
let currentProviders = [];
let logs = [];
// Función para agregar logs
function addLog(level, message, data = null) {
const timestamp = new Date().toLocaleTimeString();
const logEntry = {
timestamp,
level,
message,
data
};
logs.push(logEntry);
const logsContainer = document.getElementById('logs-container');
const logDiv = document.createElement('div');
logDiv.className = `log-entry`;
logDiv.innerHTML = `
<span class="log-timestamp">[${timestamp}]</span>
<span class="log-level-${level}">${message}</span>
`;
if (data) {
const dataDiv = document.createElement('div');
dataDiv.className = 'log-entry';
dataDiv.style.marginLeft = '20px';
dataDiv.style.color = '#9ca3af';
dataDiv.textContent = JSON.stringify(data, null, 2);
logDiv.appendChild(dataDiv);
}
logsContainer.appendChild(logDiv);
logsContainer.scrollTop = logsContainer.scrollHeight;
// Mantener solo los últimos 50 logs
if (logs.length > 50) {
logs.shift();
const firstLog = logsContainer.querySelector('.log-entry');
if (firstLog) firstLog.remove();
}
}
// Función para limpiar logs
function clearLogs() {
logs = [];
document.getElementById('logs-container').innerHTML = `
<div class="log-entry">
<span class="log-timestamp">[Sistema]</span>
<span class="log-level-info">Logs limpiados.</span>
</div>
`;
}
// Función para cargar proveedores CON CLAVES del usuario
async function loadProviders() {
const providerType = document.getElementById('provider-type').value;
addLog('info', `Cargando proveedores CON CLAVES de tipo: ${providerType}`);
try {
const response = await api('get_user_providers_with_keys_safe.php', {
method: 'POST',
body: {
provider_type: providerType
}
});
addLog('info', 'Respuesta de proveedores con claves recibida', response);
if (response.ok && response.providers) {
currentProviders = response.providers;
renderProviders();
addLog('success', `Cargados ${currentProviders.length} proveedores CON CLAVES configuradas`);
if (currentProviders.length === 0) {
addLog('warning', 'No tienes claves configuradas para este tipo de proveedor. Ve a la página de configuración para agregar claves.');
}
} else {
addLog('error', 'Error cargando proveedores con claves', response);
}
} catch (error) {
addLog('error', 'Error en petición de proveedores con claves', error);
}
}
// Función para renderizar proveedores CON CLAVES
function renderProviders() {
const container = document.getElementById('providers-container');
if (currentProviders.length === 0) {
container.innerHTML = `
<div style="background: #fef3c7; border: 1px solid #fde68a; color: #92400e; padding: 15px; border-radius: 8px;">
<h3>🔑 Sin Claves Configuradas</h3>
<p>No tienes claves API configuradas para este tipo de proveedor.</p>
<p><strong>Para probar:</strong></p>
<ol>
<li>Ve a la página de <strong>Configuración</strong></li>
<li>Agrega claves API para los proveedores que quieras probar</li>
<li>Regresa a esta página de prueba</li>
</ol>
</div>
`;
return;
}
const grid = document.createElement('div');
grid.className = 'provider-grid';
currentProviders.forEach(provider => {
const card = document.createElement('div');
card.className = 'provider-card';
const config = JSON.parse(provider.config_json || '{}');
const hasTestConfig = config.test && Object.keys(config.test).length > 0;
card.innerHTML = `
<div class="provider-header">
<div>
<div class="provider-name">${provider.name}</div>
<div style="font-size: 0.9rem; color: var(--text-secondary); margin-top: 4px;">
${provider.slug} • ${provider.category || 'N/A'} • ${provider.environment || 'live'}
</div>
</div>
<div class="provider-type">${document.getElementById('provider-type').value}</div>
</div>
<div style="margin-bottom: 15px;">
<div style="background: #dcfce7; border: 1px solid #bbf7d0; color: #166534; padding: 8px; border-radius: 4px; margin-bottom: 10px;">
<strong>🔑 Clave Configurada:</strong><br>
• Label: ${provider.user_key_label || 'Sin etiqueta'}<br>
• Últimos 4: ••••${provider.last4 || '????'}<br>
• Ambiente: ${provider.environment || 'live'}<br>
• Estado: ${provider.key_status || 'N/A'}
</div>
<strong>URL Request:</strong> ${provider.url_request || 'No configurada'}<br>
<strong>Base URL:</strong> ${provider.base_url || 'No configurada'}<br>
<strong>Auth Type:</strong> ${provider.auth_type || 'N/A'}<br>
<strong>Test Config:</strong> ${hasTestConfig ? '✅ Configurado' : '❌ No configurado'}
</div>
<div class="test-form">
<div class="form-group">
<label class="form-label">Project Fields (JSON):</label>
<textarea id="fields-${provider.id}" class="form-input" rows="2" placeholder='{"resource": "mi-recurso", "api_version": "2024-10-21"}'></textarea>
</div>
<button class="btn-test" onclick="testProvider(${provider.id}, '${provider.name}')"
${!hasTestConfig ? 'disabled title="No hay configuración de prueba"' : ''}>
🧪 Probar
</button>
</div>
<div id="result-${provider.id}" class="result-section"></div>
`;
grid.appendChild(card);
});
container.innerHTML = '';
container.appendChild(grid);
}
// Función para probar proveedor
async function testProvider(providerId, providerName) {
const providerType = document.getElementById('provider-type').value;
const fieldsText = document.getElementById(`fields-${providerId}`).value;
addLog('info', `Iniciando prueba para: ${providerName} (ID: ${providerId})`);
let projectFields = {};
if (fieldsText.trim()) {
try {
projectFields = JSON.parse(fieldsText);
addLog('info', 'Project fields parseados', projectFields);
} catch (error) {
addLog('error', 'Error parseando project fields JSON', error);
return;
}
}
const resultDiv = document.getElementById(`result-${providerId}`);
resultDiv.style.display = 'block';
resultDiv.className = 'result-section';
resultDiv.innerHTML = '<div>🔄 Probando...</div>';
try {
const response = await api('test_provider_key_safe.php', {
method: 'POST',
body: {
provider_type: providerType,
provider_id: providerId,
project_fields: projectFields
}
});
addLog('info', 'Respuesta de prueba recibida', response);
if (response.ok) {
resultDiv.className = 'result-section result-success';
resultDiv.innerHTML = `
<div class="result-header">
<div class="result-status">✅ Prueba Exitosa</div>
<div class="result-duration">${response.duration_ms}ms</div>
</div>
<div><strong>HTTP:</strong> ${response.http_code}</div>
<div><strong>Proveedor:</strong> ${response.provider_name} (${response.provider_slug})</div>
<div><strong>Ambiente:</strong> ${response.environment}</div>
${response.debug ? `<div><strong>Debug:</strong> ${response.debug}</div>` : ''}
<div class="result-details">${response.body_snippet}</div>
`;
addLog('success', `Prueba exitosa: ${response.provider_name}`);
} else {
resultDiv.className = 'result-section result-error';
resultDiv.innerHTML = `
<div class="result-header">
<div class="result-status">❌ Prueba Fallida</div>
<div class="result-duration">${response.duration_ms || 'N/A'}ms</div>
</div>
<div><strong>Error:</strong> ${response.reason}</div>
<div><strong>HTTP:</strong> ${response.http_code || 'N/A'}</div>
<div><strong>Proveedor:</strong> ${response.provider_name || providerName}</div>
${response.debug ? `<div><strong>Debug:</strong> ${response.debug}</div>` : ''}
<div class="result-details">${response.body_snippet || 'Sin detalles'}</div>
`;
addLog('error', `Prueba fallida: ${response.reason}`);
}
} catch (error) {
resultDiv.className = 'result-section result-error';
resultDiv.innerHTML = `
<div class="result-header">
<div class="result-status">💥 Error de Conexión</div>
</div>
<div><strong>Error:</strong> ${error.message}</div>
`;
addLog('error', 'Error en petición de prueba', error);
}
}
// Función para obtener token del usuario logueado
function getAuthToken() {
// Intentar obtener token de diferentes fuentes
let token = localStorage.getItem('token') ||
localStorage.getItem('auth_token') ||
sessionStorage.getItem('token') ||
sessionStorage.getItem('auth_token');
// Si no hay token, intentar obtener del ConfigPortable
if (!token && window.ConfigPortable && window.ConfigPortable.getToken) {
token = window.ConfigPortable.getToken();
}
// Si aún no hay token, verificar si hay función global
if (!token && typeof getToken === 'function') {
token = getToken();
}
addLog('info', `Token obtenido: ${token ? 'SÍ' : 'NO'} (${token ? token.substring(0, 20) + '...' : 'N/A'})`);
return token;
}
// Función para verificar si el usuario está autenticado
async function checkAuthStatus() {
const token = getAuthToken();
if (!token) {
addLog('warning', 'No hay token de autenticación. Redirigiendo a login...');
showAuthPrompt();
return false;
}
try {
// Verificar si el token es válido haciendo una petición simple
const response = await fetch('api/auth_me.php', {
headers: {
'Authorization': `Bearer ${token}`
}
});
if (response.ok) {
addLog('success', 'Usuario autenticado correctamente');
return true;
} else {
addLog('warning', 'Token expirado o inválido. Redirigiendo a login...');
showAuthPrompt();
return false;
}
} catch (error) {
addLog('error', 'Error verificando autenticación', error);
showAuthPrompt();
return false;
}
}
// Función para mostrar prompt de autenticación
function showAuthPrompt() {
const container = document.getElementById('providers-container');
container.innerHTML = `
<div style="background: #fef3c7; border: 1px solid #fde68a; color: #92400e; padding: 20px; border-radius: 8px; text-align: center;">
<h3>🔐 Autenticación Requerida</h3>
<p>Necesitas iniciar sesión para usar esta página de prueba.</p>
<p><strong>Opciones:</strong></p>
<ol style="text-align: left; display: inline-block;">
<li>Ve a la página principal y <strong>inicia sesión</strong></li>
<li>Regresa a esta página una vez autenticado</li>
<li>O recarga la página si ya iniciaste sesión</li>
</ol>
<div style="margin-top: 15px;">
<button onclick="location.reload()" class="btn-test" style="background: var(--primary-color);">
🔄 Recargar Página
</button>
<button onclick="location.href='index.html'" class="btn-test" style="background: var(--gray-color); margin-left: 10px;">
🏠 Ir a Inicio
</button>
</div>
</div>
`;
}
// Función API helper
async function api(endpoint, options = {}) {
const url = `api/${endpoint}`;
const token = getAuthToken();
if (!token) {
addLog('error', 'No se encontró token de autenticación. Inicia sesión primero.');
throw new Error('No hay token de autenticación. Inicia sesión primero.');
}
const config = {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`
},
...options
};
if (config.body && typeof config.body === 'object') {
config.body = JSON.stringify(config.body);
}
addLog('info', `Realizando petición a: ${url}`);
try {
const response = await fetch(url, config);
const data = await response.json();
addLog('info', `Respuesta recibida (${response.status}):`, data);
// Si el token expiró, mostrar mensaje y sugerir recargar
if (!response.ok && (data.error === 'invalid-token' || data.detail === 'token-expired')) {
addLog('warning', 'Token expirado. Recarga la página o inicia sesión nuevamente.');
showAuthPrompt();
}
return data;
} catch (error) {
addLog('error', 'Error en petición de red', error);
throw error;
}
}
// Función para refrescar el token
async function refreshToken() {
addLog('info', 'Intentando refrescar token...');
// Limpiar tokens existentes
localStorage.removeItem('token');
localStorage.removeItem('auth_token');
sessionStorage.removeItem('token');
sessionStorage.removeItem('auth_token');
// Intentar obtener nuevo token
const newToken = getAuthToken();
if (newToken) {
addLog('success', 'Nuevo token obtenido');
// Verificar si el nuevo token es válido
const isValid = await checkAuthStatus();
if (isValid) {
addLog('success', 'Token válido. Puedes continuar con las pruebas.');
}
} else {
addLog('warning', 'No se pudo obtener nuevo token. Ve a la página principal para iniciar sesión.');
showAuthPrompt();
}
}
// Event listeners
document.getElementById('load-providers').addEventListener('click', loadProviders);
document.getElementById('clear-logs').addEventListener('click', clearLogs);
document.getElementById('refresh-token').addEventListener('click', refreshToken);
// Verificar estado de autenticación
function checkAuthStatus() {
const token = getAuthToken();
if (token) {
addLog('success', 'Usuario autenticado correctamente');
return true;
} else {
addLog('error', 'Usuario no autenticado. Inicia sesión en la aplicación principal.');
return false;
}
}
// Cargar proveedores por defecto
document.addEventListener('DOMContentLoaded', async () => {
addLog('info', 'Página cargada. Sistema de prueba genérico listo.');
// Verificar autenticación al cargar
const isAuthenticated = await checkAuthStatus();
if (!isAuthenticated) {
// Mostrar mensaje de error en la interfaz
const container = document.getElementById('providers-container');
container.innerHTML = `
<div style="background: #fee2e2; border: 1px solid #fecaca; color: #991b1b; padding: 15px; border-radius: 8px;">
<h3>🔐 Autenticación Requerida</h3>
<p>Para usar esta página de prueba, debes estar logueado en la aplicación principal.</p>
<p><strong>Pasos:</strong></p>
<ol>
<li>Ve a la página principal de la aplicación</li>
<li>Inicia sesión con tu usuario</li>
<li>Regresa a esta página de prueba</li>
</ol>
<p><strong>Token encontrado:</strong> ${getAuthToken() ? 'SÍ' : 'NO'}</p>
</div>
`;
}
});
</script>
</body>
</html>