สมมติว่าเราสร้างตารางดังนี้
create table public.transactions (
id bigint generated always as identity primary key,
user_id uuid not null references auth.users(id),
title text not null,
amount numeric not null,
created_at timestamptz not null default now()
);
จากนั้นเปิด RLS
alter table public.transactions
enable row level security;
Policy สำหรับอ่านข้อมูลของตัวเอง
create policy "Users can view their own transactions"
on public.transactions
for select
to authenticated
using (
(select auth.uid()) = user_id
);
เมื่อผู้ใช้เรียกดูข้อมูล PostgreSQL จะคืนเฉพาะแถวที่มี user_id ตรงกับผู้ใช้ที่เข้าสู่ระบบอยู่
Policy สำหรับเพิ่มข้อมูลของตัวเอง
create policy "Users can insert their own transactions"
on public.transactions
for insert
to authenticated
with check (
(select auth.uid()) = user_id
);
Policy นี้ป้องกันไม่ให้ User A ส่งข้อมูลใหม่โดยแอบใส่ user_id ของ User B
Policy สำหรับแก้ไขข้อมูลของตัวเอง
create policy "Users can update their own transactions"
on public.transactions
for update
to authenticated
using (
(select auth.uid()) = user_id
)
with check (
(select auth.uid()) = user_id
);
ในกรณีของ UPDATE:
จึงช่วยป้องกันทั้งการแก้รายการของคนอื่น และการเปลี่ยน user_id ของรายการให้เป็นผู้ใช้อื่น
Policy สำหรับลบข้อมูลของตัวเอง
create policy "Users can delete their own transactions"
on public.transactions
for delete
to authenticated
using (
(select auth.uid()) = user_id
);
หลังจากกำหนด Policy เหล่านี้ ผู้ใช้งานที่เข้าสู่ระบบจะสามารถจัดการเฉพาะข้อมูลของตัวเองได้
ทำไม NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY จึงเปิดเผยได้?
หลายคนเห็นคำว่า NEXT_PUBLIC แล้วกังวลว่า Supabase Key จะหลุดออกไปยัง Browser
ความจริงคือ Publishable Key ถูกออกแบบมาให้ใช้ใน Front-end เช่น เว็บไซต์ แอปมือถือ และโปรแกรมที่ผู้ใช้สามารถตรวจสอบไฟล์หรือ Source Code ได้อยู่แล้ว
ตัวอย่างการตั้งค่าใน Next.js:
NEXT_PUBLIC_SUPABASE_URL=https://your-project.supabase.co
NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY=sb_publishable_xxx
Publishable Key มีหน้าที่ระบุโปรเจกต์และเริ่มต้นการเชื่อมต่อ ไม่ได้ให้สิทธิ์ระดับผู้ดูแลระบบโดยตัวมันเอง
เมื่อผู้ใช้เข้าสู่ระบบผ่าน Supabase Auth ตัว Supabase Client จะส่ง Access Token ของผู้ใช้ไปพร้อมคำขอ จากนั้น PostgreSQL จะใช้ Role และข้อมูลประจำตัวของผู้ใช้ตรวจสอบกับ RLS Policy อีกครั้ง
ดังนั้น Publishable Key จึงสามารถอยู่ใน Front-end ได้ แต่ต้องใช้งานร่วมกับ RLS และสิทธิ์ที่จำกัดตามความจำเป็น Supabase Docs: API Keys