簡體   English   中英

PostgreSQL 行級安全涉及其他表的外鍵

[英]PostgreSQL row-level security involving foreign key with other table

我想知道在 PostgreSQL 中是否可以使用 RLS(或任何其他機制)進行以下操作。 如果用戶的 id 與另一個表中的列匹配,我希望用戶能夠獲取該表的某些行。

例如,我們有下表:

“用戶”表:列:id、name

| id | name  |
| --- | ---  |
| 1   | one  |
| 2   | two  |
| 3   | three|
| 4   | four |

“租戶”表:列:id、name

| id | name |
| --- | --- |
| 1   | t1  |
| 2   | t2  |

“user_tenant”表:列:user_id、tenant_id

| user_id | tenant_id|
| ---     | ---      |
| 1       | t1       |
| 2       | t2       |
| 3       | t1       |
| 4       | t2       |

現在我只想要具有相同 tenant_id 的用戶。

output:

| id | name  |
| --- | ---  |
| 1   | one  |
| 3   | three|

為此,我需要制定如下政策:

CREATE POLICY tenant_policy ON "user" USING (tenant_id = current_setting('my_user.current_tenant')::uuid);

但是根據上述政策,它不起作用,因為我得到了所有用戶。

注意:用戶和租戶表具有多對多關系。

PS我知道我們可以通過加入或其他條件來做到這一點。 但我想使用 PostgreSQL 使用 RLS(行級安全性)實現上述 output

提前致謝!!

如果行級安全性不起作用,可能是因為以下情況之一適用:

  • 您沒有啟用行級安全性:

     ALTER TABLE "user" ENABLE ROW LEVEL SECURITY;
  • 用戶擁有該表

    您可以為所有者啟用行級安全性

    ALTER TABLE "user" FORCE ROW LEVEL SECURITY;
  • 你是一個超級用戶,總是免於 RLS

  • 您是使用BYPASSRLS定義的用戶

  • 參數row_security設置為off

除此之外,您可能必須在您的政策中加入user_tenant

CREATE POLICY tenant_policy ON "user"
   USING (
      EXISTS(SELECT 1 FROM user_tenant AS ut
             WHERE ut.user_id = "user".id
               AND ut.tenant_id = current_setting('my_user.current_tenant')::uuid
            )
      );

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM