session issue fix

This commit is contained in:
Surendiran 2026-01-06 12:49:10 +05:30
parent 9635548e26
commit 1a7cec70cb
6 changed files with 68 additions and 77 deletions

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,4 @@
import 'package:flutter/material.dart';
final GlobalKey<NavigatorState> navigatorKey =
GlobalKey<NavigatorState>();

View File

@ -40,8 +40,10 @@ import '../../presentation/screens/staff/policy/policy.dart';
import '../../presentation/screens/staff/policy/policy_list.dart'; import '../../presentation/screens/staff/policy/policy_list.dart';
import '../../presentation/screens/staff/policy/policy_validation.dart'; import '../../presentation/screens/staff/policy/policy_validation.dart';
import '../../presentation/screens/staff/quotations/quotation.dart'; import '../../presentation/screens/staff/quotations/quotation.dart';
import '../config/navigation_service.dart';
final GoRouter appRouter = GoRouter( final GoRouter appRouter = GoRouter(
navigatorKey: navigatorKey,
initialLocation: AppRoutes.login, initialLocation: AppRoutes.login,
// initialLocation: AppRoutes.home, // initialLocation: AppRoutes.home,
routes: [ routes: [

View File

@ -13,27 +13,47 @@ import '../config/env.dart';
import 'package:universal_html/html.dart' as html; import 'package:universal_html/html.dart' as html;
import 'package:http/http.dart' as http; import 'package:http/http.dart' as http;
import '../config/navigation_service.dart';
import '../routing/app_router.dart';
import '../routing/routes.dart'; import '../routing/routes.dart';
class ApiService { class ApiService {
late final BuildContext context; late final BuildContext context;
String? _token; String? _token;
bool _isLoggingOut = false;
Future<void> clearLocalStorageAndRedirect() async {
if (_isLoggingOut) return;
_isLoggingOut = true;
await AuthService.clearToken();
final ctx = navigatorKey.currentContext;
if (ctx != null) {
// ToastHelper.showErrorToast(ctx, 'Session expired');
ctx.go(AppRoutes.login);
} else {
// fallback (web-safe)
appRouter.go(AppRoutes.login);
}
}
Future<void> _initializeToken() async { Future<void> _initializeToken() async {
_token = await AuthService.getToken(); _token = await AuthService.getToken();
print("APISERTOKEN - $_token"); print("APISERTOKEN - $_token");
} }
Future<void> clearLocalStorageAndRedirect() async { // Future<void> clearLocalStorageAndRedirect() async {
// final prefs = await SharedPreferences.getInstance(); // // final prefs = await SharedPreferences.getInstance();
// await prefs.clear(); // // await prefs.clear();
// Assuming you have access to the context // // Assuming you have access to the context
ToastHelper.showErrorToast(context, 'Session Out'); // ToastHelper.showErrorToast(context, 'Session Out');
// Navigator.pushNamed(context, 'login'); // // Navigator.pushNamed(context, 'login');
AuthService.clearToken(); // AuthService.clearToken();
context.go(AppRoutes.login); // context.go(AppRoutes.login);
} // }
Future<Map<String, dynamic>> _makeGetRequest( Future<Map<String, dynamic>> _makeGetRequest(
Uri url, Uri url,
@ -49,18 +69,10 @@ class ApiService {
) async { ) async {
final response = await http.get(url, headers: headers); final response = await http.get(url, headers: headers);
if (response.statusCode == 200) { if (response.statusCode == 401 || response.statusCode == 403) {
return response; // return full http.Response, not Map
} else if (response.statusCode == 401) {
await clearLocalStorageAndRedirect(); await clearLocalStorageAndRedirect();
return http.Response('Forbidden', 401);
} else if (response.statusCode == 403) {
await clearLocalStorageAndRedirect();
return http.Response('Forbidden', 403);
} else {
ToastHelper.show('No File Found', Colors.red);
throw Exception('Failed request: ${response.statusCode}');
} }
return response;
} }
Future<Map<String, dynamic>> _makePostRequestJson( Future<Map<String, dynamic>> _makePostRequestJson(
@ -116,7 +128,7 @@ class ApiService {
return response; return response;
} }
Future<Map<String, dynamic>> logoutUsingAPI(agentId) async { Future<Map<String, dynamic>> logoutUsingAPI(BuildContext context) async {
// print(_token); // print(_token);
if (_token == null) { if (_token == null) {
await _initializeToken(); await _initializeToken();
@ -146,58 +158,24 @@ class ApiService {
Future<Map<String, dynamic>> _handleResponse(http.Response response) async { Future<Map<String, dynamic>> _handleResponse(http.Response response) async {
Map<String, dynamic> body = {}; Map<String, dynamic> body = {};
// 1. Try to parse JSON, but don't let a parse error stop the 401 check
try { try {
body = jsonDecode(response.body); body = jsonDecode(response.body);
} catch (e) { } catch (_) {}
debugPrint("Could not parse JSON body: $e");
}
// 2. SUCCESS
if (response.statusCode == 200) { if (response.statusCode == 200) {
return body; return body;
} }
// 3. UNAUTHORIZED / FORBIDDEN (The 401/403 Fix) if (response.statusCode == 401 || response.statusCode == 403) {
// if ((response.statusCode == 401 && body['status'] == 401) || await clearLocalStorageAndRedirect();
// (response.statusCode == 403 && body['status'] == 403)) { throw Exception('Session expired');
// // 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 {};
// }
final message = (body['message'] ?? body['error'] ?? '')
.toString()
.toLowerCase();
// 2 TOKEN / AUTH FAILURE (message OR status based)
final isAuthError =
response.statusCode == 401 ||
response.statusCode == 403 ||
message.contains('token required') ||
message.contains('invalid or expired token');
if (isAuthError) {
await clearLocalStorageAndRedirect(); // handles navigation internally
// Stop further execution
throw Exception('Authentication error');
} }
// 4. ALL OTHER ERRORS
throw Exception('Server Error: ${response.statusCode}'); throw Exception('Server Error: ${response.statusCode}');
} }
Future<Map<String, dynamic>> CheckDuplicate( Future<Map<String, dynamic>> CheckDuplicate(
BuildContext context, BuildContext context,
String value, String value,

View File

@ -2284,7 +2284,14 @@ Future<void> handleDashboardNavigation(
await prefs.setString('dashboardStatusProvider', status); await prefs.setString('dashboardStatusProvider', status);
await prefs.setString('dashboardStaffIdProvider', staffId!); await prefs.setString('dashboardStaffIdProvider', staffId!);
context.go(AppRoutes.enquiryForStaff); context.go(
AppRoutes.enquiryForStaff,
extra: {
'fromDashboard': true,
},
);
// context.go(AppRoutes.enquiryForStaff);
// // Navigate // // Navigate
// if (role == 'manager') { // if (role == 'manager') {
// context.go(AppRoutes.enquiryForStaff); // context.go(AppRoutes.enquiryForStaff);

View File

@ -700,26 +700,26 @@ packages:
dependency: transitive dependency: transitive
description: description:
name: leak_tracker name: leak_tracker
sha256: "6bb818ecbdffe216e81182c2f0714a2e62b593f4a4f13098713ff1685dfb6ab0" sha256: "33e2e26bdd85a0112ec15400c8cbffea70d0f9c3407491f672a2fad47915e2de"
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "10.0.9" version: "11.0.2"
leak_tracker_flutter_testing: leak_tracker_flutter_testing:
dependency: transitive dependency: transitive
description: description:
name: leak_tracker_flutter_testing name: leak_tracker_flutter_testing
sha256: f8b613e7e6a13ec79cfdc0e97638fddb3ab848452eff057653abd3edba760573 sha256: "1dbc140bb5a23c75ea9c4811222756104fbcd1a27173f0c34ca01e16bea473c1"
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "3.0.9" version: "3.0.10"
leak_tracker_testing: leak_tracker_testing:
dependency: transitive dependency: transitive
description: description:
name: leak_tracker_testing name: leak_tracker_testing
sha256: "6ba465d5d76e67ddf503e1161d1f4a6bc42306f9d66ca1e8f079a47290fb06d3" sha256: "8d5a2d49f4a66b49744b23b018848400d23e54caf9463f4eb20df3eb8acb2eb1"
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "3.0.1" version: "3.0.2"
lints: lints:
dependency: transitive dependency: transitive
description: description:
@ -1297,10 +1297,10 @@ packages:
dependency: transitive dependency: transitive
description: description:
name: test_api name: test_api
sha256: fb31f383e2ee25fbbfe06b40fe21e1e458d14080e3c67e7ba0acfde4df4e0bbd sha256: "522f00f556e73044315fa4585ec3270f1808a4b186c936e612cab0b565ff1e00"
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "0.7.4" version: "0.7.6"
toastification: toastification:
dependency: "direct main" dependency: "direct main"
description: description:
@ -1417,10 +1417,10 @@ packages:
dependency: transitive dependency: transitive
description: description:
name: vector_math name: vector_math
sha256: "80b3257d1492ce4d091729e3a67a60407d227c27241d6927be0130c98e741803" sha256: d530bd74fea330e6e364cda7a85019c434070188383e1cd8d9777ee586914c5b
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "2.1.4" version: "2.2.0"
vm_service: vm_service:
dependency: transitive dependency: transitive
description: description: