管理用户数据
为了安全起见,auth
模式不在自动生成的API上公开。
尽管Supabase提供了一个auth.users
表,但在public
模式中创建表来存储你想通过API访问的用户数据可能会有帮助。
创建用户表
当你创建表来存储用户数据时,在主键中引用auth.users
表是有帮助的。这可以确保数据的完整性。
例如,一个 public.profiles
表可能看起来像这样:
create table public.profiles (
id uuid references auth.users not null,
first_name text,
last_name text,
primary key (id)
);
alter table public.profiles enable row level security;
公开访问
由于启用了行级安全,这个表可以通过API访问,但除非我们设置了一些策略,否则不会有数据返回。 如果我们想让每个人都能读到数据,但只允许登录的用户更新他们自己的数据,那么策略会是这样的。
create policy "Public profiles are viewable by everyone."
on profiles for select
using ( true );
create policy "Users can insert their own profile."
on profiles for insert
with check ( auth.uid() = id );
create policy "Users can update own profile."
on profiles for update
using ( auth.uid() = id );
私人访问
如果数据只能由拥有该数据的用户读取,我们只需要更改上面的for select
查询。
create policy "Profiles are viewable by users who created them."
on profiles for select
using ( auth.uid() = id );
这种模式的好处是什么?我们现在可以通过API查询这个表,我们不需要在API查询中包含数据过滤器--政策将为我们处理这个问题。
// This will return nothing while the user is logged out
const { data } = await supabase
.from('profiles')
.select('id, username, avatar_url, website')
// After the user is logged in, this will only return
// the logged-in user's data - in this case a single row
const { error } = await supabase.auth.signIn({ email })
const { data: profile } = await supabase
.from('profiles')
.select('id, username, avatar_url, website')
绕过行级安全
如果你需要获取一个完整的用户资料列表,我们提供了一个 service_key
,你可以使用你的API和客户端库来绕过行级安全。
请确保你永远不要公开暴露这个 service_key
密钥。应用开发人员可以在服务器端使用 service_key
密钥,以获取所有的用户信息。