设计一个用户(users)、角色(roles)、**组织(organizations)**三者的多对多关系,并且加上 Supabase RLS(行级安全)策略
1. 数据库设计
三类实体:
- users 用户表
- roles 角色表
- organizations 组织表
由于是多对多关系,需要中间表:
- user_roles 用户-角色 多对多
- user_organizations 用户-组织 多对多
- role_organizations 角色-组织 多对多(可选,看你的业务需求)
建主表
-- 用户表(业务信息扩展)
create table public.users (
id uuid primary key references auth.users(id) on delete cascade,
email text unique not null,
name text,
created_at timestamp with time zone default now()
);
-- 角色表
create table public.roles (
id uuid primary key default gen_random_uuid(),
name text unique not null,
description text,
created_at timestamp with time zone default now()
);
-- 组织表
create table public.organizations (
id uuid primary key default gen_random_uuid(),
name text unique not null,
description text,
created_at timestamp with time zone default now()
);
创建多对多关系表
-- 用户 - 角色 多对多
create table public.user_roles (
user_id uuid references public.users(id) on delete cascade,
role_id uuid references public.roles(id) on delete cascade,
primary key (user_id, role_id)
);
-- 用户 - 组织 多对多
create table public.user_organizations (
user_id uuid references public.users(id) on delete cascade,
org_id uuid references public.organizations(id) on delete cascade,
primary key (user_id, org_id)
);
-- 角色 - 组织 多对多(可选)
create table public.role_organizations (
role_id uuid references public.roles(id) on delete cascade,
org_id uuid references public.organizations(id) on delete cascade,
primary key (role_id, org_id)
);
2. 开启 RLS(行级安全)
RLS 会让每个用户只能访问自己有权限的数据。
-- 开启行级安全
alter table public.users enable row level security;
alter table public.roles enable row level security;
alter table public.organizations enable row level security;
alter table public.user_roles enable row level security;
alter table public.user_organizations enable row level security;
alter table public.role_organizations enable row level security;
3. 添加 RLS 策略
这里假设 JWT 的 auth.uid() 是 users.id。
用户只能看到自己
create policy "Users can view their own data"
on public.users
for select
using ( id = auth.uid() );
create policy "Users can update their own data"
on public.users
for update
using ( id = auth.uid() );
用户只能看到自己关联的组织
create policy "Users can view their organizations"
on public.organizations
for select
using (
exists (
select 1 from public.user_organizations uo
where uo.org_id = organizations.id
and uo.user_id = auth.uid()
)
);
用户只能看到自己关联的角色
create policy "Users can view their roles"
on public.roles
for select
using (
exists (
select 1 from public.user_roles ur
where ur.role_id = roles.id
and ur.user_id = auth.uid()
)
);
4. 说明
- 这样设计后,用户、角色、组织 三个表之间的关系都能通过多对多中间表建立。
- Supabase RLS 策略确保用户只能看到与自己有关的数据。
- 如果是 管理员 角色,你可以单独加一个策略放开限制。