Index of every page on this site: llms.txt
All skills
jeremylongshore avatar

/supabase-enterprise-rbac

@0d57af8
Run it yourself

Implement custom role-based access control via JWT claims in Supabase: app_metadata.role, RLS policies with auth.jwt() role extraction, organization-scoped access, and API key scoping. Use when implementing role-based permissions, configuring organization-level access, building admin/member/viewer hierarchies, or scoping API keys per role. Trigger with "supabase RBAC", "supabase roles", "supabase permissions", "supabase JWT claims", "supabase organization access", "supabase custom roles", "supabase app_metadata".

Use this Skill: https://skilld.dev/gh/jeremylongshore/tons-of-skills-marketplace/supabase-enterprise-rbac

Nothing lands on disk. Nothing to clean up.

Fork this Skill

Edit a local copy. It keeps the author and licence.

referencesrole-assignment.md

≈823 tokens on demand. Your agent reads this file only when SKILL.md points to it.

Role Assignment via app_metadata and JWT Claims

Store custom roles in the user's app_metadata using the Admin API. These claims appear in every JWT the user receives and are available in RLS policies.

Set user roles with the Admin API

import { createClient } from '@supabase/supabase-js';

const supabase = createClient(
  process.env.NEXT_PUBLIC_SUPABASE_URL!,
  process.env.SUPABASE_SERVICE_ROLE_KEY!,
  { auth: { autoRefreshToken: false, persistSession: false } }
);

// Define the role hierarchy
type AppRole = 'admin' | 'editor' | 'viewer' | 'member';

interface AppMetadata {
  role: AppRole;
  org_id: string;
  permissions?: string[];
}

// Assign a role to a user (admin operation)
async function setUserRole(userId: string, role: AppRole, orgId: string) {
  const { data, error } = await supabase.auth.admin.updateUserById(userId, {
    app_metadata: {
      role,
      org_id: orgId,
    },
  });

  if (error) throw new Error(`Failed to set role: ${error.message}`);

  console.log(`User ${userId} assigned role "${role}" in org "${orgId}"`);
  return data.user;
}

// Assign granular permissions (optional, for fine-grained control)
async function setUserPermissions(
  userId: string,
  permissions: string[]
) {
  const { data, error } = await supabase.auth.admin.updateUserById(userId, {
    app_metadata: { permissions },
  });

  if (error) throw new Error(`Failed to set permissions: ${error.message}`);
  return data.user;
}

// Bulk role assignment (e.g., onboarding a team)
async function assignTeamRoles(
  orgId: string,
  assignments: { userId: string; role: AppRole }[]
) {
  const results = await Promise.allSettled(
    assignments.map(({ userId, role }) => setUserRole(userId, role, orgId))
  );

  const succeeded = results.filter((r) => r.status === 'fulfilled').length;
  const failed = results.filter((r) => r.status === 'rejected').length;
  console.log(`Assigned ${succeeded} roles, ${failed} failures`);
}

Read roles from the JWT in application code

import { createClient } from '@supabase/supabase-js';

const supabase = createClient(
  process.env.NEXT_PUBLIC_SUPABASE_URL!,
  process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!
);

// Get the current user's role from their JWT
async function getCurrentUserRole(): Promise<AppRole | null> {
  const { data: { user }, error } = await supabase.auth.getUser();
  if (error || !user) return null;

  return (user.app_metadata?.role as AppRole) ?? null;
}

// Get the current user's organization
async function getCurrentOrg(): Promise<string | null> {
  const { data: { user } } = await supabase.auth.getUser();
  return user?.app_metadata?.org_id ?? null;
}

// Check if current user has a specific role or higher
function hasRole(userRole: AppRole, requiredRole: AppRole): boolean {
  const hierarchy: Record<AppRole, number> = {
    admin: 4,
    editor: 3,
    member: 2,
    viewer: 1,
  };
  return hierarchy[userRole] >= hierarchy[requiredRole];
}

// Middleware-style role check for API routes
async function requireRole(requiredRole: AppRole) {
  const role = await getCurrentUserRole();
  if (!role || !hasRole(role, requiredRole)) {
    throw new Error(
      `Access denied: requires "${requiredRole}" role, user has "${role ?? 'none'}"`
    );
  }
}

Source: SKILL.md on GitHub

skilld matched fixed text patterns in SKILL.md and file names. Patterns miss obfuscated code.

skilld run checks every file with the same patterns. It asks for approval before it loads a Skill with a behavior marked Needs approval.

No alerts2mo3 checks · Risk SAFE
  • Gen Agent Trust Hub2mo

    The skill provides a set of implementation guides and code samples for building a custom role-based access control (RBAC) system using Supabase. It follows security best practices by utilizing environment variables for sensitive keys and implementing server-side enforcement to complement database-level security policies.

  • Socket2mo

    No alerts

  • Snyk2mo

    Risk: LOW · No issues

Signed by skilld at 0d57af8. This ties the file your Agent reads to that commit on GitHub. It does not review the instructions.

Last checked against GitHub yesterday.

Activeupdated last month
What it can do
Reads files Edits files Runs commands
version
1.55.0
author
Jeremy Longshore <jeremy@intentsolutions.io>
compatibility
Designed for Claude Code
All 6 allowed tools
ReadWriteEditBash(npx supabase:*)Bash(supabase:*)Bash(psql:*)
Other metadata
tags
[
  "saas",
  "supabase",
  "rbac",
  "security",
  "enterprise",
  "roles",
  "permissions"
]

README badge

README badge for jeremylongshore/tons-of-skills-marketplace/supabase-enterprise-rbac