仅当用户具有确切的文档 ID postgresql 行级安全性/supabase 时才允许读取

Run*_*sen 5 postgresql row-level-security supabase supabase-database

有没有办法让用户只有拥有确切的文档 ID 才能读取文档?

我想避免创建用户,因此唯一的安全性是保存在浏览器内存中的随机 guid - 设置将保存在 id=guid 的“设置”表中。

因此,当页面打开时,它将获取

supabase.from('设置').select('*').eq('id', guid)

如何保护该设置(无需创建(虚拟)用户)

在 Firebase 中就像这样: Firebase firestore 仅允许在用户具有确切文档 ID 时读取,但对于 postgresql/supabase

小智 5

这是可行的,但我会:

  1. 禁止用户通过 RLS 对表进行所有访问anon(从 RLS 策略返回 false)
  2. 使用该函数编写一个 postgres 函数,security definer该函数接受 auuid作为参数,并且仅根据该参数从表中返回一行。(如果该行不存在则不返回任何内容)
  3. 使用supabase.rpc()格式调用该函数。

例子:

create table people (id uuid primary key default gen_random_uuid(), name text);
alter table people enable row level security;
-- now, with no RLS policy, no anon or authenticated users can access the table
create or replace function get_person(person_id uuid)
  returns table (id uuid, name text) security definer 
  language sql AS $$
  select id, name from people where id = person_id;
$$;
Run Code Online (Sandbox Code Playgroud)

在您的客户端代码中:

const { data, error } = 
await supabase.rpc('get_person', { person_id: 'some-uuid' });
return { data, error };
Run Code Online (Sandbox Code Playgroud)