Its a no brainer to use supabase to get started on projects that quickly prototype and scale without shifting stacks but when scaling we do need to make sure we do it the right way, here we talk about something extremely essential for many apps so lets take a deep dive into effective Supabase Role-Based Access Control (RBAC)! In this guide, I'll walk you through the essential steps to set up RBAC within your Supabase project, ensuring secure and granular access controls for your application.
To begin with RBAC, it's crucial to establish a solid foundation. We'll start by creating the necessary database tables that will define roles, permissions, and their associations. Let's dive right in!,
Decide if you use an external superadmin panel or not, if you want an external super admin panel you create a different schema to make it bulletproof
Start off with with the ROLES table, this will have the roles name and description which will be used to map towards permissions and more that we will be defining in the future.
Next up we create the permissions table:
This has the type column which can be any one of SELECTINSERTUPDATE or DELETE
then object column which has the table name
so when we say a permission of SELECT ON BLOGS meaning the user has view permission for blogs.
Now that we have role and permission its time to map it. Like if I am a USER what permissions are supposed to be with me:
role_id and permission_id maps the role and permission, we make both of them primary keys so that we do not have duplicate pairs
With this we are almost done, now to assign users to a role we need another table, or if you wanna map a role to the user table you could do that too, but i like keeping it in a separate table to make admin easy.
The table Schema is done! To make admin easy, lets create views to make sense of things without jumping in and out of multiple tables:
interviewer_role_map helps us get an instant list of all users with relevant data and their assigned roles.
Next we make granular_permissions view to see what exactly is going on when we set our RLS.
We are done with everything related to definition now. Lets define some roles.
here we have 3 simple roles:
User- A person who is authenticated but has least privilege our business logic will auto-assign user role to a person when they first login
Manager (you can call this an admin too) - A person with elevated permissions
Super User - A person who has the highest privilege usually reserved to perform potentially destructive actions like assigning others roles, deleting users etc.
Next up we populate the permission table with all the 4 CRUD operations on each table:
Now we map the roles to the permissions: it makes sense to give super admin roles for both users and blogs, but a manager should only have access to users and not blogs.