rest_condition icon indicating copy to clipboard operation
rest_condition copied to clipboard

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

Open barseghyanartur opened this issue 8 years ago • 3 comments

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

barseghyanartur avatar May 04 '16 11:05 barseghyanartur

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

caxap avatar Nov 01 '16 14:11 caxap

@caxap:

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

barseghyanartur avatar Nov 01 '16 14:11 barseghyanartur

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

virtualbrown avatar Apr 24 '18 16:04 virtualbrown