Authorization library for Django
Project description
django-cancan
django-cancan
is an authorization library for Django. It works on top of default Django permissions and allows to restrict the resources (models and objects) a given user can access.
This library is inspired by cancancan for Ruby on Rails.
Key features
-
All of your permissions logic is kept in one place. User permissions are defined in a single function and not scattered across views, querysets, etc.
-
Same permissions logic is used to check permissions on a single model instance and to generate queryset containing all instances that the user can access
-
Easy unit testing
-
Integration with built-in Django default permissions system and Django admin (coming soon)
-
Intergration with Django Rest Framework (coming soon)
How to install
Using pip
:
pip install django-cancan
Quick start
- Add
cancan
to yourINSTALLED_APPS
setting like this:
INSTALLED_APPS = [
...,
'cancan',
]
- Create a function that define user abilites. For example, in
abilities.py
:
def declare_abilities(user, ability):
if not user.is_authenticated:
# Allow anonymous users to view published articles
return ability.can('view', Article, published=True)
if user.has_perm('article.view_own_article'):
# Allow logged in user to change his articles
return ability.can('change', Article, author=user)
if user.is_superuser:
# Allow superuser change all articles
return ability.can('change', Article)
- Configure
cancan
by addingCANCAN
section insettings.py
:
CANCAN = {
'ABILITIES': 'myapp.abilities.declare_abilities'
}
Next, add cancan
middleware after AuthenticationMiddleware
:
MIDDLEWARE = [
...
'django.contrib.auth.middleware.AuthenticationMiddleware',
'cancan.middleware.CanCanMiddleware',
...
]
Adding the middleware adds request.ability
instance which you can use
to check for: model permissions, object permissions and model querysets.
- Check abilities in views:
class ArticleListView(ListView):
model = Article
def get_queryset():
# this is how you can retrieve all objects a user can access
qs = self.request.ability.queryset_for('view', Article)
return qs
class ArticleDetailView(PermissionRequiredMixin, DetailView):
queryset = Article.objects.all()
def has_permission(self):
article = self.get_object()
# this is how you can check if user can access an object
return self.request.ability.can('view', article)
Sponsors
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Hashes for django_cancan-0.3.3-py3-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | 229daa77a1d1bca28f933c42d9f0269c03f3f5ea0b6780230d71c0d1321e3dc5 |
|
MD5 | 35e2543c48c0b9cd598f5f69ee5d441b |
|
BLAKE2b-256 | 6457dafa0c72b450a3569cba998f8c35145f81378ea8a86f2ca9e1c61b17f399 |