Victor Molina
Victor Molina

Reputation: 2661

Firebase Storage Error when uploading content (Bug?)

I have created a function to upload photos to my storage. Sometimes it works fine, but in several moments I get the following error:

Possible Unhandled Promise Rejection (id: 0):
FirebaseStorageError {
  "code_": "storage/unauthorized",
  "message_": "Firebase Storage: User does not have permission to access 'photos/1d1be05f-b82d-4928-9a8e-002abc0d462e'.",
  "name_": "FirebaseError",
  "serverResponse_": "{
  \"error\": {
    \"code\": 403,
    \"message\": \"Permission denied. Could not perform this operation\"
  }
}",
}

I am using Expo, and fetching the local uri (for creating a blob) using this function:

export function urlToBlob(url) {
  return new Promise((resolve, reject) => {
    var xhr = new XMLHttpRequest();
    xhr.onerror = reject;
    xhr.onreadystatechange = () => {
      if (xhr.readyState === 4) {
        resolve(xhr.response);
      }
    };
    xhr.open("GET", url);
    xhr.responseType = "blob"; // convert type
    xhr.send();
  });
}
 

My storage security rules looks like this:

rules_version = '2';
service firebase.storage {
  match /b/{bucket}/o {
    function isSignedIn() {
        return request.auth.uid != null;
    }
    match /photos/{photo} {
            function hasValidSize() {
        // Max. photo size = 30MB (For all dimensions)
        return request.resource.size < 30 * 1024 * 1024;
      }
      function isImage() {
            return request.resource.contentType.matches("image/.*");
            }
      allow read;
      allow write: if isSignedIn() && isImage() && hasValidSize();
    }
  }
}

I think that the error is here, because when I delete uploadTask.then works fine.

// Upload to storage const uploadTask = storageRef.put(blob);

uploadTask.on("state_changed", (taskSnapshot) => {
  // Update progress bar
  const percent =
    (taskSnapshot.bytesTransferred / taskSnapshot.totalBytes) * 100;

  setUploadProgress(percent);
});


// When the image is fully uploaded to the storage...
    uploadTask.then(async () => {  // <------------------------- When I delete this...
       ...   
      // Reset upload progress
      setUploadProgress(null);
    }); // <------------------------- ...and this, all works fine
  };

Any ideas?

UPDATE

When I change the storage rule (deleting the isImage() condition), it works too with the uploadTask.

Upvotes: 1

Views: 428

Answers (1)

Victor Molina
Victor Molina

Reputation: 2661

I think that's an Expo bug, because I moved from development mode to production and all is working fine!

Upvotes: 1

Related Questions