callSecureOps static method

Future<Map<String, dynamic>> callSecureOps(
  1. Map<String, dynamic> data
)

Calls secureOps. On web, uses secureOpsWeb (HTTP with CORS). On mobile, uses the callable secureOps via Firebase SDK.

Implementation

static Future<Map<String, dynamic>> callSecureOps(Map<String, dynamic> data) async {
  if (kIsWeb) {
    // `getConfig` es la única que no cuesta dinero y puede correr sin
    // sesión. El resto estaban en esta lista como «públicas», que era justo
    // lo que dejaba el proxy abierto: ahora se firma antes de llamar.
    final isPublicAction = data['action'] == 'getConfig';
    final user = isPublicAction
        ? FirebaseAuth.instance.currentUser
        : await _ensureSignedIn();

    if (user == null && !isPublicAction) {
      throw Exception('Authentication required — user not logged in');
    }

    final url = Uri.parse(_getSecureOpsWebUrl());

    final token = user != null ? await user.getIdToken() : null;
    final headers = <String, String>{
      'Content-Type': 'application/json',
      if (token != null) 'Authorization': 'Bearer $token',
    };

    late final http.Response response;
    try {
      response = await http
          .post(
            url,
            headers: headers,
            body: jsonEncode({'data': data}),
          )
          .timeout(const Duration(seconds: 15));
    } catch (error) {
      if (CloudEndpointPolicy.usesLocalEndpoints) {
        throw StateError(
          '${CloudEndpointPolicy.emulatorUnavailableMessage} '
          'Error original: $error',
        );
      }
      rethrow;
    }

    if (response.statusCode != 200) {
      throw Exception('secureOpsWeb HTTP ${response.statusCode}: ${response.body}');
    }

    final body = jsonDecode(response.body);
    if (body is Map<String, dynamic>) {
      if (body['error'] != null) {
        final err = body['error'];
        throw Exception(err is Map ? (err['message'] ?? 'Unknown error') : err.toString());
      }
      // onCall wraps in 'result', HTTP returns directly
      if (body.containsKey('result') && body['result'] is Map) {
        return body['result'] as Map<String, dynamic>;
      }
      return body;
    }
    return {};
  }

  // Mobile: use Firebase SDK callable.
  //
  // `httpsCallable` adjunta el token solo si YA hay un usuario; si no,
  // `request.auth` llega null y el servidor rechaza. Se firma antes, igual
  // que en la rama web, para que el invitado en móvil siga funcionando.
  if (data['action'] != 'getConfig') {
    await _ensureSignedIn();
  }
  final callable = FirebaseFunctions.instance.httpsCallable('secureOps');
  final result = await callable.call(data);
  final normalized = _normalizeJsonValue(result.data);
  if (normalized is Map<String, dynamic>) {
    return normalized;
  }
  return {};
}