Skip to content

Instantly share code, notes, and snippets.

@guilherme-v
Last active September 17, 2021 17:24
Show Gist options
  • Save guilherme-v/dc6ddcd4cad0962f89a82e4f018b87db to your computer and use it in GitHub Desktop.
Save guilherme-v/dc6ddcd4cad0962f89a82e4f018b87db to your computer and use it in GitHub Desktop.
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 = '';
}
}
@trueAtom
Copy link

trueAtom commented Sep 17, 2021

Hello! Thx for the code. Why don't you reset the "_inMemoryToken" along with sharedPref CACHED_USER on log out?

@guilherme-v
Copy link
Author

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 👍

@trueAtom
Copy link

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