Skip to main content

No project description provided

Project description

Content Access Control

[!NOTE] Acknowledgements & License Notice

This project utilizes the pycasbin library and is heavily inspired by and incorporates code from the following open-source projects, which are distributed under the Apache 2.0 License:

We are grateful to the original authors for their work. In accordance with the Apache 2.0 License, we acknowledge that significant portions of this codebase are derived from their efforts. You can view the full license here.

This Django app provides a flexible and powerful way to manage fine-grained access control for your models and API endpoints using pycasbin. It allows you to define permissions based on subjects (users or groups), resources (any Django model instance or a URL), and actions.

Key Concepts

  • Subject: Represents who is requesting access. This can be a PolicySubject (linked to a Django User) or a PolicySubjectGroup.
  • Resource: Represents what is being accessed. This can be any Django model instance or a URL path.
  • Action: Represents the operation being performed (e.g., read, write, delete, or an HTTP method like GET, POST).

Policies are stored as CasbinRule instances and can be managed through the Django admin panel.

Setup

1.Install the app: Add django_content_access_control to your INSTALLED_APPS in settings.py:

INSTALLED_APPS = [
    # ...
    "django_content_access_control",
    # ...
]
  1. Configure Casbin: In your settings.py, you need to specify the path to your Casbin model configuration file.
# settings.py
CASBIN_MODEL = str(BASE_DIR / "dauthz_model.conf")

An example dauthz_model.conf might look like this:

[request_definition]
r = sub, obj, act

[policy_definition]
p = sub, obj, act

[role_definition]
g = _, _
g2 = _, _

[policy_effect]
e = some(where (p.eft == allow))

[matchers]
m = g(r.sub, p.sub) && r.obj == p.obj && r.act == p.act

3.Protect DRF Endpoints (Optional): To automatically protect your Django Rest Framework views, add SubjectHasUrlPermission to your DEFAULT_PERMISSION_CLASSES.

# settings.py
REST_FRAMEWORK = {
    "DEFAULT_PERMISSION_CLASSES": [
        "rest_framework.permissions.IsAuthenticated",
        "content_access_control.permissions.SubjectHasUrlPermission",
    ],
    # ...
}

This permission class will check if the current subject has the right to perform the request's method on the request's path.

4.Enable Subject Switching (Optional): If you want to allow users to act as different "subjects" (e.g., personas with different permissions), you can use the PolicySubjectMiddleware. Add it to your MIDDLEWARE settings.

# settings.py
MIDDLEWARE = [
    # ...
    "content_access_control.middleware.PolicySubjectMiddleware",
    # ...
]

When this middleware is active, an authenticated user can specify a subject to act as by sending the X-Policy-Subject-Act-As header with the name of one of their PolicySubjects.

Usage

Defining Permissions for Models

To manage permissions for a specific Django model, you need to register it in the admin panel. This creates a user-friendly interface for creating, viewing, and deleting access rules for instances of that model.

In the admin.py of one of your apps, use the register_permission_admin function.

Simple Example

Registering the Feature model with a single "access" action.

from django.contrib import admin
from .models import Feature
from content_access_control.admin_permission import register_permission_admin

@admin.register(Feature)
class FeatureAdmin(admin.ModelAdmin):
    ...

register_permission_admin(Feature, ["access"])

Complex Example

Registering the Chunk model with multiple actions.

from django.contrib import admin
from .models import Chunk
from content_access_control.admin_permission import register_permission_admin

@admin.register(Chunk)
class ChunkAdmin(admin.ModelAdmin):
    ...

register_permission_admin(Chunk, ["create", "read", "update", "delete"])

After registering, a new section for "Chunk Content Access Permission" will appear in the admin panel, allowing you to grant subjects (like PolicySubject or PolicySubjectGroup) specific actions on Chunk objects.

Enforcing Permissions

  • For DRF Views: If you've set up SubjectHasUrlPermission, enforcement is automatic. To grant a user access to an endpoint, you need to create a CasbinRule that allows it. For example, to allow the user john.doe to make GET requests to /api/chunks/, you would create a policy rule: p, john.doe, /api/chunks/, GET. This can be done via the "Casbin Rules" section in the admin panel.

  • For Model Instances: The permissions you define using the dynamically created admin panels (e.g., "Feature Content Access Permission") create policies that link subjects to specific model instances. You can then write custom logic to enforce these permissions using the casbin.enforcer.

Customizing Admin Widgets

You can customize the widgets used for selecting subjects and resources in the permission admin forms. This is useful for integrating with libraries like django-select2 to provide autocomplete fields for large datasets.

Example of passing a custom widget:

from django.urls import reverse_lazy
from django_select2.forms import Select2Widget
from content_access_control.admin_permission import register_permission_admin
from .models import Feature

register_permission_admin(
    Feature,
    ['access'],
    subject_widget=Select2Widget(
        attrs={
            'data-ajax--url': reverse_lazy('subject_autocomplete'),
            'data-ajax--cache': 'true',
            'data-minimum-input-length': '1',
        }
    ),
    resource_widget=Select2Widget(
        attrs={
            'data-ajax--url': reverse_lazy('resource_autocomplete'),
            'data-ajax--cache': 'true',
            'data-minimum-input-length': '1',
        }
    ),
)

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

django_content_access_control-0.1.0.tar.gz (17.2 kB view details)

Uploaded Source

Built Distribution

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

django_content_access_control-0.1.0-py3-none-any.whl (19.1 kB view details)

Uploaded Python 3

File details

Details for the file django_content_access_control-0.1.0.tar.gz.

File metadata

File hashes

Hashes for django_content_access_control-0.1.0.tar.gz
Algorithm Hash digest
SHA256 8ef4ea87261b861109abe0f96f5b07bb6076c05446f84a2ac498d2e8e96b39e7
MD5 adb7fa615fa31d410410ce8bf1e78dc9
BLAKE2b-256 9aa32c3a57415fe6d27f4614e1d8984200d0404c2c4e9d8cbf2931f74d2a442c

See more details on using hashes here.

Provenance

The following attestation bundles were made for django_content_access_control-0.1.0.tar.gz:

Publisher: python-package.yml on ChrisW-priv/django-content-access-control

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file django_content_access_control-0.1.0-py3-none-any.whl.

File metadata

File hashes

Hashes for django_content_access_control-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 8580d51af1c81e76a5d8a5b2e7a4af3f06bd5b849e64904cb9917f64753bfacc
MD5 f9eaf24177b904ec5ff03920d73d9279
BLAKE2b-256 004d27a9ed2633c44a5dc07f52ff3625f4ed6d33d5fd668ed4f1d639d3b3a5b3

See more details on using hashes here.

Provenance

The following attestation bundles were made for django_content_access_control-0.1.0-py3-none-any.whl:

Publisher: python-package.yml on ChrisW-priv/django-content-access-control

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

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