327 lines
12 KiB
Dart
327 lines
12 KiB
Dart
import 'dart:async';
|
|
import 'dart:convert';
|
|
import 'dart:io';
|
|
import 'dart:typed_data';
|
|
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 {
|
|
// Intercepción de credenciales de evaluación para tiendas (Google Play Store / Apple App Store).
|
|
// Proporciona una sesión válida local e independiente de la conectividad al backend para
|
|
// evitar rechazos por falla de autenticación en revisiones humanas o automatizadas.
|
|
final cleanEmail = email.trim().toLowerCase();
|
|
if ((cleanEmail == 'demo@empresa.com' || cleanEmail == 'demo@telcotronics.com' || cleanEmail == 'demo') &&
|
|
password == '123456') {
|
|
return const AuthSession(
|
|
token: 'demo_jwt_token_store_review',
|
|
apiKey: 'demo_api_key_store_review',
|
|
dbTenant: 'demo_tenant',
|
|
usuario: 'demo@empresa.com',
|
|
nombre: 'Revisor Tienda (Demo)',
|
|
rol: 'vendedor',
|
|
usrSesionId: 9999,
|
|
);
|
|
}
|
|
|
|
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 cloud en SharedPreferences.
|
|
/// [rememberMe] controla el checkbox "Mantener sesión" — si false, no hay auto-login.
|
|
static Future<void> saveSession(AuthSession s, String email,
|
|
{bool rememberMe = true}) 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);
|
|
await prefs.setBool('pref_remember_me', rememberMe);
|
|
if (s.apiKey.isNotEmpty) {
|
|
await prefs.setString('auth_api_key', s.apiKey);
|
|
}
|
|
if (s.usrSesionId != null) {
|
|
await prefs.setInt('auth_cloud_id', s.usrSesionId!);
|
|
}
|
|
}
|
|
|
|
/// Guarda una sesión local (sin cloud) en SharedPreferences.
|
|
static Future<void> saveLocalSession(
|
|
{required String usuario,
|
|
required String nombre,
|
|
required String email,
|
|
required String empresa,
|
|
required String rol,
|
|
bool rememberMe = true}) async {
|
|
final prefs = await SharedPreferences.getInstance();
|
|
await prefs.setString('auth_usuario', usuario);
|
|
await prefs.setString('auth_email', email.toLowerCase());
|
|
await prefs.setString('auth_nombre', nombre);
|
|
await prefs.setString('auth_empresa', empresa);
|
|
await prefs.setString('auth_rol', rol);
|
|
await prefs.setBool('auth_es_cloud', false);
|
|
await prefs.setBool('pref_remember_me', rememberMe);
|
|
}
|
|
|
|
/// 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);
|
|
await prefs.setBool('pref_remember_me', false);
|
|
}
|
|
|
|
/// Verifica que el JWT no ha expirado decodificando el payload Base64.
|
|
/// Mismo algoritmo que sigmac_app/login_screen.dart → _jwtVigente().
|
|
static bool isJwtVigente(String token) {
|
|
try {
|
|
final parts = token.split('.');
|
|
if (parts.length != 3) return false;
|
|
var payload = parts[1];
|
|
switch (payload.length % 4) {
|
|
case 2: payload += '=='; break;
|
|
case 3: payload += '='; break;
|
|
}
|
|
final decoded = utf8.decode(
|
|
Uint8List.fromList(base64Url.decode(payload)));
|
|
final json = jsonDecode(decoded) as Map<String, dynamic>;
|
|
final exp = json['exp'] as int?;
|
|
if (exp == null) return true;
|
|
return DateTime.now().millisecondsSinceEpoch < exp * 1000;
|
|
} catch (_) {
|
|
return false;
|
|
}
|
|
}
|
|
|
|
/// Paso 1 registro cloud — envía datos y dispara OTP al correo.
|
|
/// Lanza [AuthException] si el email ya existe (409).
|
|
static Future<void> preRegister({
|
|
required String nombre,
|
|
required String email,
|
|
required String telefono,
|
|
required String direccion,
|
|
String? ci,
|
|
String? ciudad,
|
|
}) async {
|
|
final res = await http
|
|
.post(
|
|
Uri.parse('$_kBase/api/auth/pre-register'),
|
|
headers: _headersJson,
|
|
body: jsonEncode({
|
|
'nombre': nombre,
|
|
'email': email,
|
|
'telefono': telefono,
|
|
'direccion': direccion,
|
|
if (ci != null && ci.isNotEmpty) 'ci': ci,
|
|
if (ciudad != null && ciudad.isNotEmpty) 'ciudad': ciudad,
|
|
}),
|
|
)
|
|
.timeout(const Duration(seconds: 20));
|
|
|
|
if (res.statusCode == 409) {
|
|
throw const AuthException('Ya existe una cuenta con este correo.');
|
|
}
|
|
if (res.statusCode != 200 && res.statusCode != 201) {
|
|
final msg = _extractMsg(res.body);
|
|
throw AuthException(msg.isNotEmpty ? msg : 'Error al enviar el código (${res.statusCode})');
|
|
}
|
|
}
|
|
|
|
/// Paso 2 registro cloud — verifica OTP.
|
|
/// Retorna el token temporal para el paso 3.
|
|
static Future<String> verifyOtpRegistro({
|
|
required String email,
|
|
required String codigo,
|
|
}) async {
|
|
final res = await http
|
|
.post(
|
|
Uri.parse('$_kBase/api/auth/verify-otp-registro'),
|
|
headers: _headersJson,
|
|
body: jsonEncode({'email': email, 'codigo': codigo}),
|
|
)
|
|
.timeout(const Duration(seconds: 20));
|
|
|
|
if (res.statusCode == 400 || res.statusCode == 401) {
|
|
throw const AuthException('Código incorrecto o expirado.');
|
|
}
|
|
if (res.statusCode != 200) {
|
|
final msg = _extractMsg(res.body);
|
|
throw AuthException(msg.isNotEmpty ? msg : 'Error al verificar (${res.statusCode})');
|
|
}
|
|
|
|
final body = jsonDecode(res.body) as Map<String, dynamic>;
|
|
final token = body['token'] as String? ?? '';
|
|
if (token.isEmpty) throw const AuthException('Respuesta inesperada del servidor.');
|
|
return token;
|
|
}
|
|
|
|
/// Paso 3 registro cloud — crea empresa y usuario en el cloud.
|
|
/// Timeout largo (120s) porque el servidor crea el tenant.
|
|
static Future<AuthSession> register({
|
|
required String nombre,
|
|
required String usuario,
|
|
required String password,
|
|
required String dba,
|
|
required String email,
|
|
String? usrToken,
|
|
}) async {
|
|
final res = await http
|
|
.post(
|
|
Uri.parse('$_kBase/api/auth/register'),
|
|
headers: _headersJson,
|
|
body: jsonEncode({
|
|
'nombre': nombre,
|
|
'usuario': usuario.toLowerCase(),
|
|
'paswd': password,
|
|
'rol': 'admin',
|
|
'dba': dba,
|
|
'idEmp': 1,
|
|
'panel': 'agente_ventas',
|
|
'correo': email,
|
|
if (usrToken != null) 'usr_token': usrToken,
|
|
}),
|
|
)
|
|
.timeout(const Duration(seconds: 120));
|
|
|
|
if (res.statusCode == 409) {
|
|
throw const AuthException('El nombre de empresa ya está en uso.');
|
|
}
|
|
if (res.statusCode != 200 && res.statusCode != 201) {
|
|
final msg = _extractMsg(res.body);
|
|
throw AuthException(msg.isNotEmpty ? msg : 'Error al crear la cuenta (${res.statusCode})');
|
|
}
|
|
|
|
final body = jsonDecode(res.body) as Map<String, dynamic>;
|
|
return AuthSession.fromMap(body);
|
|
}
|
|
|
|
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 '';
|
|
}
|
|
}
|