SupabaseS
Supabase4y ago
jxyz

RLS not working on my roles table

I'm trying to implement RBAC. My RLS works on my "permissions" and "user_roles" table, but not on my "roles" table. Any ideas why?

CREATE TYPE "role" as enum ('administrator', 'moderator');
CREATE TYPE "scope" as enum ('authentication', 'authorization');
CREATE TYPE "action" as enum ('read', 'write');

CREATE TABLE "roles" (
  "id" bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  "name" role NOT NULL
);
CREATE TABLE "permissions" (
  "id" bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  "role_id" bigint REFERENCES "roles" ON DELETE CASCADE NOT NULL,
  "scope" scope NOT NULL,
  "actions" action[] NOT NULL
);
CREATE TABLE "user_roles" (
  "id" bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  "user_id" uuid REFERENCES auth.users ON DELETE CASCADE NOT NULL,
  "role_id" bigint REFERENCES "roles" ON DELETE CASCADE NOT NULL
);

ALTER TABLE "roles" ENABLE ROW LEVEL SECURITY;
ALTER TABLE "permissions" ENABLE ROW LEVEL SECURITY;
ALTER TABLE "user_roles" ENABLE ROW LEVEL SECURITY;

-- let users see their roles based on their user_roles
-- [ ] OK
CREATE POLICY "roles: select" ON "roles" AS PERMISSIVE
FOR SELECT TO authenticated USING (
  EXISTS (
    SELECT 1 FROM "user_roles" as user_role
    WHERE user_role.role_id = "id"
    AND user_role.user_id = auth.uid()
  )
);

-- let users see their permissions based on their user_roles
-- [x] OK
CREATE POLICY "permissions: select" ON "permissions" AS PERMISSIVE
FOR SELECT To authenticated USING (
  EXISTS (
    SELECT 1 FROM "roles" as role
    WHERE role.id = "role_id"
    AND EXISTS (
      SELECT 1 FROM "user_roles" as user_role
      WHERE user_role.role_id = role.id
      AND user_role.user_id = auth.uid()
    )
  )
);

-- let users see their user_roles
-- [x] OK
CREATE POLICY "user_roles: select" ON "user_roles" AS PERMISSIVE
FOR SELECT To authenticated USING (
  "user_id" = auth.uid()
);
Was this page helpful?