199 lines
8.3 KiB
Dart
199 lines
8.3 KiB
Dart
import 'dart:convert';
|
|
import 'package:http/http.dart' as http;
|
|
import 'package:shared_preferences/shared_preferences.dart';
|
|
import '../db/database_helper.dart';
|
|
|
|
/// Flujo de autenticación WebControl (2 pasos):
|
|
///
|
|
/// Paso 1 — POST /api/auth/empresas { email, paswd }
|
|
/// → { success, usuario, empresas:[{dba,nombre,rol}], unica }
|
|
///
|
|
/// Paso 2 — POST /api/auth/login { email, paswd, dba }
|
|
/// → { success, token, apiKey, db_tenant, usuario:{id,nombre,usuario,rol} }
|
|
///
|
|
/// Uso posterior (llamadas a api.telcotronics.com):
|
|
/// final h = await ApiAuthService.instance.getCentinelHeaders();
|
|
class ApiAuthService {
|
|
static const _base = 'https://api.siax-system.net';
|
|
|
|
static const _keyToken = 'webcontrol_token';
|
|
static const _keyApiKey = 'centinel_api_key';
|
|
static const _keyTenant = 'centinel_tenant';
|
|
static const _keyNombre = 'operador_nombre';
|
|
static const _keyUsuario = 'operador_usuario';
|
|
// Comentario explicativo: Clave de preferencias para almacenar el rol del operador
|
|
static const _keyRol = 'operador_rol';
|
|
|
|
ApiAuthService._();
|
|
static final ApiAuthService instance = ApiAuthService._();
|
|
|
|
// Comentario explicativo: Verificación de credenciales de evaluación demo fijas.
|
|
// Permite acceso inmediato a los revisores de Google Play y Apple App Store
|
|
// sin depender de conectividad, servidores externos ni SMS/WhatsApp.
|
|
bool isDemoCredentials(String email, String paswd) {
|
|
final e = email.trim().toLowerCase();
|
|
final p = paswd.trim();
|
|
return (e == 'demo@empresa.com' || e == 'demo@siax-system.net' || e == 'demo') && p == '123456';
|
|
}
|
|
|
|
// ── Paso 1: obtener empresas del usuario ──────────────────────
|
|
Future<List<Map<String, dynamic>>?> getEmpresas(
|
|
String email, String paswd) async {
|
|
// Comentario explicativo: Retorno inmediato de empresa demo para revisores de tienda
|
|
if (isDemoCredentials(email, paswd)) {
|
|
return [
|
|
{'dba': 'TELCOTRONICS_DEMO', 'nombre': 'Empresa Demo (Revisión)', 'rol': 'OPERADOR'}
|
|
];
|
|
}
|
|
|
|
try {
|
|
final resp = await http.post(
|
|
Uri.parse('$_base/api/auth/empresas'),
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
'accept': 'application/json',
|
|
},
|
|
body: jsonEncode({'email': email, 'paswd': paswd}),
|
|
).timeout(const Duration(seconds: 10));
|
|
|
|
if (resp.statusCode != 200) return null;
|
|
final body = jsonDecode(resp.body) as Map<String, dynamic>;
|
|
if (body['success'] != true) return null;
|
|
|
|
return List<Map<String, dynamic>>.from(
|
|
body['empresas'] as List? ?? []);
|
|
} catch (_) {
|
|
return null;
|
|
}
|
|
}
|
|
|
|
// ── Paso 2: login completo con dba ────────────────────────────
|
|
Future<bool> login(String email, String paswd, {String? dba}) async {
|
|
// Comentario explicativo: Intercepción de cuenta demo para evaluación de tienda.
|
|
// Si el revisor introduce las credenciales demo fijas, se crea la sesión local
|
|
// y se puebla la base de datos SQLite con datos de prueba realistas sin depender de la red.
|
|
if (isDemoCredentials(email, paswd)) {
|
|
final prefs = await SharedPreferences.getInstance();
|
|
await prefs.setString(_keyToken, 'demo_jwt_token_tienda_2026');
|
|
await prefs.setString(_keyApiKey, 'demo_api_key_evaluador');
|
|
await prefs.setString(_keyTenant, 'TELCOTRONICS_DEMO');
|
|
await prefs.setString(_keyNombre, 'Operador Demo (Tienda)');
|
|
await prefs.setString(_keyUsuario, email.trim().toLowerCase());
|
|
// Comentario explicativo: Asigna rol de supervisor al operador de prueba
|
|
await prefs.setString(_keyRol, 'Supervisor de Central (Demo)');
|
|
await DatabaseHelper.instance.poblarDatosDemo(force: true);
|
|
return true;
|
|
}
|
|
|
|
try {
|
|
// Paso 1: obtener dba si no se pasó
|
|
String? dbaTenant = dba;
|
|
if (dbaTenant == null) {
|
|
final empresas = await getEmpresas(email, paswd);
|
|
if (empresas == null || empresas.isEmpty) return false;
|
|
dbaTenant = empresas.first['dba'] as String?;
|
|
if (dbaTenant == null) return false;
|
|
}
|
|
|
|
// Paso 2: login real
|
|
final resp = await http.post(
|
|
Uri.parse('$_base/api/auth/login'),
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
'accept': 'application/json',
|
|
},
|
|
body: jsonEncode({'email': email, 'paswd': paswd, 'dba': dbaTenant}),
|
|
).timeout(const Duration(seconds: 10));
|
|
|
|
if (resp.statusCode != 200) return false;
|
|
|
|
final body = jsonDecode(resp.body) as Map<String, dynamic>;
|
|
if (body['success'] != true) return false;
|
|
|
|
final token = body['token'] as String?;
|
|
final apiKey = body['apiKey'] as String?;
|
|
final tenant = body['db_tenant'] as String?;
|
|
final usr = body['usuario'] as Map<String, dynamic>?;
|
|
final nombre = usr?['nombre'] as String? ?? email;
|
|
final usuario = usr?['usuario'] as String? ?? email;
|
|
|
|
final rol = usr?['rol'] as String? ?? 'Operador';
|
|
|
|
if (apiKey == null || tenant == null) return false;
|
|
|
|
final prefs = await SharedPreferences.getInstance();
|
|
if (token != null) await prefs.setString(_keyToken, token);
|
|
await prefs.setString(_keyApiKey, apiKey);
|
|
await prefs.setString(_keyTenant, tenant);
|
|
await prefs.setString(_keyNombre, nombre);
|
|
await prefs.setString(_keyUsuario, usuario);
|
|
// Comentario explicativo: Almacena el rol del usuario en la sesión
|
|
await prefs.setString(_keyRol, rol);
|
|
return true;
|
|
} catch (_) {
|
|
return false;
|
|
}
|
|
}
|
|
|
|
// ── Logout ────────────────────────────────────────────────────
|
|
Future<void> logout() async {
|
|
final prefs = await SharedPreferences.getInstance();
|
|
await prefs.remove(_keyToken);
|
|
await prefs.remove(_keyApiKey);
|
|
await prefs.remove(_keyTenant);
|
|
await prefs.remove(_keyNombre);
|
|
await prefs.remove(_keyUsuario);
|
|
// Comentario explicativo: Elimina el rol almacenado al cerrar sesión
|
|
await prefs.remove(_keyRol);
|
|
}
|
|
|
|
// ── Estado ────────────────────────────────────────────────────
|
|
Future<bool> isAuthenticated() async {
|
|
final prefs = await SharedPreferences.getInstance();
|
|
final apiKey = prefs.getString(_keyApiKey);
|
|
return apiKey != null && apiKey.isNotEmpty;
|
|
}
|
|
|
|
// ── Headers para api.telcotronics.com ─────────────────────────
|
|
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',
|
|
'accept': 'application/json',
|
|
'x-api-key': apiKey,
|
|
'x-database': tenant ?? '',
|
|
};
|
|
}
|
|
|
|
// ── Getters ───────────────────────────────────────────────────
|
|
Future<String?> getNombre() async =>
|
|
(await SharedPreferences.getInstance()).getString(_keyNombre);
|
|
|
|
Future<String?> getUsuario() async =>
|
|
(await SharedPreferences.getInstance()).getString(_keyUsuario);
|
|
|
|
Future<String?> getApiKey() async =>
|
|
(await SharedPreferences.getInstance()).getString(_keyApiKey);
|
|
|
|
Future<String?> getToken() async =>
|
|
(await SharedPreferences.getInstance()).getString(_keyToken);
|
|
|
|
// Comentario explicativo: Retorna true si la sesión activa actual corresponde a la cuenta demo de evaluación
|
|
Future<bool> isModoDemo() async {
|
|
final prefs = await SharedPreferences.getInstance();
|
|
final token = prefs.getString(_keyToken);
|
|
return token == 'demo_jwt_token_tienda_2026';
|
|
}
|
|
|
|
// Comentario explicativo: Retorna el rol del operador autenticado o un valor por defecto seguro
|
|
Future<String?> getRol() async {
|
|
final prefs = await SharedPreferences.getInstance();
|
|
final rol = prefs.getString(_keyRol);
|
|
if (rol != null) return rol;
|
|
return (await isModoDemo()) ? 'Supervisor de Central (Demo)' : 'Operador';
|
|
}
|
|
}
|