Created
May 3, 2021 06:38
-
-
Save namphho/92109a587523041b36ba0cc85ab9f4d4 to your computer and use it in GitHub Desktop.
log_data
This file contains 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:app/data/storage/auth/auth_shared_references.dart'; | |
import 'package:app/domain/repository/auth_repo.dart'; | |
import 'package:app/domain/repository/logging_repo.dart'; | |
import 'package:dio/dio.dart'; | |
import 'package:kiwi/kiwi.dart'; | |
//#1 | |
const String KEY_LOGGED_HEADER = "isLogged"; | |
class AuthenticationInterceptor extends Interceptor{ | |
final Dio _dio; | |
final LoggingRepo _loggingRepo = LoggingRepo(); | |
AuthenticationInterceptor(this._dio); | |
AuthSharedPreferences _authSharedPreferences = KiwiContainer().resolve<AuthSharedPreferences>(); | |
@override | |
Future onRequest(RequestOptions options) async { | |
String token = await _authSharedPreferences.getAccessToken(); | |
options.headers.addAll({'Authorization': 'Bearer $token'}); | |
//#2 check which api need to be logged | |
bool hasLogged = options.headers.containsKey(KEY_LOGGED_HEADER); | |
if (hasLogged){ | |
//#3 invoked api to store log | |
_loggingRepo.sendRequest("${options.data.toString()}"); | |
} | |
return super.onRequest(options); | |
} | |
@override | |
Future onError(DioError dioError) async{ | |
var resp = dioError.response; | |
if (resp == null) { | |
return super.onError(dioError); | |
} | |
int responseCode = resp.statusCode; | |
String oldAccessToken = await _authSharedPreferences.getAccessToken(); | |
String refreshToken = await _authSharedPreferences.getRefreshToken(); | |
if (oldAccessToken != null && refreshToken != null && responseCode == 401) { | |
_dio.interceptors.requestLock.lock(); | |
_dio.interceptors.responseLock.lock(); | |
AuthRepo _authRepo = KiwiContainer().resolve<AuthRepo>(); | |
var refreshSuccess = await _authRepo.refreshAuth(refreshToken); | |
_dio.interceptors.requestLock.unlock(); | |
_dio.interceptors.responseLock.unlock(); | |
if (refreshSuccess == true) { | |
RequestOptions options = dioError.response.request; | |
return _dio.request(options.path, options: options); | |
} | |
} | |
return super.onError(dioError); | |
} | |
@override | |
Future onResponse(Response response) { | |
return super.onResponse(response); | |
} | |
} | |
class RestClient{ | |
final Dio restClient = Dio(); | |
void setUp() { | |
restClient.interceptors.addAll([AuthenticationInterceptor(restClient)]); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment