feat: ApiAuthService + Sincronizador reescritos para WebControl/Centinel

- ApiAuthService: login WebControl → guarda jwt + apiKey + db_tenant
- Sincronizador: pull alarmas/zonas/usuarios/mensajes/banners + push pendientes
- DAOs: métodos adicionales en alarmas, eventos, usuarios
- Páginas actualizadas: ConectarProveedorPage, ControlAccesoPage, MensajeríaPage, MonitoreoAlarmaPage

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
Pablinux
2026-06-21 17:36:11 -05:00
co-authored by Claude Sonnet 4.6
parent 4724f84b04
commit efa4a792f4
9 changed files with 595 additions and 162 deletions
+69 -34
View File
@@ -2,40 +2,55 @@ import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:shared_preferences/shared_preferences.dart';
/// Gestiona la autenticación contra la API y el ciclo de vida del token JWT.
/// El token NUNCA se expone a las páginas — solo lo usa [Sincronizador].
/// 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 _keyToken = 'api_token';
static const _keyExpiry = 'api_token_expiry';
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 ──────────────────────────────────────────────────────────────────
/// Solicita token al servidor.
/// Devuelve `true` si el login fue exitoso.
Future<bool> login(String baseUrl, String usuario, String password) async {
/// 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('$baseUrl/auth/login'),
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) {
final body = jsonDecode(resp.body) as Map<String, dynamic>;
final token = body['token'] as String?;
final expiryStr = body['expiry'] as String?;
if (token == null) return false;
if (resp.statusCode != 200) return false;
final prefs = await SharedPreferences.getInstance();
await prefs.setString(_keyToken, token);
if (expiryStr != null) {
await prefs.setString(_keyExpiry, expiryStr);
}
return true;
}
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;
}
@@ -44,27 +59,47 @@ class ApiAuthService {
// ── Logout ─────────────────────────────────────────────────────────────────
Future<void> logout() async {
final prefs = await SharedPreferences.getInstance();
await prefs.remove(_keyToken);
await prefs.remove(_keyExpiry);
await prefs.remove(_keyJwt);
await prefs.remove(_keyApiKey);
await prefs.remove(_keyTenant);
}
// ── Estado ─────────────────────────────────────────────────────────────────
Future<bool> isAuthenticated() async {
final token = await getToken();
if (token == null || token.isEmpty) return false;
final prefs = await SharedPreferences.getInstance();
final expiryStr = prefs.getString(_keyExpiry);
if (expiryStr == null) return true; // Sin expiración = válido
final expiry = DateTime.tryParse(expiryStr);
if (expiry == null) return true;
return DateTime.now().isBefore(expiry);
final apiKey = prefs.getString(_keyApiKey);
return apiKey != null && apiKey.isNotEmpty;
}
// ── Token ──────────────────────────────────────────────────────────────────
// ── 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(_keyToken);
return prefs.getString(_keyJwt);
}
}
+64 -49
View File
@@ -16,9 +16,14 @@ import '../models/zona.dart';
import '../models/mensaje.dart';
import '../models/banner_item.dart';
/// Orquesta la sincronización entre la API y SQLite.
/// Orquesta la sincronización entre API_CENTINEL_SECURITY y SQLite.
/// Las páginas nunca llaman a la API directamente — solo leen SQLite.
///
/// Todas las llamadas van a [_centinelBase] usando los headers de
/// [ApiAuthService.getCentinelHeaders()] (x-api-key + x-database).
class Sincronizador {
static const _centinelBase = 'https://api.telcotronics.com';
Sincronizador._();
static final Sincronizador instance = Sincronizador._();
@@ -33,7 +38,7 @@ class Sincronizador {
await _syncLog.registrar(
tipo: 'full',
estado: 'error',
detalle: 'Sin token válido — sincronización omitida',
detalle: 'Sin credenciales Centinel — sincronización omitida',
);
return;
}
@@ -155,63 +160,79 @@ class Sincronizador {
detalle: 'banners: ${data.length} registros');
}
// ── Push de pendientes (local → API) ───────────────────────────────────────
// ── Push de pendientes (local → API_CENTINEL_SECURITY) ────────────────────
Future<void> pushPendientes() async {
await _pushAlarmasPendientes();
await _pushAccesosPendientes();
await _pushMensajesPendientes();
await _pushUsuariosPendientes();
await _syncLog.registrar(tipo: 'push', estado: 'ok',
detalle: 'Push de pendientes completado');
}
/// Empuja alarmas con sincronizado=0 usando los endpoints reales de Centinel.
/// El estado de la alarma determina el endpoint: escalar / resolver / silenciar.
Future<void> _pushAlarmasPendientes() async {
final pendientes = await AlarmasDao().getPendientes();
if (pendientes.isEmpty) return;
final baseUrl = await _config.get('api_base_url') ?? '';
final token = await _auth.getToken();
if (baseUrl.isEmpty || token == null) return;
final headers = await _auth.getCentinelHeaders();
if (headers == null) return;
for (final a in pendientes) {
try {
await http.put(
Uri.parse('$baseUrl/alarmas/${a.id}'),
headers: _headers(token),
body: jsonEncode(a.toMap()),
).timeout(const Duration(seconds: 8));
final http.Response resp;
switch (a.estado) {
case 'escalada':
resp = await http.post(
Uri.parse('$_centinelBase/api/alarmas/${a.id}/escalar'),
headers: headers,
body: jsonEncode({'severidad_nueva': a.severidad}),
).timeout(const Duration(seconds: 8));
break;
case 'silenciada':
resp = await http.put(
Uri.parse('$_centinelBase/api/alarmas/${a.id}/silenciar'),
headers: headers,
body: jsonEncode({}),
).timeout(const Duration(seconds: 8));
break;
default: // resuelta
resp = await http.put(
Uri.parse('$_centinelBase/api/alarmas/${a.id}/resolver'),
headers: headers,
body: jsonEncode({'notas': a.notas}),
).timeout(const Duration(seconds: 8));
}
if (resp.statusCode == 200 || resp.statusCode == 204) {
final db = AlarmasDao();
await db.update(a);
}
} catch (_) {
// Continúa con el siguiente — se reintentará en el próximo ciclo
// Continúa — se reintentará en el próximo ciclo de sync
}
}
}
Future<void> _pushAccesosPendientes() async {
final pendientes = await AccesosDao().getPendientes();
/// Sincroniza usuarios nuevos (registrados offline) al dispositivo Centinel.
Future<void> _pushUsuariosPendientes() async {
final pendientes = await UsuariosDao().getPendientes();
if (pendientes.isEmpty) return;
final baseUrl = await _config.get('api_base_url') ?? '';
final token = await _auth.getToken();
if (baseUrl.isEmpty || token == null) return;
for (final a in pendientes) {
try {
await http.post(
Uri.parse('$baseUrl/accesos'),
headers: _headers(token),
body: jsonEncode(a.toMap()),
).timeout(const Duration(seconds: 8));
} catch (_) {}
}
}
final headers = await _auth.getCentinelHeaders();
if (headers == null) return;
// Requiere deviceId configurado — pendiente cuando se registre el dispositivo
final deviceId = await _config.get('centinel_device_id');
if (deviceId == null || deviceId.isEmpty) return;
Future<void> _pushMensajesPendientes() async {
final pendientes = await MensajesDao().getPendientes();
if (pendientes.isEmpty) return;
final baseUrl = await _config.get('api_base_url') ?? '';
final token = await _auth.getToken();
if (baseUrl.isEmpty || token == null) return;
for (final m in pendientes) {
for (final u in pendientes) {
try {
await http.post(
Uri.parse('$baseUrl/mensajes'),
headers: _headers(token),
body: jsonEncode(m.toMap()),
Uri.parse('$_centinelBase/api/devices/$deviceId/employees'),
headers: headers,
body: jsonEncode({
'employeeNo': u.id.toString(),
'name': u.nombre,
'userType': 'normal',
}),
).timeout(const Duration(seconds: 8));
} catch (_) {}
}
@@ -219,14 +240,13 @@ class Sincronizador {
// ── Helpers ────────────────────────────────────────────────────────────────
Future<List<Map<String, dynamic>>?> _get(String endpoint) async {
final baseUrl = await _config.get('api_base_url') ?? '';
final token = await _auth.getToken();
if (baseUrl.isEmpty || token == null) return null;
final headers = await _auth.getCentinelHeaders();
if (headers == null) return null;
try {
final resp = await http.get(
Uri.parse('$baseUrl$endpoint'),
headers: _headers(token),
Uri.parse('$_centinelBase$endpoint'),
headers: headers,
).timeout(const Duration(seconds: 10));
if (resp.statusCode == 200) {
@@ -238,9 +258,4 @@ class Sincronizador {
return null;
}
}
Map<String, String> _headers(String token) => {
'Content-Type': 'application/json',
'Authorization': 'Bearer $token',
};
}