Error while writing in firebase - Blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Integrations

Hi,

I am struggling with an error that worked in the past weeks and now it does not, not sure if something changed in the openai platform during the meantime.

I have a custom action that reads from a URL (image from dall-e) and directly writes in Firebase.

Future<String?> uploadImageFromURLToFirebase(
  BuildContext context,
  String imageUrl,
  DocumentReference fragmentID,
) async {
  // Add your function code here!

  try {
    // Log the start of the process
    String decodedUrl = Uri.decodeFull(imageUrl);
    final response = await http.get(Uri.parse(decodedUrl));

    if (response.statusCode == 200) {
      // Log successful download
      // Decode the URL to handle any encoded characters
      // Find the position of the last dot before the question mark
      int questionMarkIndex = decodedUrl.indexOf('?');
      if (questionMarkIndex == -1) {
        throw Exception('No query parameters found in the URL');
      }
      // Extract the extension
      int dotIndex = decodedUrl.lastIndexOf('.', questionMarkIndex);
      if (dotIndex == -1 || dotIndex + 1 >= questionMarkIndex) {
        throw Exception('No file extension found before the query parameters');
      }
      // Get the file extension
      String extension = decodedUrl.substring(dotIndex + 1, questionMarkIndex);

      // Step 2: Convert image URL to a filename
      final fileName = '${fragmentID.id}.$extension';
      print('the final filename is $fileName');

      final metadata = SettableMetadata(contentType: 'image/$extension');

      // Log the size of the image data
      print('Size of image data: ${response.bodyBytes.length} bytes');

      // Step 3: Upload the image bytes directly to Firebase Storage
      final firebaseStorageRef = FirebaseStorage.instance
          .ref()
          .child('users/$userId/uploads/$fileName');
      await firebaseStorageRef.putData(response.bodyBytes, metadata);

      print('Image uploaded successfully ');
      // Get the download URL
      final downloadUrl = await firebaseStorageRef.getDownloadURL();
      print('Image download url $downloadUrl ');
      // Show a snackbar or dialog to indicate success
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
            content:
                Text('Image uploaded to Firebase Storage. URL: $downloadUrl')),
      );

      print(
          'Image successfully uploaded to Firebase Storage. Download URL: $downloadUrl');
      return downloadUrl;
    } else {
      throw Exception(
          'Failed to download image. Status code: ${response.statusCode}');
    }
  } catch (e) {
    // Handle errors and show an error message
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(content: Text('Error: ${e.toString()}')),
    );
    print('Error uploading image: $e');
    return null;
  }
}

These are the errors I see on the browser console:

Starting to download image from https://oaidalleapiprodscus.blob.core.windows.net/private/org-iDZOKOCqiFAUw4Cc2KqWAYQY/user-4h7j6rphHSJlb2MPnIvbCOeb/img-XzX2aQ3sbbN0fd07ilAbx7k7.png?st=2024-07-09T20%3A30%3A31Z&se=2024-07-09T22%3A30%3A31Z&sp=r&sv=2023-11-03&sr=b&rscd=inline&rsct=image/png&skoid=6aaadede-4fb3-4698-a8f6-684d7786b067&sktid=a48cca56-e6da-484e-a814-9c849652bcb3&skt=2024-07-09T18%3A25%3A01Z&ske=2024-07-10T18%3A25%3A01Z&sks=b&skv=2023-11-03&sig=XMP%2BwBwfTKHXDeUQ1Kj5Uew0mkNc37zchvn2pPkzhyw%3D

storyReader:1 Access to XMLHttpRequest at 'https://oaidalleapiprodscus.blob.core.windows.net/private/org-iDZOKOCqiFAUw4Cc2KqWAYQY/user-4h7j6rphHSJlb2MPnIvbCOeb/img-XzX2aQ3sbbN0fd07ilAbx7k7.png?st=2024-07-09T20:30:31Z&se=2024-07-09T22:30:31Z&sp=r&sv=2023-11-03&sr=b&rscd=inline&rsct=image/png&skoid=6aaadede-4fb3-4698-a8f6-684d7786b067&sktid=a48cca56-e6da-484e-a814-9c849652bcb3&skt=2024-07-09T18:25:01Z&ske=2024-07-10T18:25:01Z&sks=b&skv=2023-11-03&sig=XMP+wBwfTKHXDeUQ1Kj5Uew0mkNc37zchvn2pPkzhyw=' from origin 'https://ff-debug-service-frontend-free-ygxkweukma-uc.a.run.app' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

dart_sdk.js:37972 Error uploading image: ClientException: XMLHttpRequest error., uri=https://oaidalleapiprodscus.blob.core.windows.net/private/org-iDZOKOCqiFAUw4Cc2KqWAYQY/user-4h7j6rphHSJlb2MPnIvbCOeb/img-XzX2aQ3sbbN0fd07ilAbx7k7.png?st=2024-07-09T20:30:31Z&se=2024-07-09T22:30:31Z&sp=r&sv=2023-11-03&sr=b&rscd=inline&rsct=image/png&skoid=6aaadede-4fb3-4698-a8f6-684d7786b067&sktid=a48cca56-e6da-484e-a814-9c849652bcb3&skt=2024-07-09T18:25:01Z&ske=2024-07-10T18:25:01Z&sks=b&skv=2023-11-03&sig=XMP+wBwfTKHXDeUQ1Kj5Uew0mkNc37zchvn2pPkzhyw=

browser_client.dart:101

GET https://oaidalleapiprodscus.blob.core.windows.net/private/org-iDZOKOCqiFAUw4Cc2KqWAYQY/user-4h7j6rphHSJlb2MPnIvbCOeb/img-XzX2aQ3sbbN0fd07ilAbx7k7.png?st=2024-07-09T20:30:31Z&se=2024-07-09T22:30:31Z&sp=r&sv=2023-11-03&sr=b&rscd=inline&rsct=image/png&skoid=6aaadede-4fb3-4698-a8f6-684d7786b067&sktid=a48cca56-e6da-484e-a814-9c849652bcb3&skt=2024-07-09T18:25:01Z&ske=2024-07-10T18:25:01Z&sks=b&skv=2023-11-03&sig=XMP+wBwfTKHXDeUQ1Kj5Uew0mkNc37zchvn2pPkzhyw= net::ERR_FAILED 403 (Server failed to authenticate the request. Make sure the value of Authorization header is formed correctly including the signature.)

My firebase rules are the following:

rules_version = '2';
service firebase.storage {
match /b/{bucket}/o {
match /free/{allPaths=**} {
allow read: if request.auth != null; // Only authenticated users can read and write
allow write: if false;
}
// Existing rule for the /users directory
match /users/{userId}/uploads/{allPaths=**} {
allow read : if request.auth != null; // Allow read if the user is authenticated
allow write,update : if request.auth != null && request.auth.uid == userId; // Allow write if the user is authenticated and the owner
}
// Rule to prevent any access to other unspecified paths by default
match /{allPaths=**} {
allow read, write: if false; // No access to other paths
} }}

I also add the following cors.json file to my google cloud instance

[
  {
    "origin": ["https://*.a.run.app"],
    "method": ["GET"],
    "responseHeader": ["Content-Type", "Authorization"],
    "maxAgeSeconds": 3600
  }
]

I executed the following command to do so gsutil cors set cors.json gs://xxxxxxx.appspot.com

At first, I thought I might need to add a CORS file to openai to download the file from my app, but if I copy and paste the image's URL and open it in an incognito tab, the image is loaded without any issue.

Also, the file in Firebase gets created but with a size of 2 KB. This indicates to me that the Firebase rules are not the problem.

Any suggestion of what I might be doing wrong?

Many thanks

Jose

What have you tried so far?
  • changed the Firebase rules.

  • added cors file

Did you check FlutterFlow's Documentation for this topic?
No