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,323 @@
|
||||
import 'dart:convert';
|
||||
import 'package:crypto/crypto.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
import '../theme.dart';
|
||||
|
||||
class SeguridadPage extends StatefulWidget {
|
||||
const SeguridadPage({Key? key}) : super(key: key);
|
||||
|
||||
@override
|
||||
State<SeguridadPage> createState() => _SeguridadPageState();
|
||||
}
|
||||
|
||||
class _SeguridadPageState extends State<SeguridadPage> {
|
||||
static const _keyPinHash = 'local_pin_hash';
|
||||
static const _defaultPin = '123456';
|
||||
static const _pinLen = 6;
|
||||
|
||||
// Campos del PIN
|
||||
final List<TextEditingController> _ctrlActual =
|
||||
List.generate(_pinLen, (_) => TextEditingController());
|
||||
final List<TextEditingController> _ctrlNuevo =
|
||||
List.generate(_pinLen, (_) => TextEditingController());
|
||||
final List<TextEditingController> _ctrlConfirm =
|
||||
List.generate(_pinLen, (_) => TextEditingController());
|
||||
|
||||
final List<FocusNode> _focusActual =
|
||||
List.generate(_pinLen, (_) => FocusNode());
|
||||
final List<FocusNode> _focusNuevo =
|
||||
List.generate(_pinLen, (_) => FocusNode());
|
||||
final List<FocusNode> _focusConfirm =
|
||||
List.generate(_pinLen, (_) => FocusNode());
|
||||
|
||||
bool _guardando = false;
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
for (final c in [..._ctrlActual, ..._ctrlNuevo, ..._ctrlConfirm]) {
|
||||
c.dispose();
|
||||
}
|
||||
for (final f in [..._focusActual, ..._focusNuevo, ..._focusConfirm]) {
|
||||
f.dispose();
|
||||
}
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
String _pinDe(List<TextEditingController> ctrls) =>
|
||||
ctrls.map((c) => c.text).join();
|
||||
|
||||
String _hash(String pin) =>
|
||||
sha256.convert(utf8.encode(pin)).toString();
|
||||
|
||||
void _onDigit(List<TextEditingController> ctrls,
|
||||
List<FocusNode> focus, int i, String v) {
|
||||
if (v.isNotEmpty && i < _pinLen - 1) focus[i + 1].requestFocus();
|
||||
setState(() {});
|
||||
}
|
||||
|
||||
void _onKey(List<TextEditingController> ctrls,
|
||||
List<FocusNode> focus, int i, RawKeyEvent e) {
|
||||
if (e is RawKeyDownEvent &&
|
||||
e.logicalKey == LogicalKeyboardKey.backspace &&
|
||||
ctrls[i].text.isEmpty &&
|
||||
i > 0) {
|
||||
focus[i - 1].requestFocus();
|
||||
ctrls[i - 1].clear();
|
||||
setState(() {});
|
||||
}
|
||||
}
|
||||
|
||||
void _limpiarTodo() {
|
||||
for (final c in [..._ctrlActual, ..._ctrlNuevo, ..._ctrlConfirm]) {
|
||||
c.clear();
|
||||
}
|
||||
_focusActual[0].requestFocus();
|
||||
setState(() {});
|
||||
}
|
||||
|
||||
Future<void> _guardar() async {
|
||||
final actual = _pinDe(_ctrlActual);
|
||||
final nuevo = _pinDe(_ctrlNuevo);
|
||||
final confirma = _pinDe(_ctrlConfirm);
|
||||
|
||||
if (actual.length < 4 || nuevo.length < 4 || confirma.length < 4) {
|
||||
_snack('Completa todos los campos (mínimo 4 dígitos)');
|
||||
return;
|
||||
}
|
||||
if (nuevo != confirma) {
|
||||
_snack('El nuevo PIN y la confirmación no coinciden');
|
||||
return;
|
||||
}
|
||||
if (nuevo == actual) {
|
||||
_snack('El nuevo PIN debe ser diferente al actual');
|
||||
return;
|
||||
}
|
||||
|
||||
setState(() => _guardando = true);
|
||||
|
||||
try {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
final hashGuardado =
|
||||
prefs.getString(_keyPinHash) ?? _hash(_defaultPin);
|
||||
|
||||
if (_hash(actual) != hashGuardado) {
|
||||
_snack('El PIN actual es incorrecto');
|
||||
_ctrlActual.forEach((c) => c.clear());
|
||||
_focusActual[0].requestFocus();
|
||||
return;
|
||||
}
|
||||
|
||||
await prefs.setString(_keyPinHash, _hash(nuevo));
|
||||
_snack('PIN actualizado correctamente', esError: false);
|
||||
_limpiarTodo();
|
||||
} finally {
|
||||
if (mounted) setState(() => _guardando = false);
|
||||
}
|
||||
}
|
||||
|
||||
void _snack(String msg, {bool esError = true}) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
|
||||
content: Text(msg),
|
||||
backgroundColor:
|
||||
esError ? AppColors.error : AppColors.primary,
|
||||
));
|
||||
}
|
||||
|
||||
// ── Build ──────────────────────────────────────────────────────────────────
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final todosCompletos = _pinDe(_ctrlActual).length >= 4 &&
|
||||
_pinDe(_ctrlNuevo).length >= 4 &&
|
||||
_pinDe(_ctrlConfirm).length >= 4;
|
||||
|
||||
return Scaffold(
|
||||
backgroundColor: AppColors.surfaceLowest,
|
||||
appBar: AppBar(
|
||||
backgroundColor: AppColors.surfaceLow,
|
||||
elevation: 0,
|
||||
leading: IconButton(
|
||||
icon: const Icon(Icons.arrow_back_ios_new,
|
||||
color: AppColors.onSurface, size: 18),
|
||||
onPressed: () => Navigator.pop(context),
|
||||
),
|
||||
title: Text('SEGURIDAD',
|
||||
style: appHeadline(size: 16, weight: FontWeight.w800,
|
||||
color: AppColors.primary, spacing: 2.0)),
|
||||
),
|
||||
body: SafeArea(
|
||||
child: SingleChildScrollView(
|
||||
primary: false,
|
||||
padding: const EdgeInsets.all(24),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
// ── Info ────────────────────────────────────────────────────
|
||||
Container(
|
||||
width: double.infinity,
|
||||
padding: const EdgeInsets.all(16),
|
||||
decoration: BoxDecoration(
|
||||
color: AppColors.primaryContainer.withOpacity(0.3),
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
border: Border.all(
|
||||
color: AppColors.primary.withOpacity(0.2), width: 1),
|
||||
),
|
||||
child: Row(children: [
|
||||
const Icon(Icons.info_outline,
|
||||
color: AppColors.primary, size: 18),
|
||||
const SizedBox(width: 12),
|
||||
Expanded(
|
||||
child: Text(
|
||||
'El PIN es la clave de acceso local a la app. '
|
||||
'Debe tener entre 4 y 6 dígitos.',
|
||||
style: appLabel(size: 12, color: AppColors.primary),
|
||||
),
|
||||
),
|
||||
]),
|
||||
),
|
||||
const SizedBox(height: 32),
|
||||
|
||||
// ── PIN actual ──────────────────────────────────────────────
|
||||
_seccionPin(
|
||||
label: 'PIN ACTUAL',
|
||||
ctrls: _ctrlActual,
|
||||
focus: _focusActual,
|
||||
),
|
||||
const SizedBox(height: 28),
|
||||
|
||||
// ── Nuevo PIN ───────────────────────────────────────────────
|
||||
_seccionPin(
|
||||
label: 'NUEVO PIN',
|
||||
ctrls: _ctrlNuevo,
|
||||
focus: _focusNuevo,
|
||||
),
|
||||
const SizedBox(height: 28),
|
||||
|
||||
// ── Confirmar PIN ───────────────────────────────────────────
|
||||
_seccionPin(
|
||||
label: 'CONFIRMAR NUEVO PIN',
|
||||
ctrls: _ctrlConfirm,
|
||||
focus: _focusConfirm,
|
||||
),
|
||||
const SizedBox(height: 40),
|
||||
|
||||
// ── Botón guardar ───────────────────────────────────────────
|
||||
SizedBox(
|
||||
width: double.infinity,
|
||||
child: ElevatedButton(
|
||||
onPressed: (todosCompletos && !_guardando)
|
||||
? _guardar
|
||||
: null,
|
||||
style: ElevatedButton.styleFrom(
|
||||
primary: AppColors.primary,
|
||||
onPrimary: AppColors.primaryContainer,
|
||||
padding: const EdgeInsets.symmetric(vertical: 16),
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(12)),
|
||||
elevation: 0,
|
||||
),
|
||||
child: _guardando
|
||||
? const SizedBox(
|
||||
width: 20, height: 20,
|
||||
child: CircularProgressIndicator(
|
||||
strokeWidth: 2,
|
||||
color: AppColors.primaryContainer))
|
||||
: Text('GUARDAR NUEVO PIN',
|
||||
style: appLabel(
|
||||
size: 13,
|
||||
weight: FontWeight.bold,
|
||||
color: todosCompletos
|
||||
? AppColors.primaryContainer
|
||||
: AppColors.onSurfaceVariant,
|
||||
spacing: 1.5)),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
|
||||
// ── Limpiar ─────────────────────────────────────────────────
|
||||
SizedBox(
|
||||
width: double.infinity,
|
||||
child: TextButton.icon(
|
||||
onPressed: _limpiarTodo,
|
||||
icon: const Icon(Icons.backspace_outlined,
|
||||
size: 16, color: AppColors.onSurfaceVariant),
|
||||
label: Text('Limpiar campos',
|
||||
style: appLabel(
|
||||
size: 13, color: AppColors.onSurfaceVariant)),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
// ── Sección de cajas PIN ───────────────────────────────────────────────────
|
||||
Widget _seccionPin({
|
||||
required String label,
|
||||
required List<TextEditingController> ctrls,
|
||||
required List<FocusNode> focus,
|
||||
}) =>
|
||||
Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
|
||||
Text(label,
|
||||
style: appLabel(
|
||||
size: 10,
|
||||
weight: FontWeight.bold,
|
||||
color: AppColors.onSurfaceVariant,
|
||||
spacing: 2.0)),
|
||||
const SizedBox(height: 14),
|
||||
Row(
|
||||
mainAxisAlignment: MainAxisAlignment.start,
|
||||
children: List.generate(
|
||||
_pinLen,
|
||||
(i) => Padding(
|
||||
padding: const EdgeInsets.only(right: 10),
|
||||
child: RawKeyboardListener(
|
||||
focusNode: FocusNode(),
|
||||
onKey: (e) => _onKey(ctrls, focus, i, e),
|
||||
child: SizedBox(
|
||||
width: 44,
|
||||
child: TextFormField(
|
||||
controller: ctrls[i],
|
||||
focusNode: focus[i],
|
||||
textAlign: TextAlign.center,
|
||||
keyboardType: TextInputType.number,
|
||||
obscureText: true,
|
||||
maxLength: 1,
|
||||
inputFormatters: [FilteringTextInputFormatter.digitsOnly],
|
||||
style: appHeadline(
|
||||
size: 20, color: AppColors.primary),
|
||||
decoration: InputDecoration(
|
||||
counterText: '',
|
||||
contentPadding:
|
||||
const EdgeInsets.symmetric(vertical: 14),
|
||||
enabledBorder: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
borderSide: BorderSide(
|
||||
color: ctrls[i].text.isNotEmpty
|
||||
? AppColors.primary
|
||||
: AppColors.outlineVariant,
|
||||
width: ctrls[i].text.isNotEmpty ? 2 : 1,
|
||||
),
|
||||
),
|
||||
focusedBorder: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
borderSide: const BorderSide(
|
||||
color: AppColors.primary, width: 2),
|
||||
),
|
||||
filled: true,
|
||||
fillColor: ctrls[i].text.isNotEmpty
|
||||
? AppColors.primaryContainer.withOpacity(0.3)
|
||||
: AppColors.surfaceHighest,
|
||||
),
|
||||
onChanged: (v) => _onDigit(ctrls, focus, i, v),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
]);
|
||||
}
|
||||
Reference in New Issue
Block a user