Skip to main content

A flexible Django app for feature-based role-based access control (RBAC)

Project description

LDC Dashboard RBAC - Django Feature-Based Role Access Control

A lightweight, backend-only Django app for implementing feature-based role-based access control (RBAC) with group-level permissions.

Features

  • Feature-based permissions - Control access to specific features/views
  • Group management - Organize users into groups with shared permissions
  • Permission levels - Support for read, write, and admin access levels
  • Flexible configuration - Works with any authentication system
  • Performance optimized - Built-in bulk operations and efficient queries
  • Management commands - CLI tools for feature synchronization and status checking
  • Backend only - No frontend dependencies, use your own UI
  • Lightweight - Minimal dependencies, maximum flexibility
  • Django Rest Framework support - Optional DRF permission classes
  • Superadmin bypass - Automatic access for superadmin users

Installation

pip install ldc-dashboard-rbac

Quick Start

  1. Add ldc_dashboard_rbac to your INSTALLED_APPS:
INSTALLED_APPS = [
    # ... your apps
    'ldc_dashboard_rbac',
]
  1. Configure the package in your settings:
# User getter function - adapt to your authentication system
def get_current_user(request):
    return getattr(request, 'user', None)

def is_super_admin(user):
    return user and user.is_superuser

def can_manage_rbac(user):
    return user and user.is_staff

GROUP_RBAC = {
    'USER_MODEL': 'auth.User',  # Your user model
    'USER_GETTER': get_current_user,
    'SUPER_ADMIN_CHECK': is_super_admin,
    'ADMIN_CHECK': can_manage_rbac,
    'FEATURE_MODEL': 'dashboard.Feature',  # Your feature model
    'GROUP_MODEL': 'dashboard.Group',  # Your group model
    'USER_GROUP_MODEL': 'dashboard.UserGroup',  # Your user-group model
    'GROUP_FEATURE_PERMISSION_MODEL': 'dashboard.GroupFeaturePermission',  # Your permission model
}
  1. Run migrations:
python manage.py migrate
  1. Sync features from your URLs:
python manage.py sync_features
  1. Check RBAC status:
python manage.py rbac_status

Usage

In Views (Decorators)

from ldc_dashboard_rbac.decorators import feature_required, admin_required

@feature_required('user_management')
def user_list(request):
    # Only users with 'user_management' feature access can view this
    return render(request, 'users/list.html')

@feature_required('user_management', permission_level='admin')
def user_delete(request, user_id):
    # Only users with admin-level access to user_management
    return redirect('user_list')

@admin_required
def admin_panel(request):
    # Only superadmin users can access this
    return render(request, 'admin/panel.html')

In Class-Based Views

from ldc_dashboard_rbac.decorators import feature_required

class UserManagementView(ListView):
    model = User
    
    @feature_required('user_management')
    def dispatch(self, request, *args, **kwargs):
        return super().dispatch(request, *args, **kwargs)

Programmatic Permission Checking

from ldc_dashboard_rbac.permissions import user_has_feature_permission, get_user_features, is_superadmin_user

# Check single permission
if user_has_feature_permission(request.user, 'user_management', 'write'):
    # User can edit users
    pass

# Get all user's features
user_features = get_user_features(request.user)
for feature in user_features:
    print(f"User has access to: {feature.name}")

# Check if user is superadmin
if is_superadmin_user(request.user):
    # User has superadmin privileges
    pass

Django Rest Framework Support

from rest_framework.views import APIView
from ldc_dashboard_rbac.drf_permissions import HasFeaturePermission, IsFeatureAdmin

class UserAPIView(APIView):
    permission_classes = [HasFeaturePermission]
    
    def get_permissions(self):
        if self.action == 'destroy':
            return [IsFeatureAdmin()]
        return [HasFeaturePermission(feature='user_management', permission_level='read')]

In Your Own Templates

Since this is backend-only, you implement your own template logic:

# In your view
def my_view(request):
    from ldc_dashboard_rbac.permissions import user_has_feature_permission
    
    context = {
        'can_manage_users': user_has_feature_permission(request.user, 'user_management'),
        'can_view_reports': user_has_feature_permission(request.user, 'reports', 'read'),
        'is_admin': user_has_feature_permission(request.user, 'admin_panel', 'admin'),
    }
    return render(request, 'my_template.html', context)
<!-- In your template -->
{% if can_manage_users %}
    <a href="{% url 'user_list' %}">Manage Users</a>
{% endif %}

{% if is_admin %}
    <button class="delete-user">Delete User</button>
{% endif %}

Configuration

The package uses the GROUP_RBAC setting in your Django settings. Here are all available options:

GROUP_RBAC = {
    # Required settings
    'USER_MODEL': 'auth.User',  # Your user model path
    'USER_GETTER': get_current_user,  # Function to get user from request
    
    # Optional settings
    'SUPER_ADMIN_CHECK': is_super_admin,  # Function to check superadmin status
    'ADMIN_CHECK': can_manage_rbac,  # Function to check admin status
    
    # Model paths (defaults to dashboard app)
    'FEATURE_MODEL': 'dashboard.Feature',
    'GROUP_MODEL': 'dashboard.Group',
    'USER_GROUP_MODEL': 'dashboard.UserGroup',
    'GROUP_FEATURE_PERMISSION_MODEL': 'dashboard.GroupFeaturePermission',
}

Management Commands

sync_features

Sync features from your URL patterns or predefined list:

python manage.py sync_features
python manage.py sync_features --dry-run  # Preview changes

rbac_status

Check the current RBAC configuration and status:

python manage.py rbac_status

API Response Handling

The package automatically handles both web and API requests:

  • Web requests: Returns HTML permission denied page
  • API requests: Returns JSON error response

API responses include:

{
    "error": "You don't have permission to access this feature.",
    "feature": "user_management",
    "required_permission": "write"
}

Abstract Models

The package provides abstract models that you can inherit from:

from ldc_dashboard_rbac.models import (
    AbstractFeature,
    AbstractGroup,
    AbstractGroupFeaturePermission,
    AbstractUserGroup,
)

class Feature(AbstractFeature):
    pass

class Group(AbstractGroup):
    pass

class GroupFeaturePermission(AbstractGroupFeaturePermission):
    group = models.ForeignKey(Group, on_delete=models.CASCADE)
    feature = models.ForeignKey(Feature, on_delete=models.CASCADE)

class UserGroup(AbstractUserGroup):
    user = models.ForeignKey('auth.User', on_delete=models.CASCADE)
    group = models.ForeignKey(Group, on_delete=models.CASCADE)

Permission Levels

The package supports three permission levels:

  • read: View-only access
  • write: Read and write access (includes read)
  • admin: Full administrative access (includes read and write)

Superadmin Bypass

Users identified as superadmin automatically bypass all permission checks. This is configured via the SUPER_ADMIN_CHECK function in your settings.

Error Handling

The package includes comprehensive error handling and logging. Check your Django logs for detailed information about permission checks and configuration issues.

License

MIT License - see LICENSE file for details.

Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Add tests
  5. Submit a pull request

Support

For issues and questions:

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

ldc_dashboard_rbac-1.0.1.tar.gz (17.8 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

ldc_dashboard_rbac-1.0.1-py3-none-any.whl (18.3 kB view details)

Uploaded Python 3

File details

Details for the file ldc_dashboard_rbac-1.0.1.tar.gz.

File metadata

  • Download URL: ldc_dashboard_rbac-1.0.1.tar.gz
  • Upload date:
  • Size: 17.8 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.11.0

File hashes

Hashes for ldc_dashboard_rbac-1.0.1.tar.gz
Algorithm Hash digest
SHA256 fe171a28eceff3880f77e06b4e73bc40bb6c02a03fa23aa440f413e5a54a5c4e
MD5 b717bbb76e2e4a1fdb4a85a806777207
BLAKE2b-256 89821b9bab91af7fbad6b4106aedbadde629ce65a6fe55db3e908e1281dbd02a

See more details on using hashes here.

File details

Details for the file ldc_dashboard_rbac-1.0.1-py3-none-any.whl.

File metadata

File hashes

Hashes for ldc_dashboard_rbac-1.0.1-py3-none-any.whl
Algorithm Hash digest
SHA256 0cc11ab28619b7f7c0edbfc801e068292a743b46b47004b8437a5824e81af6c9
MD5 2ec3f86ddb04f73a2ab33af52e7e1767
BLAKE2b-256 7a37db040baa204f6edfb489781ddf8803fe181c79b720f32597afd720ad6801

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page