Package: django-dry-rest-permissions
Django-Dry-Rest-PermissionsRules based permissions for the Django Rest Framework.News :loudspeaker:This project is a fork from@dbkaplan/dry-rest-permissions,
multiple peoples tried to contact the old maintener but the community had no news from him in the last two years
and the package was completely out of date.This fork it's officially supported by FJNR-inc since June 10th 2020.In this context:Feel free to create issues in order to evaluate new needsFeel free to create PR in order to merge any individual enhancement you may have done on your ownFeel free to contact us if you want to contribute on this package and maintain itOverviewThis framework is a perfect fit for apps that have many tables and relationships between them. It provides a framework that allows you to define, for each action or groups of actions, what users have permission for based on existing data in your database.What does DRY Rest Permissions provide?A framework for defining global and object level permissions per action.Support for broadly defining permissions by grouping actions into safe and unsafe types.Support for defining only global (table level) permissions or only object (row level) permissions.Support for custom list and detail actions.A serializer field that will return permissions for an object to your client app. This is DRY and works with your existing permission definitions.A framework for limiting list requests based on permissionsSupport for custom list actionsWhy is DRY Rest Permissions different than other DRF permission packages?Most other DRF permissions are based on django-guardian. Django-guardian is an explicit approach to permissions that requires data to be saved in tables that explicitly grants permissions for certain actions. For apps that have many ways for a user to be given permission to certain actions, this approach can be very hard to maintain.For example: you may have an app which lets you create and modify projects if you are an admin of an association that owns the project. This means that a user's permission will be granted or revoked based on many possibilities including ownership of the project transferring to a different association, the user's admin status in the association changing and the user entering or leaving the association. This would need a lot of triggers that would key off of these actions and explicitly change permissions.DRY Rest Permissions allows developers to easily describe what gives someone permission using the current data in an implicit way.RequirementsPython (3.4+)Django (2.2, 3.0)Django REST Framework (3.8, 3.9, 3.10, 3.11)InstallationInstall usingpip…$ pip install django-dry-rest-permissionsSetupAdd to INSTALLED_APPSINSTALLED_APPS=(...'dry_rest_permissions',)Global vs. Object PermissionsDRY Rest Permissions allows you to define both global and object level permissions.Global permissions are always checked first and define the ability of a user to take an action on an entire model. For example you can define whether a user has the ability to update any projects from the database.Object permissions are checked if global permissions pass and define whether a user has the ability to perform a specific action on a single object. These are also known as row level permissions.
Note: list and create actions are the only standard actions that are only global. There is no such object level permission call because they are whole table actions.Read/Write permissions vs. Specific ActionsDRY Rest Permissions allows you to define permissions for both the standard actions (list,retrieve,update,destroyandcreate) and custom actions defined using@detail_routeand@list_route.If you don't need to define permissions on a granular action level you can generally define read or write permissions for a model. "Read" permissions groups together list and retrieve, while "write" permissions groups together destroy, update and create. All custom actions that useGETmethods are considered read actions and all other methods are considered write.Specific action permissions take precedence over general read or write permissions. For example you can lock down write permissions by always returningFalseand open up just update permissions for certain users.Thepartial_updateaction is also supported, but by default is grouped with the update permission.Add permissions to an APIPermissions can be added to ModelViewSet based APIs.Add permission class to a ModelViewSetFirst you must addDRYPermissionsto the viewset'spermission_classesfromrest_frameworkimportviewsetsfromdry_rest_permissions.genericsimportDRYPermissionsclassProjectViewSet(viewsets.ModelViewSet):permission_classes=(DRYPermissions,)queryset=Project.objects.all()serializer_class=ProjectSerializerYou may also useDRYGlobalPermissionsandDRYObjectPermissions, which will only check global or object permissions.If you want to define DRYPermissions for only some method types you can override the get_permissions function on the view like this:defget_permissions(self):ifself.request.method=='GET'orself.request.method=='PUT':return[DRYPermissions(),]return[]Define permission logic on the modelPermissions for DRY Rest permissions are defined on the model so that they can be accessed both from the view for checking and from the serializer for display purposes with theDRYPermissionsField.Global permissionsare defined as either@staticmethodor@classmethodmethods with the formathas_<action/read/write>_permission.Object permissionsare defined as methods with the formathas_object_<action/read/write>_permission.The following example shows how you would allow all users to read and create projects, while locking down the ability for any user to perform any other write action. In the example, read global and object permissions returnTrue, which grants permission to those actions. Write, globally returns False, which locks down write actions. However, create is a specific action and therefore takes precedence over write and gives all users the ability to create projects.fromdjango.dbimportmodelsfromdjango.contrib.auth.modelsimportUserclassProject(models.Model):owner=models.ForeignKey('User')@staticmethoddefhas_read_permission(request):returnTruedefhas_object_read_permission(self,request):returnTrue@staticmethoddefhas_write_permission(request):returnFalse@staticmethoddefhas_create_permission(request):returnTrueNow we will add to this example and allow project owners to update or destroy a project.classProject(models.Model):owner=models.ForeignKey('User')...@staticmethoddefhas_write_permission(request):"""We can remove the has_create_permission because this implicitly grants that permission."""returnTruedefhas_object_write_permission(self,request):returnrequest.user==self.ownerIf we just wanted to grant update permission, but not destroy we could do this:classProject(models.Model):owner=models.ForeignKey('User')...@staticmethoddefhas_write_permission(request):"""We can remove the has_create_permission because this implicitly grants that permission."""returnTruedefhas_object_write_permission(self,request):returnFalsedefhas_object_update_permission(self,request):returnrequest.user==self.ownerCustom action permissionsIf a custom action,publish, were created using@detail_routethen permissions could be defined like so:classProject(models.Model):owner=models.ForeignKey('User')...@staticmethoddefhas_publish_permission(request):returnTruedefhas_object_publish_permission(self,request):returnrequest.user==self.ownerHelpful decoratorsThree decorators were defined for common permission checks@allow_staff_or_superuser- Allows any user that has staff or superuser status to have the permission.@authenticated_users- This permission will only be checked for authenticated users. Unauthenticated users will automatically be denied permission.@unauthenticated_users- This permission will only be checked for unauthenticated users. Authenticated users will automatically be denied permission.Example:fromdry_rest_permissions.genericsimportallow_staff_or_superuser,authenticated_usersclassProject(models.Model):owner=models.ForeignKey('User')...@staticmethod@authenticated_usersdefhas_publish_permission(request):returnTrue@allow_staff_or_superuserdefhas_object_publish_permission(self,request):returnrequest.user==self.ownerReturning Permissions to the Client AppYou often need to know all of the possible permissions that are available to the current user from within your client
app so that you can show certain create, edit and destroy options. Sometimes you need to know the permissions on the
client app so that you can display messages to them.DRYPermissionsField&DRYGlobalPermissionsFieldallows
you to return these permissions in a serializer without having to redefine your permission logic. DRY!DryPermissionsFieldfromdry_rest_permissions.genericsimportDRYPermissionsFieldclassProjectSerializer(serializers.ModelSerializer):permissions=DRYPermissionsField()classMeta:model=Projectfields=('id','owner','permissions')This response object will look like this:{"id":1,"owner":100,"permissions":{"read":true,"write":false,"create":true,"update":true}}DefinitionDRYPermissionsField(actions=None, additional_actions=None, global_only=False, object_only=False, **kwargs):actions- This can be passed a list in order to limit the actions that are looked up.additional_actions- If you add custom actions then you can have DRYPermissionsField look them up by adding an array of the actions as sopermissions = DRYPermissionsField(additional_actions=['publish']).global_only- If set toTruethen it will only look up global permissions.object_only- If set toTruethen it will only look up object permissions.This field only returns what is defined on the model. By default it retrieves all default action types that are defined.A serializer with this field MUST have the request accessible via the serializer's context. By default DRF passes the request to all serializers that is creates. However, if you create a serializer yourself you will have to add the request manually like this:serializer=TestSerializer(data=request.data,context={'request':request})DryGlobalPermissionsFieldfromdry_rest_permissions.genericsimportDRYGlobalPermissionsFieldclassProjectSerializer(serializers.ModelSerializer):permissions=DRYGlobalPermissionsField()classMeta:model=Projectfields=('id','owner','permissions')This response object will look like this:{"id":1,"owner":100,"permissions":{"Project":{"read":true,"write":false},"MyOtherModel":{"create":true,"destroy":false}}}DefinitionDRYGlobalPermissionsField(actions=None, additional_actions=None, **kwargs):actions- This can be passed a list in order to limit the actions that are looked up.additional_actions- If you add custom actions then you can have DRYPermissionsField look them up by adding an array of the actions as sopermissions = DRYPermissionsField(additional_actions=['publish']).This field only returns what is defined on the model. By default it retrieves all default action types that are defined.A serializer with this field MUST have the request accessible via the serializer's context. By default DRF passes the request to all serializers that is creates. However, if you create a serializer yourself you will have to add the request manually like this:serializer=TestSerializer(data=request.data,context={'request':request})Filtering lists by action typeMany times it is not enough to say that a user does not have permission to view a list of items. Instead you want a user to only be able to view a partial list of items. In this case DRY Rest Permissions built on the filter concept usingDRYPermissionFiltersBaseto apply permissions to specific actions.If you want to apply the same permissions to all list requests (the standard one and custom list actions) you could do the following:fromdjango.db.modelsimportQfromrest_frameworkimportviewsetsfromdry_rest_permissions.genericsimportDRYPermissionFiltersBaseclassProjectFilterBackend(DRYPermissionFiltersBase):deffilter_list_queryset(self,request,queryset,view):"""Limits all list requests to only be seen by the owners or creators."""returnqueryset.filter(Q(owner=request.user)|Q(creator=request.user))classProjectViewSet(viewsets.ModelViewSet):serializer_class=ProjectSerializerqueryset=Project.objects.all()filter_backends=(ProjectFilterBackend,)If you had a custom list action calledownedthat returned just the owned projects you could do this:fromdjango.db.modelsimportQfromrest_frameworkimportviewsetsfromdry_rest_permissions.genericsimportDRYPermissionFiltersBaseclassProjectFilterBackend(DRYPermissionFiltersBase):action_routing=Truedeffilter_list_queryset(self,request,queryset,view):"""Limits all list requests to only be seen by the owners or creators."""returnqueryset.filter(Q(owner=request.user)|Q(creator=request.user))deffilter_owned_queryset(self,request,queryset,view):returnqueryset.filter(owner=request.user)classProjectViewSet(viewsets.ModelViewSet):serializer_class=ProjectSerializerqueryset=Project.objects.all()filter_backends=(ProjectFilterBackend,)History1.2.0Added type hintsAdded support for python 3.91.1.0Add DRYGlobalPermissionsField1.0.0 (2020-06-10)First release on PyPI.Forked fromhttps://github.com/dbkaplan/dry-rest-permissionson the same dayAdded support for Django 2.2Added support for Django 3.0Remove support for all Django version < 2.2Added support for Django-Rest-Framework 3.8Added support for Django-Rest-Framework 3.9Added support for Django-Rest-Framework 3.10Added support for Django-Rest-Framework 3.11Remove support for all Django-Rest-Framework version < 3.8Added support for Python 3.7Added support for Python 3.8Remove support for Python 2.7