Created
May 3, 2021 06:37
-
-
Save namphho/e202e1ac6d9c58ab8aa20537618c80f4 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); | |
} | |
//#1: get http response status code | |
int responseCode = resp.statusCode; | |
//#2: check accessToken & refreshToken | |
String oldAccessToken = await _authSharedPreferences.getAccessToken(); | |
String refreshToken = await _authSharedPreferences.getRefreshToken(); | |
if (oldAccessToken != null && refreshToken != null && responseCode == 401) { | |
//#3: lock | |
_dio.interceptors.requestLock.lock(); | |
_dio.interceptors.responseLock.lock(); | |
//#5: invoked refreshToken api | |
AuthRepo _authRepo = KiwiContainer().resolve<AuthRepo>(); | |
var refreshSuccess = await _authRepo.refreshAuth(refreshToken); | |
//#4 unlock | |
_dio.interceptors.requestLock.unlock(); | |
_dio.interceptors.responseLock.unlock(); | |
if (refreshSuccess == true) { | |
//#6: retry request which is failed | |
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