onRequest method

  1. @override
void onRequest(
  1. RequestOptions options,
  2. RequestInterceptorHandler handler
)

Called when the request is about to be sent.

Implementation

@override
void onRequest(
    RequestOptions options, RequestInterceptorHandler handler) async {
  options.headers['Content-Type'] = "application/x-www-form-urlencoded";
  SharedPreferences sharedPreferences = await DeviceStorage().getInstance();
  String refreshToken =
      sharedPreferences.getString(DeviceStorage.refreshToken) ?? "";
  String sessionToken =
      sharedPreferences.getString(DeviceStorage.sessionToken) ?? "";
  String deviceToken =
      sharedPreferences.getString(DeviceStorage.deviceToken) ?? "";
  if (kDebugMode) {
    // print("deviceToken");
    // print(deviceToken);
    // print(sessionToken);
    // print(refreshToken);
  }
  //ProviderConstants.isLoggedIn
  if (!options.path.contains("getcountry")) {
    if (NetworkHandler.hasTokenExpired(refreshToken)) {
      //logout the user
      NetworkHandler().logout();
      //add device token headers since the user is logged out
      if (NetworkHandler.hasTokenExpired(deviceToken)) {
        deviceToken = await NetworkHandler.refreshDeviceToken();
      }

      //print("add device token headers since the user is logged out");
      options.headers["authorization"] = 'Bearer $deviceToken';
    } else {
      if (NetworkHandler.hasTokenExpired(sessionToken)) {
        sessionToken = await NetworkHandler.refreshSessionToken(refreshToken);
      }
      if (sessionToken == "") {
        //logout the user the session was expired
        NetworkHandler().logout();
        if (NetworkHandler.hasTokenExpired(deviceToken)) {
          deviceToken = await NetworkHandler.refreshDeviceToken();
        }
        //print("add device token headers since the user is logged out");
        options.headers["authorization"] = 'Bearer $deviceToken';
      } else {
        // addd session token headers since the user is logged in
        //print("addd session token headers since the user is logged in");
        //print(sessionToken);
        options.headers["X-SESSION"] = sessionToken;
      }
    }
  } else {
    if (NetworkHandler.hasTokenExpired(deviceToken)) {
      deviceToken = await NetworkHandler.refreshDeviceToken();
    }
    // add device token headers since the user is not logged in
    options.headers["authorization"] = 'Bearer $deviceToken';
    //print("add device token headers since the user is not logged in");
  }
  handler.next(options);
}