Row_level_security
Chapter 47: Row-Level Security
Section titled “Chapter 47: Row-Level Security”Fine-Grained Access Control
Section titled “Fine-Grained Access Control”47.1 Understanding RLS
Section titled “47.1 Understanding RLS”Row-Level Security (RLS) restricts which rows users can see or modify.
-- Enable RLS on tableALTER TABLE orders ENABLE ROW LEVEL SECURITY;
-- Create policy for users to see their own ordersCREATE POLICY own_orders_select ON orders FOR SELECT USING (user_id = current_user_id());
-- Create policy for users to insert their own ordersCREATE POLICY own_orders_insert ON orders FOR INSERT WITH CHECK (user_id = current_user_id());
-- Create policy for users to update their own ordersCREATE POLICY own_orders_update ON orders FOR UPDATE USING (user_id = current_user_id());
-- Create policy for users to delete their own ordersCREATE POLICY own_orders_delete ON orders FOR DELETE USING (user_id = current_user_id());
-- Test as userSET session authorization john;SELECT * FROM orders; -- Only sees john's orders47.2 Advanced RLS
Section titled “47.2 Advanced RLS”-- Policy based on roleCREATE POLICY admin_all ON orders FOR ALL TO admin_role USING (true) WITH CHECK (true);
-- Policy with multiple conditionsCREATE POLICY regional_sales ON orders FOR SELECT USING ( user_id = current_user_id() OR region = current_user_region() );
-- Function to get user's regionCREATE FUNCTION current_user_region() RETURNS VARCHAR AS $$BEGIN RETURN (SELECT region FROM users WHERE user_id = current_user_id());END;$$ LANGUAGE plpgsql SECURITY DEFINER;
-- Policy using subqueryCREATE POLICY team_orders ON orders FOR SELECT USING ( user_id IN ( SELECT user_id FROM team_members WHERE team_id IN ( SELECT team_id FROM team_members WHERE user_id = current_user_id() ) ) );47.3 Managing RLS
Section titled “47.3 Managing RLS”-- List all policiesSELECT * FROM pg_policies WHERE tablename = 'orders';
-- Check if RLS is enabledSELECT relname, relrowsecurityFROM pg_classWHERE relname = 'orders';
-- Bypass RLS for superusers-- (Superusers bypass RLS by default)
-- Disable RLSALTER TABLE orders DISABLE ROW LEVEL SECURITY;
-- Drop policyDROP POLICY own_orders_select ON orders;Summary
Section titled “Summary”| Command | Purpose |
|---|---|
| ENABLE ROW LEVEL SECURITY | Turn on RLS |
| CREATE POLICY | Define access rules |
| USING | Filter condition |
| WITH CHECK | Insert/update condition |