onResponse method

  1. @override
void onResponse(
  1. dynamic response,
  2. dynamic handler
)

Implementation

@override
void onResponse(Response response, ResponseInterceptorHandler handler) async {
  if (!shouldRunDioInterceptor(response.requestOptions)) {
    return handler.next(response);
  }
  _refreshAPILock.acquireWrite();
  await saveTokensFromHeaders(response);
  String? frontTokenFromResponse =
      response.headers.map[frontTokenHeaderKey]?.first.toString();
  SuperTokensUtils.fireSessionUpdateEventsIfNecessary(
    wasLoggedIn:
        _preRequestLocalSessionState.status == LocalSessionStateStatus.EXISTS,
    status: response.statusCode!,
    frontTokenFromResponse: frontTokenFromResponse,
  );
  List<dynamic>? setCookieFromResponse =
      response.headers.map[HttpHeaders.setCookieHeader];
  setCookieFromResponse?.forEach((element) async {
    await Client.cookieStore
        ?.saveFromSetCookieHeader(response.realUri, element);
  });

  try {
    if (response.statusCode == SuperTokens.sessionExpiryStatusCode) {
      RequestOptions requestOptions = response.requestOptions;
      requestOptions =
          await _removeAuthHeaderIfMatchesLocalToken(requestOptions);
      UnauthorisedResponse shouldRetry =
          await Client.onUnauthorisedResponse(_preRequestLocalSessionState);
      if (shouldRetry.status == UnauthorisedStatus.RETRY) {
        requestOptions.headers[HttpHeaders.cookieHeader] = userSetCookie;
        Response<dynamic> res = await client.fetch(requestOptions);
        List<dynamic>? setCookieFromResponse =
            res.headers.map[HttpHeaders.setCookieHeader];
        setCookieFromResponse?.forEach((element) async {
          await Client.cookieStore
              ?.saveFromSetCookieHeader(res.realUri, element);
        });
        await saveTokensFromHeaders(res);
        return handler.next(res);
      } else {
        if (shouldRetry.exception != null) {
          handler.reject(
            DioException(
                requestOptions: response.requestOptions,
                error: SuperTokensException(shouldRetry.exception!.message),
                type: DioExceptionType.unknown),
          );
          return;
        } else {
          _refreshAPILock.release();
          return handler.next(response);
        }
      }
    } else {
      _refreshAPILock.release();
      return handler.next(response);
    }
  } on DioException catch (e) {
    handler.reject(e);
  } catch (e) {
    handler.reject(
      DioException(
          requestOptions: response.requestOptions,
          type: DioExceptionType.unknown,
          error: e),
    );
  } finally {
    LocalSessionState localSessionState =
        await SuperTokensUtils.getLocalSessionState();
    if (localSessionState.status == LocalSessionStateStatus.NOT_EXISTS) {
      await AntiCSRF.removeToken();
      await FrontToken.removeToken();
    }
  }
}