onResponse method

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

Intercepts API responses and verifies the security signature.

If a response contains an X-Signature header, the interceptor attempts to verify the signature to ensure data integrity. If verification fails, it triggers the onResponseSecurityNotValid callback and rejects the response.

Implementation

@override
void onResponse(Response response, ResponseInterceptorHandler handler) async {
  try {
    if (!_isSecurityKeyInitialized) {
      throw Exception(
        "Security configuration is not initialized. Call VenturoApiSecurity in VenturoApiConfig before using it.",
      );
    }

    var signature =
        response.headers.value('X-Signature') ?? response.headers.value('x-signature');
    var hasSignature = signature != null;
    if (!hasSignature) return super.onResponse(response, handler);

    bool isVerified = false;
    String data = "";

    bool isAll = response.headers.value('x-response')?.toLowerCase() == 'all';
    if (isAll) {
      data = jsonEncode(_funcSortList(response.data));
    } else {
      data = jsonEncode(_funcSortList(response.data['data']));
    }

    isVerified = await _verifySignature(data, signature);

    if (!isVerified) {
      if (configItc?.onResponseSecurityNotValid != null) {
        configItc!.onResponseSecurityNotValid!(response, handler);
      }
      return handler.reject(
        DioException(
          message: "Data not valid",
          error: Exception("Signature not verified"),
          response: Response<dynamic>(requestOptions: response.requestOptions, statusCode: 406),
          stackTrace: StackTrace.current,
          requestOptions: response.requestOptions,
          type: DioExceptionType.cancel,
        ),
      );
    }

    if (configItc?.onResponseSecurityValid != null) configItc!.onResponseSecurityValid!();
    return super.onResponse(response, handler);
  } catch (e, s) {
    log(e.toString(), name: "VAM");
    log(s.toString(), name: "VAM");
    return super.onResponse(response, handler);
  }
}