diff --git a/lib/core/services/api_service.dart b/lib/core/services/api_service.dart index 3ac2bb4..d9ff488 100644 --- a/lib/core/services/api_service.dart +++ b/lib/core/services/api_service.dart @@ -68,6 +68,9 @@ class ApiService { if (response.statusCode == 200) { return response; // return full http.Response, not Map + } else if (response.statusCode == 401) { + await clearLocalStorageAndRedirect(); + return http.Response('Forbidden', 401); } else if (response.statusCode == 403) { await clearLocalStorageAndRedirect(); return http.Response('Forbidden', 403); @@ -130,6 +133,7 @@ class ApiService { return response; } + Future> logoutUsingAPI(agentId) async { // print(_token); if (_token == null) { @@ -146,17 +150,56 @@ class ApiService { return response; } + // Future> _handleResponse(http.Response response) async { + // if (response.statusCode == 200) { + // return jsonDecode(response.body); + // } else if (response.statusCode == 401 || response.statusCode == 403) { + // await clearLocalStorageAndRedirect(); + // return {}; + // } else { + // throw Exception('Failed to load data'); + // } + // } + Future> _handleResponse(http.Response response) async { + Map body = {}; + + // 1. Try to parse JSON, but don't let a parse error stop the 401 check + try { + body = jsonDecode(response.body); + } catch (e) { + debugPrint("Could not parse JSON body: $e"); + } + + // 2. SUCCESS if (response.statusCode == 200) { - return jsonDecode(response.body); - } else if (response.statusCode == 401 || response.statusCode == 403) { + return body; + } + + // 3. UNAUTHORIZED / FORBIDDEN (The 401/403 Fix) + if ((response.statusCode == 401 && body['status'] == 401) || (response.statusCode == 403 && body['status'] == 403)) { + + // Perform cleanup + await AuthService.clearToken(); + + // Redirect using global appRouter (avoids context errors) + context.go(AppRoutes.login); + + // Return a structured error so the UI knows why it failed + return {'status': 401, 'message': 'Session expired or invalid'}; + } + + if (response.statusCode == 401 || response.statusCode == 403) { await clearLocalStorageAndRedirect(); return {}; - } else { - throw Exception('Failed to load data'); } + + // 4. ALL OTHER ERRORS + throw Exception('Server Error: ${response.statusCode}'); + } + Future> CheckDuplicate( BuildContext context, String value,