181186 - Criar PDV Android para rodar em maquinas P.O.S.
This commit is contained in:
commit
c9983cbad5
204 files changed
+11453
No files matched your search
@@ -0,0 +1,207 @@
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
import 'dart:developer' as developer;
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:http/http.dart' as http;
|
||||
|
||||
import '../../core/storage/secure_session_storage.dart';
|
||||
import '../../domain/entities/app_settings.dart';
|
||||
import '../../domain/entities/app_session.dart';
|
||||
import '../../domain/entities/pos_device.dart';
|
||||
import '../../domain/repositories/auth_repository.dart';
|
||||
import '../datasources/remote/odoo_api_uri_builder.dart';
|
||||
|
||||
class OdooAuthRepository implements AuthRepository {
|
||||
OdooAuthRepository({
|
||||
required SecureSessionStorage sessionStorage,
|
||||
http.Client? client,
|
||||
}) : _sessionStorage = sessionStorage,
|
||||
_client = client ?? http.Client();
|
||||
|
||||
static const _requestTimeout = Duration(seconds: 60);
|
||||
final SecureSessionStorage _sessionStorage;
|
||||
final http.Client _client;
|
||||
Uri? _activeServerUri;
|
||||
bool _isAuthenticated = false;
|
||||
AppSession? _currentSession;
|
||||
|
||||
@override
|
||||
bool get isAuthenticated => _isAuthenticated;
|
||||
|
||||
@override
|
||||
AppSession? get currentSession => _currentSession;
|
||||
|
||||
@override
|
||||
Future<AppSession> authenticate({
|
||||
required String username,
|
||||
required String password,
|
||||
required AppSettings settings,
|
||||
required PosDevice device,
|
||||
required String appVersion,
|
||||
}) async {
|
||||
if (await _sessionStorage.readCookie() != null) {
|
||||
await logout();
|
||||
}
|
||||
_isAuthenticated = false;
|
||||
_currentSession = null;
|
||||
final serverUri = Uri.parse(settings.serverUrl);
|
||||
final endpoint = OdooApiUriBuilder.endpoint(serverUri, '/pdv_pos/logar');
|
||||
final response = await _sendPost(
|
||||
endpoint,
|
||||
body: {
|
||||
'cnpj': settings.companyIdentifier,
|
||||
'username': username,
|
||||
'password': password,
|
||||
'platform': device.platform,
|
||||
if (device.serial != null) 'serial': device.serial!,
|
||||
if (device.model != null) 'model': device.model!,
|
||||
if (device.brand != null) 'brand': device.brand!,
|
||||
'version': appVersion,
|
||||
},
|
||||
);
|
||||
|
||||
final payload = _decodeResponse(response);
|
||||
if (payload['status'] != 'ok') {
|
||||
final message = payload['message'];
|
||||
throw AuthUnavailableException(
|
||||
message is String
|
||||
? message
|
||||
: 'Não foi possível autenticar no servidor.',
|
||||
);
|
||||
}
|
||||
|
||||
final cookie = _sessionCookie(response.headers['set-cookie']);
|
||||
final sessionId = payload['session_id'];
|
||||
if (cookie == null || sessionId is! String || sessionId.isEmpty) {
|
||||
throw const AuthUnavailableException(
|
||||
'O servidor não iniciou uma sessão segura para o PDV.',
|
||||
);
|
||||
}
|
||||
|
||||
await _sessionStorage.writeSession(
|
||||
cookie: cookie,
|
||||
serverUrl: settings.serverUrl,
|
||||
sessionId: sessionId,
|
||||
);
|
||||
final user = payload['user'];
|
||||
final userId = user is Map ? user['id'] : null;
|
||||
if (userId is! num) {
|
||||
await _sessionStorage.clearCookie();
|
||||
throw const AuthUnavailableException(
|
||||
'O servidor não retornou os dados do operador.',
|
||||
);
|
||||
}
|
||||
final companyIdValue = payload['company_id'];
|
||||
final companyNameValue = payload['company_name'];
|
||||
_currentSession = AppSession(
|
||||
userId: userId.toInt(),
|
||||
userName: user['name'] is String ? user['name'] as String : username,
|
||||
companyId: companyIdValue is num ? companyIdValue.toInt() : null,
|
||||
companyName: companyNameValue is String ? companyNameValue : null,
|
||||
);
|
||||
_activeServerUri = serverUri;
|
||||
_isAuthenticated = true;
|
||||
return _currentSession!;
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> logout() async {
|
||||
var serverUri = _activeServerUri;
|
||||
final cookie = await _sessionStorage.readCookie();
|
||||
final sessionId = await _sessionStorage.readSessionId();
|
||||
if (serverUri == null) {
|
||||
final storedServerUrl = await _sessionStorage.readServerUrl();
|
||||
if (storedServerUrl != null) serverUri = Uri.tryParse(storedServerUrl);
|
||||
}
|
||||
try {
|
||||
if (serverUri != null && cookie != null && sessionId != null) {
|
||||
await _sendPost(
|
||||
OdooApiUriBuilder.endpoint(serverUri, '/pdv_pos/logout'),
|
||||
body: {'session_id': sessionId},
|
||||
cookie: cookie,
|
||||
);
|
||||
}
|
||||
} catch (_) {
|
||||
// Local credentials are cleared even if the server cannot be reached.
|
||||
} finally {
|
||||
await _sessionStorage.clearCookie();
|
||||
_activeServerUri = null;
|
||||
_isAuthenticated = false;
|
||||
_currentSession = null;
|
||||
}
|
||||
}
|
||||
|
||||
Future<http.Response> _sendPost(
|
||||
Uri uri, {
|
||||
required Map<String, String> body,
|
||||
String? cookie,
|
||||
}) async {
|
||||
final request = http.Request('POST', uri)
|
||||
..followRedirects = false
|
||||
..headers['Accept'] = 'application/json'
|
||||
..headers['Content-Type'] =
|
||||
'application/x-www-form-urlencoded; charset=utf-8'
|
||||
..body = Uri(queryParameters: body).query;
|
||||
if (cookie != null) request.headers['Cookie'] = cookie;
|
||||
developer.log('Enviando chamada HTTP ${request.method} ${uri.path}.',
|
||||
name: 'pdv.auth');
|
||||
|
||||
try {
|
||||
final response = await _client
|
||||
.send(request)
|
||||
.then(http.Response.fromStream)
|
||||
.timeout(_requestTimeout);
|
||||
if (response.statusCode != HttpStatus.ok) {
|
||||
developer.log(
|
||||
'Resposta HTTP ${response.statusCode} em ${uri.path}.',
|
||||
name: 'pdv.auth',
|
||||
);
|
||||
throw const AuthUnavailableException(
|
||||
'O servidor não conseguiu processar a solicitação do PDV.',
|
||||
);
|
||||
}
|
||||
return response;
|
||||
} on TimeoutException {
|
||||
developer.log('Timeout na chamada HTTP ${uri.path}.', name: 'pdv.auth');
|
||||
throw const AuthUnavailableException(
|
||||
'Tempo esgotado ao comunicar com o servidor.',
|
||||
);
|
||||
} on SocketException {
|
||||
developer.log('Falha de socket na chamada HTTP ${uri.path}.',
|
||||
name: 'pdv.auth');
|
||||
throw const AuthUnavailableException(
|
||||
'Não foi possível alcançar o servidor.',
|
||||
);
|
||||
} on AuthUnavailableException {
|
||||
rethrow;
|
||||
} catch (error, stackTrace) {
|
||||
developer.log(
|
||||
'Falha HTTP ${uri.path}: ${error.runtimeType}.',
|
||||
name: 'pdv.auth',
|
||||
stackTrace: stackTrace,
|
||||
);
|
||||
throw const AuthUnavailableException(
|
||||
'Falha de comunicação com o servidor.',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Map<String, dynamic> _decodeResponse(http.Response response) {
|
||||
try {
|
||||
final decoded = jsonDecode(response.body);
|
||||
if (decoded is Map<String, dynamic>) return decoded;
|
||||
} on FormatException {
|
||||
// Mapped below to a safe protocol error.
|
||||
}
|
||||
throw const AuthUnavailableException(
|
||||
'O servidor retornou uma resposta inválida.',
|
||||
);
|
||||
}
|
||||
|
||||
String? _sessionCookie(String? setCookieHeader) {
|
||||
if (setCookieHeader == null) return null;
|
||||
final cookie = setCookieHeader.split(';').first.trim();
|
||||
return cookie.startsWith('sid=') && cookie.length > 4 ? cookie : null;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user