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 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; 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 logout() async { final prefs = await SharedPreferences.getInstance(); await prefs.remove(_keyJwt); await prefs.remove(_keyApiKey); await prefs.remove(_keyTenant); } // ── Estado ───────────────────────────────────────────────────────────────── Future isAuthenticated() async { final prefs = await SharedPreferences.getInstance(); final apiKey = prefs.getString(_keyApiKey); return apiKey != null && apiKey.isNotEmpty; } // ── Headers para API_CENTINEL_SECURITY ───────────────────────────────────── /// Devuelve los headers necesarios para llamar a api.telcotronics.com. /// Retorna `null` si no hay credenciales guardadas. Future?> 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 getApiKey() async { final prefs = await SharedPreferences.getInstance(); return prefs.getString(_keyApiKey); } Future 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 getToken() async { final prefs = await SharedPreferences.getInstance(); return prefs.getString(_keyJwt); } }