Skip to content

Commit

Permalink
Use cached token instead of fetching
Browse files Browse the repository at this point in the history
  • Loading branch information
GravityDarkLab committed Feb 3, 2024
1 parent 3368e7f commit a0529af
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 8 deletions.
8 changes: 1 addition & 7 deletions lib/base/networking/api/handler/grpc_handler.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -42,13 +41,8 @@ class GrpcHandler {
Future<T> 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 = <String, String>{
Expand Down
20 changes: 19 additions & 1 deletion lib/base/networking/api/handler/token_handler.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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.
///
Expand Down Expand Up @@ -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) {
Expand All @@ -103,10 +104,27 @@ class TokenHandler {
static Future<void> 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<String> 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<void> _invalidateToken() async {
cachedToken = '';
}


}

0 comments on commit a0529af

Please sign in to comment.