From a0529af10f367c0140cf7f0afcc09d4d6321a9de Mon Sep 17 00:00:00 2001 From: Achraf Labidi Date: Sat, 3 Feb 2024 17:54:23 +0100 Subject: [PATCH] Use cached token instead of fetching --- .../networking/api/handler/grpc_handler.dart | 8 +------- .../networking/api/handler/token_handler.dart | 20 ++++++++++++++++++- 2 files changed, 20 insertions(+), 8 deletions(-) diff --git a/lib/base/networking/api/handler/grpc_handler.dart b/lib/base/networking/api/handler/grpc_handler.dart index 89ec8f9..13a2b75 100644 --- a/lib/base/networking/api/handler/grpc_handler.dart +++ b/lib/base/networking/api/handler/grpc_handler.dart @@ -9,7 +9,6 @@ import 'package:logger/logger.dart'; /// Handles gRPC communication for the application. class GrpcHandler { static final Logger _logger = Logger(); - final String host; final int port; late ClientChannel _channel; @@ -42,13 +41,8 @@ class GrpcHandler { Future Function(APIClient client) grpcMethod, ) async { _logger.d('callGrpcMethod: Initiating gRPC call'); + final token = await TokenHandler.getToken(); try { - String token = ''; - try { - token = await TokenHandler.loadToken('jwt'); - }catch(e) { - token = ''; - } CallOptions callOptions; if(token.isNotEmpty) { final metadata = { diff --git a/lib/base/networking/api/handler/token_handler.dart b/lib/base/networking/api/handler/token_handler.dart index cf970fe..1499e45 100644 --- a/lib/base/networking/api/handler/token_handler.dart +++ b/lib/base/networking/api/handler/token_handler.dart @@ -11,6 +11,8 @@ import 'package:logger/logger.dart'; class TokenHandler { static final Logger _logger = Logger(); static const _storage = FlutterSecureStorage(); + static String cachedToken = ''; + /// Stores a token. /// @@ -84,7 +86,6 @@ class TokenHandler { _logger.w('Token not found for key: $key'); return ""; } - _logger.i('Token successfully loaded for key: $key'); return token; } catch (e) { @@ -103,10 +104,27 @@ class TokenHandler { static Future deleteToken(String key) async { try { await _storage.delete(key: key); + await _invalidateToken(); _logger.i('Token successfully deleted for key: $key'); } catch (e) { _logger.e('Error deleting token: $e'); throw AppError.notFound(); } } + + static Future getToken() async { + if(cachedToken.isNotEmpty) { + _logger.d('Using cached token'); + return cachedToken; + } + _logger.d('Loading token from storage'); + cachedToken = await loadToken('jwt'); + return cachedToken; + } + + static Future _invalidateToken() async { + cachedToken = ''; + } + + }