Roles
Implement role-based access control (RBAC) to manage user permissions.
Overview
DYPAI's role system allows you to:
- Create custom roles with specific permissions
- Assign roles to users
- Control access to API endpoints
- Enforce permissions with Row Level Security
Default Roles
| Role | Description |
|---|---|
authenticated | Any logged-in user |
anon | Anonymous/unauthenticated requests |
service_role | Full admin access, bypasses RLS |
Creating Roles
Go to Auth Settings
Navigate to Auth β Roles in your project dashboard.
Create New Role
Click "New Role" and enter a unique name (e.g., "editor", "moderator").
Define Permissions
Configure the permissions for this role.
Save Role
Save the role. It's now available for assignment.
Permission Structure
Permissions use a resource:action format:
{
"role": "editor",
"permissions": [
"posts:read",
"posts:create",
"posts:update",
"posts:delete",
"comments:read",
"comments:create",
"comments:update",
"media:upload"
]
}Wildcards
{
"role": "admin",
"permissions": [
"*:*" // Full access to everything
]
}
{
"role": "content-manager",
"permissions": [
"posts:*", // All actions on posts
"media:*", // All actions on media
"comments:read" // Read-only for comments
]
}Assigning Roles to Users
// Assign role via API (requires service role key)
const response = await fetch('https://your-project.dypai.io/auth/v1/admin/users/{user_id}', {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + serviceRoleKey
},
body: JSON.stringify({
app_metadata: {
role: 'editor',
permissions: ['posts:*', 'comments:read']
}
})
});Roles are stored in
app_metadata which users cannot modify themselves.Checking Roles
// Check user role in JavaScript
const user = await getUser();
const role = user.app_metadata?.role || 'user';
if (role === 'admin') {
// Show admin features
}
// Check specific permission
const permissions = user.app_metadata?.permissions || [];
const canEditPosts = permissions.includes('posts:update') ||
permissions.includes('posts:*') ||
permissions.includes('*:*');Row Level Security with Roles
Use roles in PostgreSQL RLS policies:
-- Allow editors to read all posts
CREATE POLICY "Editors can read all posts"
ON posts FOR SELECT
TO authenticated
USING (
(auth.jwt() -> 'app_metadata' ->> 'role') = 'editor'
);
-- Allow users to edit their own posts
CREATE POLICY "Users can edit own posts"
ON posts FOR UPDATE
TO authenticated
USING (auth.uid() = user_id)
WITH CHECK (auth.uid() = user_id);
-- Admins can do everything
CREATE POLICY "Admin full access"
ON posts FOR ALL
TO authenticated
USING (
(auth.jwt() -> 'app_metadata' ->> 'role') = 'admin'
);Protecting API Endpoints
Check roles in Edge Functions:
# Python Edge Function
async def handler(request):
user = request.user
if not user:
return {"error": "Unauthorized"}, 401
role = user.get('app_metadata', {}).get('role', 'user')
if role not in ['admin', 'editor']:
return {"error": "Forbidden"}, 403
# Proceed with protected logic
return {"message": "Success"}Role Hierarchy
Example of a role hierarchy:
const roleHierarchy = {
'super_admin': ['admin', 'moderator', 'editor', 'user'],
'admin': ['moderator', 'editor', 'user'],
'moderator': ['editor', 'user'],
'editor': ['user'],
'user': []
};
function hasRole(userRole, requiredRole) {
if (userRole === requiredRole) return true;
const inherits = roleHierarchy[userRole] || [];
return inherits.includes(requiredRole);
}
// Usage
hasRole('admin', 'editor'); // true
hasRole('editor', 'admin'); // falseGlobal vs Scoped Roles
| Type | Description | Example |
|---|---|---|
| Global | Projectlies across entire app | Super admin, platform moderator |
| Scoped | Projectlies to specific resource | Project owner, team member |
// Scoped roles example
{
"app_metadata": {
"global_role": "user",
"organizations": {
"org-123": "admin",
"org-456": "member"
},
"projects": {
"proj-789": "owner"
}
}
}Best Practices
- Use descriptive role names
- Follow the principle of least privilege
- Implement role hierarchy for easier management
- Always validate roles on the server
- Log role changes for audit trails