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:
co-authored by
Claude Sonnet 4.6
parent
4724f84b04
commit
efa4a792f4
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user