Postgres RLS 策略:仅允许 SELECT 行基于外部关系的存在

Postgres RLS policy: Only allow SELECT on row based on existence of foreign relation

我有以下 Postgres tables:

用户

+---------+--------------+
| id (PK) |  full_name   |
+---------+--------------+
| uuid()  | varchar      |
+---------+--------------+

组织

+---------+---------+
| id (PK) |  name   |
+---------+---------+
| uuid()  | varchar |
+---------+---------+

organization_memberships

+---------+----------------------+--------------+
| id (PK) | organization_id (FK) | user_id (FK) |
+---------+----------------------+--------------+
| uuid()  | uuid()               | uuid()       |
+---------+----------------------+--------------+

我正在尝试编写 Postgres 行级安全 (RLS) 策略。

政策必须强制规定,当 organization_memberships table 中有相应的条目时,用户只能从 organizations table SELECT .

这是我目前拥有的,但似乎并没有像我预期的那样工作。请注意,uid() 方法由我的 DBAAS 解决方案提供,用于获取经过身份验证的用户的 ID。

ALTER POLICY "User can only Select organizations where they are members" ON public.organizations USING (
  (
    EXISTS (
      SELECT
        orgmembs.user_id,
        orgmembs.organization_id
      FROM
        organization_memberships orgmembs
      WHERE
        (
          (orgmembs.organization_id = organizations.id)
          AND (orgmembs.user_id = uid())
        )
    )
  )
);

我也试过这个略有不同的版本,但我收到错误,Error updating policy: missing FROM-clause entry for table "organization":

ALTER POLICY "User can only Select organizations where they are member" ON public.organizations USING (
  auth.uid() IN (
    SELECT
      user_id
    FROM
      organization_memberships
    WHERE
      organization_memberships.organization_id = organization.id
  )
);
alter POLICY "User can only Select organizations where they are member"
      ON organizations 
      USING (id  IN (
                        SELECT organization_id 
                        FROM organization_memberships om 
                        JOIN users u ON om.user_id = u.id
                    )
            )