feat: add SQLite data layer, local auth and security settings
- Add offline-first SQLite architecture with DatabaseHelper singleton, 12 CREATE TABLE statements and full seed data on first launch - Add 10 models (fromMap/toMap) and 12 DAOs with CRUD + getPendientes() - Add ApiAuthService (JWT via SharedPreferences) and Sincronizador skeleton - Move login auth from SQLite to SharedPreferences with SHA-256 PIN hash; default PIN 123456, platform-independent (no native plugin required) - Add seguridad_page.dart: change PIN form (current → new → confirm) - Add Cerrar Sesión with confirmation dialog and full stack clear - Redesign settings_page.dart with AppColors dark theme; add Sistema section with "Inicializar base de datos" and "Inicializar sincronización" - Fix Linux desktop: sqflite_common_ffi with platform detection in DatabaseHelper - Fix ScrollController conflict on Linux: primary: false on all IndexedStack pages - Update plan_proyecto.md with session 2–3 progress and auth roadmap Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Sonnet 4.6
parent
8f13d57839
commit
1184ab5fe2
@@ -0,0 +1,70 @@
|
||||
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].
|
||||
class ApiAuthService {
|
||||
static const _keyToken = 'api_token';
|
||||
static const _keyExpiry = 'api_token_expiry';
|
||||
|
||||
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 {
|
||||
try {
|
||||
final resp = await http.post(
|
||||
Uri.parse('$baseUrl/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;
|
||||
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
await prefs.setString(_keyToken, token);
|
||||
if (expiryStr != null) {
|
||||
await prefs.setString(_keyExpiry, expiryStr);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
} catch (_) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// ── Logout ─────────────────────────────────────────────────────────────────
|
||||
Future<void> logout() async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
await prefs.remove(_keyToken);
|
||||
await prefs.remove(_keyExpiry);
|
||||
}
|
||||
|
||||
// ── 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);
|
||||
}
|
||||
|
||||
// ── Token ──────────────────────────────────────────────────────────────────
|
||||
Future<String?> getToken() async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
return prefs.getString(_keyToken);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,246 @@
|
||||
import 'dart:convert';
|
||||
import 'package:http/http.dart' as http;
|
||||
import 'api_auth_service.dart';
|
||||
import '../db/dao/alarmas_dao.dart';
|
||||
import '../db/dao/accesos_dao.dart';
|
||||
import '../db/dao/usuarios_dao.dart';
|
||||
import '../db/dao/zonas_dao.dart';
|
||||
import '../db/dao/mensajes_dao.dart';
|
||||
import '../db/dao/banners_dao.dart';
|
||||
import '../db/dao/sync_log_dao.dart';
|
||||
import '../db/dao/configuracion_dao.dart';
|
||||
import '../models/alarma.dart';
|
||||
import '../models/acceso.dart';
|
||||
import '../models/usuario.dart';
|
||||
import '../models/zona.dart';
|
||||
import '../models/mensaje.dart';
|
||||
import '../models/banner_item.dart';
|
||||
|
||||
/// Orquesta la sincronización entre la API y SQLite.
|
||||
/// Las páginas nunca llaman a la API directamente — solo leen SQLite.
|
||||
class Sincronizador {
|
||||
Sincronizador._();
|
||||
static final Sincronizador instance = Sincronizador._();
|
||||
|
||||
final _auth = ApiAuthService.instance;
|
||||
final _syncLog = SyncLogDao();
|
||||
final _config = ConfiguracionDao();
|
||||
|
||||
// ── Punto de entrada principal ─────────────────────────────────────────────
|
||||
Future<void> sincronizar() async {
|
||||
final autenticado = await _auth.isAuthenticated();
|
||||
if (!autenticado) {
|
||||
await _syncLog.registrar(
|
||||
tipo: 'full',
|
||||
estado: 'error',
|
||||
detalle: 'Sin token válido — sincronización omitida',
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
await sincronizarZonas();
|
||||
await sincronizarUsuarios();
|
||||
await sincronizarAlarmas();
|
||||
await sincronizarAccesos();
|
||||
await sincronizarMensajes();
|
||||
await sincronizarBanners();
|
||||
await pushPendientes();
|
||||
|
||||
await _syncLog.registrar(
|
||||
tipo: 'full',
|
||||
estado: 'ok',
|
||||
detalle: 'Sincronización completa',
|
||||
);
|
||||
} catch (e) {
|
||||
await _syncLog.registrar(
|
||||
tipo: 'full',
|
||||
estado: 'error',
|
||||
detalle: e.toString(),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// ── Métodos específicos ────────────────────────────────────────────────────
|
||||
|
||||
Future<void> sincronizarZonas() async {
|
||||
final data = await _get('/zonas');
|
||||
if (data == null) return;
|
||||
final dao = ZonasDao();
|
||||
for (final item in data) {
|
||||
final z = Zona.fromMap({...item, 'sincronizado': 1});
|
||||
final existente = await dao.getById(z.id);
|
||||
if (existente == null) {
|
||||
await dao.insert(z);
|
||||
} else {
|
||||
await dao.update(z);
|
||||
}
|
||||
}
|
||||
await _syncLog.registrar(tipo: 'parcial', estado: 'ok',
|
||||
detalle: 'zonas: ${data.length} registros');
|
||||
}
|
||||
|
||||
Future<void> sincronizarUsuarios() async {
|
||||
final data = await _get('/usuarios');
|
||||
if (data == null) return;
|
||||
final dao = UsuariosDao();
|
||||
for (final item in data) {
|
||||
final u = Usuario.fromMap({...item, 'sincronizado': 1});
|
||||
final existente = await dao.getById(u.id);
|
||||
if (existente == null) {
|
||||
await dao.insert(u);
|
||||
} else {
|
||||
await dao.update(u);
|
||||
}
|
||||
}
|
||||
await _syncLog.registrar(tipo: 'parcial', estado: 'ok',
|
||||
detalle: 'usuarios: ${data.length} registros');
|
||||
}
|
||||
|
||||
Future<void> sincronizarAlarmas() async {
|
||||
final data = await _get('/alarmas');
|
||||
if (data == null) return;
|
||||
final dao = AlarmasDao();
|
||||
for (final item in data) {
|
||||
final a = Alarma.fromMap({...item, 'sincronizado': 1});
|
||||
final existente = await dao.getById(a.id);
|
||||
if (existente == null) {
|
||||
await dao.insert(a);
|
||||
} else {
|
||||
await dao.update(a);
|
||||
}
|
||||
}
|
||||
await _syncLog.registrar(tipo: 'parcial', estado: 'ok',
|
||||
detalle: 'alarmas: ${data.length} registros');
|
||||
}
|
||||
|
||||
Future<void> sincronizarAccesos() async {
|
||||
final data = await _get('/accesos');
|
||||
if (data == null) return;
|
||||
final dao = AccesosDao();
|
||||
for (final item in data) {
|
||||
final a = Acceso.fromMap({...item, 'sincronizado': 1});
|
||||
await dao.insert(a);
|
||||
}
|
||||
await _syncLog.registrar(tipo: 'parcial', estado: 'ok',
|
||||
detalle: 'accesos: ${data.length} registros');
|
||||
}
|
||||
|
||||
Future<void> sincronizarMensajes() async {
|
||||
final data = await _get('/mensajes');
|
||||
if (data == null) return;
|
||||
final dao = MensajesDao();
|
||||
for (final item in data) {
|
||||
final m = Mensaje.fromMap({...item, 'sincronizado': 1});
|
||||
await dao.insert(m);
|
||||
}
|
||||
await _syncLog.registrar(tipo: 'parcial', estado: 'ok',
|
||||
detalle: 'mensajes: ${data.length} registros');
|
||||
}
|
||||
|
||||
Future<void> sincronizarBanners() async {
|
||||
final data = await _get('/banners');
|
||||
if (data == null) return;
|
||||
final dao = BannersDao();
|
||||
for (final item in data) {
|
||||
final b = BannerItem.fromMap({...item, 'sincronizado': 1});
|
||||
final existente = await dao.getById(b.id);
|
||||
if (existente == null) {
|
||||
await dao.insert(b);
|
||||
} else {
|
||||
await dao.update(b);
|
||||
}
|
||||
}
|
||||
await _syncLog.registrar(tipo: 'parcial', estado: 'ok',
|
||||
detalle: 'banners: ${data.length} registros');
|
||||
}
|
||||
|
||||
// ── Push de pendientes (local → API) ───────────────────────────────────────
|
||||
Future<void> pushPendientes() async {
|
||||
await _pushAlarmasPendientes();
|
||||
await _pushAccesosPendientes();
|
||||
await _pushMensajesPendientes();
|
||||
await _syncLog.registrar(tipo: 'push', estado: 'ok',
|
||||
detalle: 'Push de pendientes completado');
|
||||
}
|
||||
|
||||
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;
|
||||
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));
|
||||
} catch (_) {
|
||||
// Continúa con el siguiente — se reintentará en el próximo ciclo
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _pushAccesosPendientes() async {
|
||||
final pendientes = await AccesosDao().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 (_) {}
|
||||
}
|
||||
}
|
||||
|
||||
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) {
|
||||
try {
|
||||
await http.post(
|
||||
Uri.parse('$baseUrl/mensajes'),
|
||||
headers: _headers(token),
|
||||
body: jsonEncode(m.toMap()),
|
||||
).timeout(const Duration(seconds: 8));
|
||||
} catch (_) {}
|
||||
}
|
||||
}
|
||||
|
||||
// ── 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;
|
||||
|
||||
try {
|
||||
final resp = await http.get(
|
||||
Uri.parse('$baseUrl$endpoint'),
|
||||
headers: _headers(token),
|
||||
).timeout(const Duration(seconds: 10));
|
||||
|
||||
if (resp.statusCode == 200) {
|
||||
final body = jsonDecode(resp.body);
|
||||
if (body is List) return body.cast<Map<String, dynamic>>();
|
||||
}
|
||||
return null;
|
||||
} catch (_) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
Map<String, String> _headers(String token) => {
|
||||
'Content-Type': 'application/json',
|
||||
'Authorization': 'Bearer $token',
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user