Skip to main content

Role-based API and model field permissions for Django REST Framework

Project description

drf-api-role-permissions

Role-based access control for Django REST Framework. Assign users to roles, grant API endpoint access by URL name and HTTP method, and restrict model field visibility and object access at the serializer and queryset level.

Features

  • API permissions — sync discovered URL patterns and enforce access by url_name + HTTP method
  • Model permissions — field-level and object-level restrictions for view, edit, and create actions
  • Automatic DRF integration — optional monkey-patches for ModelSerializer and GenericAPIView
  • Management API — REST endpoints to manage roles, permissions, and user assignments
  • Django admin — manage roles and model permissions from the admin site

Installation

pip install drf-api-role-permissions

Add to INSTALLED_APPS:

INSTALLED_APPS = [
    # ...
    "rest_framework",
    "django_filters",
    "role_permissions",
]

Run migrations:

python manage.py migrate role_permissions

Quick start

1. Wire up URLs

# urls.py
from django.urls import include, path

urlpatterns = [
    path("api/v1/rbac/", include("role_permissions.urls")),
]

2. Enable API permission checks

Every protected endpoint must have a named URL pattern. Then set the default DRF permission class:

REST_FRAMEWORK = {
    "DEFAULT_PERMISSION_CLASSES": [
        "role_permissions.permissions.HasAPIRolePermission",
    ],
}

3. Sync API permissions

Discover all named URL routes and store them in the database:

python manage.py sync_api_permissions

4. Assign roles

Use the management API or Django admin to:

  1. Create a Role
  2. Attach APIPermission and ModelPermission records
  3. Assign the role to a user via UserRole

Configuration

Optional settings under RBAC in settings.py:

RBAC = {
    # Auto-patch ModelSerializer and GenericAPIView (default: True)
    "AUTO_PATCH_SERIALIZERS": True,

    # Apps excluded from model/field discovery
    "EXCLUDE_APPS": ["admin", "auth", "contenttypes", "sessions", "messages", "staticfiles", "role_permissions"],

    # URL path regexes excluded from API permission sync
    "EXCLUDE_URL_REGEXES": [r"^admin/.*$", r"^docs/.*$", r"^static/.*$", r"^media/.*$"],

    # Role permission cache TTL in seconds
    "CACHE_TTL": 3600,

    # Fields shown in nested user serializers
    "USER_DETAIL_FIELDS": ("id", "username", "first_name", "last_name", "email"),

    # Pagination class for management API list views
    "PAGINATION_CLASS": "role_permissions.pagination.DefaultLimitOffsetPagination",
}

Middleware (optional)

If serializers are created without request context, enable thread-local request storage:

MIDDLEWARE = [
    # ...
    "role_permissions.middleware.CurrentRequestMiddleware",
]

Serializer integration

Automatic patching (default)

When AUTO_PATCH_SERIALIZERS is enabled, all ModelSerializer instances automatically enforce field permissions, and list/retrieve/update views filter objects by object_ids.

Explicit mixin

Disable auto-patching and use the mixin on specific serializers:

from role_permissions.serializer_mixins import RolePermissionsModelSerializer

class ProductSerializer(RolePermissionsModelSerializer):
    class Meta:
        model = Product
        fields = "__all__"

Opt out per serializer:

class PublicSerializer(RolePermissionsModelSerializer):
    class Meta:
        model = Product
        fields = ("id", "name")
        disable_rbac = True

License

MIT

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

drf_api_role_permissions-1.0.0.tar.gz (14.0 kB view details)

Uploaded Source

Built Distribution

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

drf_api_role_permissions-1.0.0-py3-none-any.whl (20.3 kB view details)

Uploaded Python 3

File details

Details for the file drf_api_role_permissions-1.0.0.tar.gz.

File metadata

  • Download URL: drf_api_role_permissions-1.0.0.tar.gz
  • Upload date:
  • Size: 14.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.5

File hashes

Hashes for drf_api_role_permissions-1.0.0.tar.gz
Algorithm Hash digest
SHA256 c7595c0471cf75e3b5d526715239c66dca79cdce43b094b33a5d9d530aa18ddb
MD5 edb23b38a2bf79f968245e1d49a5724e
BLAKE2b-256 bf66662188e45dd509cd1bd30ed3ac4d58a82c83b7d42a26425c60014a021ef0

See more details on using hashes here.

File details

Details for the file drf_api_role_permissions-1.0.0-py3-none-any.whl.

File metadata

File hashes

Hashes for drf_api_role_permissions-1.0.0-py3-none-any.whl
Algorithm Hash digest
SHA256 fccff56482475667325958703e3e6db6c5c8af31287fcac9b42a2e6c1269ff32
MD5 d64909812cfc19d0d2037dcffe2ee2d2
BLAKE2b-256 41cf7e42e1ed42b66954178dcca39d276846631211a1f8ea0e4f7a70efb1f7f3

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