Created
May 3, 2021 06:01
-
-
Save namphho/e5414faac302d9f9972e2a9d2e0e4f2b to your computer and use it in GitHub Desktop.
authentication intercepto retry
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:dio/dio.dart'; | |
import 'package:kiwi/kiwi.dart'; | |
class AuthenticationInterceptor extends Interceptor{ | |
final Dio _dio; | |
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'}); | |
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