Saturday, 1 April 2023

Firebase Storage Security Rules deny read permissions even though "allow read: if true"

I'm probably missing something simple. I have been stuck on this for a while and its critical. Any assistance would be appreciated.

I have a firestore storage database with rules that allow everyone to read(see) images.

rules_version = '2';
service firebase.storage {
  match /b/{bucket}/o {
    match /images/{userId} {
      allow read: if true;
      allow write: if request.auth != null && request.auth.uid == userId;
    }
    match /videos/{userId} {
      allow read: if true
      allow write: if request.auth != null && request.auth.uid == userId;
    }
  }
}

Yet when i refresh a particular page, i get a:

Uncaught (in promise) FirebaseError: Firebase Storage: User does not have permission to access 'images/BJBAPfJMTCOq9OypfdkZ9z1NtQ93'. (storage/unauthorized)

The code to list all images belonging to a specific user:

export default function MultiMedia({ handleUser }) {
  const imageListRef = useRef(ref(storage, `images/${handleUser}`));
  const [imageList, setImageList] = useState([]);

  useEffect(() => {
    listAll(imageListRef.current).then((response) => {
      response.items.forEach((item) => {
        getDownloadURL(item).then((url) => {
          setImageList((prev) => [...prev, url]);
        });
      });
    });
  }, []);

  return...

The confusion is that images do render on a different page, the home page which pulls from a firestore database that has images url and uid as fields, amongst other fields.

export default function ImageGallery() {
  const [imageData, setImageData] = useState([]);

  useEffect(() => {
    async function reloadHome() {
      try {
        const querySnapshot = await getDocs(collection(db, "images"));

        querySnapshot.forEach((doc) => {
          setImageData((prevValue) => {
            return [
              ...prevValue,
              { imageURL: doc.data().imageURL, user: doc.data().user },
            ];
          });
        });
      } catch (error) {
        console.log(error);
      }
    }
    reloadHome();
  }, []);

Firestore security for images folder:

rules_version = '2';
service cloud.firestore {
    match /images/{image} {
    allow read: if true;
      allow create: if isLoggedIn();
      allow update, delete: if isLoggedIn() && request.auth.uid == resource.data.user;
    }
}

I would expect the storage security rules that would prevent a user from seeing an image on a user profile pulled from Firebase storage would be the same rule that would prevent the same user from seeing the same image who's download URL was stored in a Firestore database.



from Firebase Storage Security Rules deny read permissions even though "allow read: if true"

No comments:

Post a Comment