Skip to content

Commit

Permalink
fix(fresh_dio): add assert to prevent infinite refresh loop (#98)
Browse files Browse the repository at this point in the history
Co-authored-by: Felix Angelov <[email protected]>
  • Loading branch information
LukasMirbt and felangel authored Jul 20, 2024
1 parent 446e01e commit 0eee07a
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 0 deletions.
23 changes: 23 additions & 0 deletions packages/fresh_dio/lib/src/fresh.dart
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,29 @@ class Fresh<T> extends QueuedInterceptor with FreshMixin<T> {
RequestOptions options,
RequestInterceptorHandler handler,
) async {
assert(
_httpClient.interceptors.every((interceptor) => interceptor != this),
'''
Cycle Detected!
The Fresh instance was created using an http client
which already contains the Fresh instance as an interceptor.
This will cause an infinite loop on token refresh.
Example:
```
final httpClient = Dio();
final fresh = Fresh.oAuth2(
httpClient: httpClient,
...
);
httpClient.interceptors.add(fresh); // <-- BAD
```
''',
);

final currentToken = await token;
final headers = currentToken != null
? _tokenHeader(currentToken)
Expand Down
24 changes: 24 additions & 0 deletions packages/fresh_dio/test/fresh_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,30 @@ void main() {

group('onRequest', () {
const oAuth2Token = OAuth2Token(accessToken: 'accessToken');

test(
'throws AssertionError when httpClient.interceptors '
'contains the Fresh instance as an interceptor',
() {
when(() => tokenStorage.read()).thenAnswer((_) async => oAuth2Token);

final httpClient = Dio();

final fresh = Fresh.oAuth2(
tokenStorage: tokenStorage,
refreshToken: emptyRefreshToken,
httpClient: httpClient,
);

httpClient.interceptors.add(fresh);

expect(
fresh.onRequest(RequestOptions(), RequestInterceptorHandler()),
throwsA(isA<AssertionError>()),
);
},
);

test(
'appends token header when token is OAuth2Token '
'and tokenHeader is not provided', () async {
Expand Down

0 comments on commit 0eee07a

Please sign in to comment.