DEV Community

Cover image for SUPABASE- RLS POLICY
Hussain Ahmed Siddiqui
Hussain Ahmed Siddiqui

Posted on

SUPABASE- RLS POLICY

If you are familiar with SUPABASE and
Are you integrating supabase RLS policies? And you don't know what RLS policies are?

Let's first start with what actually RLS policy is:-
What is Row Level Security (RLS)?
Row Level Security (RLS) is a powerful feature that allows you to control access to specific rows in a database table based on the characteristics of the current user. This means you can enforce fine-grained access control policies directly within your database, ensuring that users can only access the data they are permitted to see. Users are anon user and authenticated users.

Benefits of Using RLS

Enhanced Security: RLS ensures that users can only access the data they are authorized to see.

Simplified Application Logic: By handling access control within the database, you can simplify your application code.

Centralized Policy Management: RLS policies are defined and enforced within the database, making it easier to manage and audit access controls.

Now let's take an example, suppose you have a table of projects and you want only the auth users mean only users who have logged in successfully can access the table and make changes, you can write the following policy in the SQL editor:

*-It first enables the RLS on the table *

-- Enable Row-Level Security (RLS) on the project table
ALTER TABLE projects ENABLE ROW LEVEL SECURITY;

-- Policy to allow any user to select data from the projects table
CREATE POLICY public_select_policy ON projects
FOR SELECT
USING (true);

-Now it enables the auth users to perform CRUD operation on table:

-- Policy to allow authenticated users to select data from the projects table
CREATE POLICY authenticated_select_policy ON projects
FOR SELECT
USING (auth.role() = 'authenticated');

-- Policy to allow authenticated users to update data in the projects table
CREATE POLICY authenticated_update_policy ON projects
FOR UPDATE
USING (auth.role() = 'authenticated');

-- Policy to allow authenticated users to insert data into the projects table
CREATE POLICY authenticated_insert_policy ON projects
FOR INSERT
WITH CHECK (auth.role() = 'authenticated');

-- Policy to allow authenticated users to delete data from the projects table
CREATE POLICY authenticated_delete_policy ON projects
FOR DELETE
USING (auth.role() = 'authenticated');

This is how you can enable RLS in the supabase and write the policy for the specific users.

Or you can use its default template just following the steps:

1- Logged into your project on Supabse
2- Goto Database option, then there you see the policy option
3- Enable the RLS of the specific table
4- Now Click on Create Policy, this will appear

Image description

5- Update the policy according to your requirements!

Top comments (0)