Skip to content

Conversation

@barseghyanartur
Copy link

Add a custom Boolean type in order to be able to provide custom descriptive message along the error status.

In that case, the following would be possible.

from rest_framework.permissions import BasePermission
from rest_framework.viewsets import GenericViewSet, ModelViewSet, ViewSet
from rest_condition.mixins import UpdatedPermissionChecksMixin
from rest_condition.types import Boolean


class MyPermission1(BasePermission):
    """
    """
    def has_permission(self, request, view):
        if some_condition: # In some conditions, provide a custom error message
            return Boolean(False, "My custom message why")


class MyPermission2(BasePermission):
    """
    """
    # Some code here


class MyModelViewSet(UpdatedPermissionChecksMixin, ModelViewSet):
    """
    """
    permission_classes = [
        Or (
           MyPermission1,
           MyPermission2
        )
    ]

It would also work with GenericViewSet or ViewSet:

class MyGenericViewSet(UpdatedPermissionChecksMixin, GenericViewSet):
    """
    """
    # Some code here


class MyViewSet(UpdatedPermissionChecksMixin, ViewSet):
    """
    """
    # Some code here

@caxap
Copy link
Owner

caxap commented Nov 1, 2016

I think it is very specific case and this logic should be implemented at application level.

@barseghyanartur
Copy link
Author

barseghyanartur commented Nov 1, 2016

@caxap:

That's what we did. Still very useful. If you're not interested, feel free to close this. I have no objections.

@virtualbrown
Copy link

virtualbrown commented Apr 24, 2018

DRF has a built-in way of providing custom error messages.
However, these error messages are currently ignored by 'rest_condition' classes.

In DRF, you can specify a message class level attribute that then gets used as the error message if the permission check fails.


http://www.django-rest-framework.org/api-guide/permissions/#custom-permissions

from rest_framework import permissions

class CustomerAccessPermission(permissions.BasePermission):
message = 'Adding customers not allowed.'

def has_permission(self, request, view):
     ...

It seems evaluate_permissions(....) in permissions.py could be enhanced to read the message attribute from the condition instance and set its own message attribute to that.

e.g.
permissions.py : evaluate_permissions(....)

...

if reduced_result is not _NONE:

        # read the error message from the custom permissions class and set it here so DRF
        # can pick it up.
        if hasattr(condition.__class__, 'message'):
            Condition.message = condition.__class__.message

        return not reduced_result if self.negated else reduced_result

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants