RLS for bucket joined with table data

Hello 👋🏻 I'm unable to figure out the correct syntax for a row-level security policy on my storage bucket.

I have a table named entities that has columns for
user_id
, slug, and name. I also have a bucket where I want to store an image for each entity. I want the image to be stored at the path /:slug/images, so for example my entity with slug my-thing would have an image at the path /my-thing/images/image.png.

When a user attempt to upload an image to their folder, I want to check that they have access to that folder by checking the
user_id
and slug in my entities table.

Here's what my policy query looks like:

BEGIN;
  ALTER POLICY "Give users access to their own folders"
  ON "storage"."objects"
  WITH CHECK (
    ((bucket_id = 'my-bucket'::text)
    AND (
      (SELECT auth.uid() AS uid)
      IN (SELECT entities.user_id FROM entities WHERE ((entities.slug)::text = (storage.foldername(name))[1])))
    )
  );
COMMIT;


Every time I save this policy, Supabase replaces storage.foldername(name) with storage.foldername(entities.name) which will never work. Can anybody please help me figure out what I'm doing wrong?
Was this page helpful?