Files
seguridad_electronica/lib/services/api_auth_service.dart
T

121 lines
5.0 KiB
Dart

import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:shared_preferences/shared_preferences.dart';
/// Gestiona la autenticación contra WebControl y las credenciales para Centinel.
///
/// Flujo:
/// login(usuario, password)
/// → POST https://api.siax-system.net/api/auth/login
/// → recibe { jwt, apiKey, db_tenant }
/// → guarda en SharedPreferences
///
/// Uso posterior (para llamadas a api.telcotronics.com):
/// final h = await ApiAuthService.instance.getCentinelHeaders();
/// http.get(uri, headers: h)
///
/// WebControl es el dueño de las API keys.
/// Centinel solo las valida — no crea ni gestiona ninguna.
class ApiAuthService {
static const _webControlBase = 'https://api.siax-system.net';
static const _keyJwt = 'webcontrol_jwt';
static const _keyApiKey = 'centinel_api_key';
static const _keyTenant = 'centinel_tenant';
ApiAuthService._();
static final ApiAuthService instance = ApiAuthService._();
// ── Login ──────────────────────────────────────────────────────────────────
/// Autentica contra WebControl.
/// Devuelve `true` si el login fue exitoso y las credenciales quedaron guardadas.
Future<bool> login(String usuario, String password) async {
try {
final resp = await http.post(
Uri.parse('$_webControlBase/api/auth/login'),
headers: {'Content-Type': 'application/json'},
body: jsonEncode({'usuario': usuario, 'password': password}),
).timeout(const Duration(seconds: 10));
if (resp.statusCode != 200) return false;
final body = jsonDecode(resp.body) as Map<String, dynamic>;
final jwt = body['jwt'] as String?;
final apiKey = body['apiKey'] as String?;
final tenant = body['db_tenant'] as String?;
if (apiKey == null || tenant == null) return false;
final prefs = await SharedPreferences.getInstance();
if (jwt != null) await prefs.setString(_keyJwt, jwt);
await prefs.setString(_keyApiKey, apiKey);
await prefs.setString(_keyTenant, tenant);
return true;
} catch (_) {
return false;
}
}
// ── Logout ─────────────────────────────────────────────────────────────────
Future<void> logout() async {
final prefs = await SharedPreferences.getInstance();
await prefs.remove(_keyJwt);
await prefs.remove(_keyApiKey);
await prefs.remove(_keyTenant);
}
// ── Estado ─────────────────────────────────────────────────────────────────
Future<bool> isAuthenticated() async {
final prefs = await SharedPreferences.getInstance();
final apiKey = prefs.getString(_keyApiKey);
return apiKey != null && apiKey.isNotEmpty;
}
// Establece credenciales manuales para API_CENTINEL_SECURITY (útil en onboarding y pruebas)
Future<void> setCentinelCredentials({required String apiKey, required String tenant}) async {
final prefs = await SharedPreferences.getInstance();
await prefs.setString(_keyApiKey, apiKey);
await prefs.setString(_keyTenant, tenant);
}
// Precarga las credenciales oficiales de prueba confirmadas por Agente api-centinel-security
Future<void> usarCredencialesPruebaCentinel() async {
await setCentinelCredentials(
apiKey: 'admin-api-key-centinel-2026',
tenant: 'security_db',
);
}
// ── Headers para API_CENTINEL_SECURITY ─────────────────────────────────────
/// Devuelve los headers necesarios para llamar a api.telcotronics.com.
/// Retorna `null` si no hay credenciales guardadas.
Future<Map<String, String>?> getCentinelHeaders() async {
final prefs = await SharedPreferences.getInstance();
final apiKey = prefs.getString(_keyApiKey);
final tenant = prefs.getString(_keyTenant);
if (apiKey == null || apiKey.isEmpty) return null;
return {
'Content-Type': 'application/json',
'x-api-key': apiKey,
'x-database': tenant ?? '',
};
}
// ── Acceso individual a valores guardados ───────────────────────────────────
Future<String?> getApiKey() async {
final prefs = await SharedPreferences.getInstance();
return prefs.getString(_keyApiKey);
}
Future<String?> getTenant() async {
final prefs = await SharedPreferences.getInstance();
return prefs.getString(_keyTenant);
}
/// JWT de WebControl — disponible para llamadas a api.siax-system.net si se necesitan.
Future<String?> getToken() async {
final prefs = await SharedPreferences.getInstance();
return prefs.getString(_keyJwt);
}
}