Last active
September 17, 2021 17:24
-
-
Save guilherme-v/dc6ddcd4cad0962f89a82e4f018b87db to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'package:http/http.dart' as http; | |
import 'package:shared_preferences/shared_preferences.dart'; | |
class AuthenticatedHttpClient extends http.BaseClient { | |
SharedPreferences sharedPref; | |
AuthenticatedHttpClient({this.sharedPref}); | |
// Use a memory cache to avoid local storage access in each call | |
String _inMemoryToken = ''; | |
String get userAccessToken { | |
// use in memory token if available | |
if (_inMemoryToken.isNotEmpty) return _inMemoryToken; | |
// otherwise load it from local storage | |
_inMemoryToken = _loadTokenFromSharedPreference(); | |
return _inMemoryToken; | |
} | |
@override | |
Future<http.StreamedResponse> send(http.BaseRequest request) { | |
// intercept each call and add the Authorization header if token is available | |
if (userAccessToken.isNotEmpty) { | |
request.headers.putIfAbsent('Authorization', () => userAccessToken); | |
} | |
return request.send(); | |
} | |
String _loadTokenFromSharedPreference() { | |
var accessToken = ''; | |
final user = sharedPref.getString(CACHED_USER); | |
// If user is already authenticated, we can load his token from cache | |
if (user != null) { | |
accessToken = user.accessToken; | |
} | |
return accessToken; | |
} | |
// Don't forget to reset the cache when logging out the user | |
void reset() { | |
_inMemoryToken = ''; | |
} | |
} |
Hello! Thx for the code. Why don't you reset the "_inMemoryToken" along with sharedPref CACHED_USER on log out?
Hi! We have a different class that is responsible for reseting all the sharedPref variables. In this case we'd preferred to only reset variables related to (owned by) the HttpClient. Besides it was a precaution in case you want to start using more than a single AuthenticatedHttpClient instance
But do what works better/(makes more sense) to your project :D π
Thank you very much! π€π»
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi! We have a different class that is responsible for reseting all the sharedPref variables. In this case we'd preferred to only reset variables related to (owned by) the HttpClient. Besides it was a precaution in case you want to start using more than a single AuthenticatedHttpClient instance
But do what works better/(makes more sense) to your project :D π