auth_service.dart: - URL corregida: https://api.siax-system.net (no la IP interna) - Campo contraseña corregido: paswd (no password) - Eliminado paso empresas innecesario — login directo igual que sigmac_app - Sesión guardada en SharedPreferences con mismas claves que sigmac_app - AuthSession.fromMap idéntico al de CentralCloudApi.AuthSession cloud_sync_service.dart (nuevo): - Base URL: https://api-gateway-cloud.telcotronics.net - Solo x-api-key en headers (NO Bearer JWT) — igual que GatewayCloudApi - Items: GET /api/items/sync con paginación por offset - Clientes: GET /api/clientes/verClientesJsonApp - Campos reales: codigo_prdcto, detalle_prdcto, client_rucCed, etc. app_provider.dart: - login() llama AuthService.login() con la firma correcta - Después de auth exitosa sincroniza items y clientes del cloud - Preserva precios locales en upsert de productos (API no devuelve precios) - Fallback offline mantiene credenciales SQLite locales - logout() borra SharedPreferences Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
164 lines
5.6 KiB
Dart
164 lines
5.6 KiB
Dart
import 'dart:async';
|
|
import 'dart:convert';
|
|
import 'dart:io';
|
|
import 'package:http/http.dart' as http;
|
|
import 'package:shared_preferences/shared_preferences.dart';
|
|
|
|
// URL pública de API-SIGMA-WEBCONTROL — igual que en sigmac_app/CentralCloudApi
|
|
const _kBase = 'https://api.siax-system.net';
|
|
|
|
// ── Modelos ────────────────────────────────────────────────────────────────
|
|
|
|
class AuthSession {
|
|
final String token;
|
|
final String apiKey;
|
|
final String dbTenant;
|
|
final String usuario;
|
|
final String nombre;
|
|
final String rol;
|
|
final int? usrSesionId;
|
|
|
|
const AuthSession({
|
|
required this.token,
|
|
required this.apiKey,
|
|
required this.dbTenant,
|
|
required this.usuario,
|
|
required this.nombre,
|
|
required this.rol,
|
|
this.usrSesionId,
|
|
});
|
|
|
|
// Mismo parsing que sigmac_app/central_cloud_api.dart → AuthSession.fromMap()
|
|
factory AuthSession.fromMap(Map<String, dynamic> m) {
|
|
final d = m['data'] is Map<String, dynamic>
|
|
? m['data'] as Map<String, dynamic>
|
|
: m;
|
|
|
|
final rawUsuario = d['usuario'];
|
|
final usuarioMap = rawUsuario is Map<String, dynamic> ? rawUsuario : null;
|
|
|
|
final usuarioStr = rawUsuario is String
|
|
? rawUsuario
|
|
: (usuarioMap?['usuario'] as String?) ?? '';
|
|
|
|
final nombre = d['nombre'] as String? ?? usuarioMap?['nombre'] as String? ?? '';
|
|
final rol = d['rol'] as String? ?? usuarioMap?['rol'] as String? ?? '';
|
|
final rawId = d['usrSesion_ID'] ?? d['id'] ?? d['userId']
|
|
?? usuarioMap?['id'] ?? usuarioMap?['id_usr'];
|
|
|
|
return AuthSession(
|
|
token: (d['token'] as String?) ?? (d['accessToken'] as String?) ?? '',
|
|
apiKey: (d['apiKey'] as String?) ?? '',
|
|
dbTenant: (d['db_tenant'] as String?) ?? (d['dba'] as String?) ?? '',
|
|
usuario: usuarioStr,
|
|
nombre: nombre,
|
|
rol: rol,
|
|
usrSesionId: rawId is int ? rawId : int.tryParse(rawId?.toString() ?? ''),
|
|
);
|
|
}
|
|
}
|
|
|
|
class AuthException implements Exception {
|
|
final String message;
|
|
const AuthException(this.message);
|
|
@override
|
|
String toString() => message;
|
|
}
|
|
|
|
// ── Servicio ───────────────────────────────────────────────────────────────
|
|
|
|
class AuthService {
|
|
static const _headersJson = {
|
|
'accept': 'application/json',
|
|
'Content-Type': 'application/json',
|
|
};
|
|
|
|
/// Login contra API-SIGMA-WEBCONTROL.
|
|
/// Endpoint: POST https://api.siax-system.net/api/auth/login
|
|
/// Body: {email, paswd} ← campo es `paswd`, NO `password`
|
|
///
|
|
/// Retorna [AuthSession] si el login fue exitoso.
|
|
/// Retorna `null` si no hay conexión (fallback a modo offline).
|
|
/// Lanza [AuthException] si las credenciales son incorrectas.
|
|
static Future<AuthSession?> login(String email, String password) async {
|
|
try {
|
|
final res = await http
|
|
.post(
|
|
Uri.parse('$_kBase/api/auth/login'),
|
|
headers: _headersJson,
|
|
body: jsonEncode({'email': email, 'paswd': password}),
|
|
)
|
|
.timeout(const Duration(seconds: 15));
|
|
|
|
if (res.statusCode == 401 || res.statusCode == 400) {
|
|
throw const AuthException('Usuario o contraseña incorrectos');
|
|
}
|
|
if (res.statusCode >= 500) {
|
|
throw AuthException('Error del servidor (${res.statusCode})');
|
|
}
|
|
if (res.statusCode != 200) {
|
|
final msg = _extractMsg(res.body);
|
|
throw AuthException(msg.isNotEmpty ? msg : 'Respuesta inesperada (${res.statusCode})');
|
|
}
|
|
|
|
final body = jsonDecode(res.body);
|
|
final map = body is Map<String, dynamic> ? body : <String, dynamic>{};
|
|
return AuthSession.fromMap(map);
|
|
} on AuthException {
|
|
rethrow;
|
|
} on SocketException {
|
|
return null; // sin red → fallback offline
|
|
} on TimeoutException {
|
|
return null;
|
|
} on HttpException {
|
|
return null;
|
|
} catch (_) {
|
|
return null;
|
|
}
|
|
}
|
|
|
|
/// Guarda la sesión en SharedPreferences.
|
|
/// Mismas claves que usa sigmac_app para compatibilidad futura.
|
|
static Future<void> saveSession(AuthSession s, String email) async {
|
|
final prefs = await SharedPreferences.getInstance();
|
|
await prefs.setString('auth_token', s.token);
|
|
await prefs.setString('auth_usuario', s.usuario);
|
|
await prefs.setString('auth_email', email.toLowerCase());
|
|
await prefs.setString('auth_nombre', s.nombre);
|
|
await prefs.setString('auth_rol', s.rol);
|
|
await prefs.setString('auth_empresa', s.dbTenant);
|
|
await prefs.setBool('auth_es_cloud', true);
|
|
if (s.apiKey.isNotEmpty) {
|
|
await prefs.setString('auth_api_key', s.apiKey);
|
|
}
|
|
if (s.usrSesionId != null) {
|
|
await prefs.setInt('auth_cloud_id', s.usrSesionId!);
|
|
}
|
|
}
|
|
|
|
/// Borra la sesión de SharedPreferences al hacer logout.
|
|
static Future<void> clearSession() async {
|
|
final prefs = await SharedPreferences.getInstance();
|
|
await prefs.remove('auth_token');
|
|
await prefs.remove('auth_usuario');
|
|
await prefs.remove('auth_email');
|
|
await prefs.remove('auth_nombre');
|
|
await prefs.remove('auth_rol');
|
|
await prefs.remove('auth_api_key');
|
|
await prefs.remove('auth_empresa');
|
|
await prefs.setBool('auth_es_cloud', false);
|
|
}
|
|
|
|
static String _extractMsg(String body) {
|
|
try {
|
|
final j = jsonDecode(body);
|
|
if (j is Map) {
|
|
for (final k in ['message', 'error', 'msg', 'detail']) {
|
|
if (j[k] is String && (j[k] as String).isNotEmpty) return j[k] as String;
|
|
}
|
|
}
|
|
} catch (_) {}
|
|
return '';
|
|
}
|
|
}
|