rsinger86 / drf-access-policy

Declarative access policies/permissions modeled after AWS' IAM policies.
https://rsinger86.github.io/drf-access-policy/
MIT License
472 stars 50 forks source link

Include additional information in permission denied response #90

Closed samul-1 closed 2 years ago

samul-1 commented 2 years ago

First things first, this is an awesome package and I love it. Thanks!

Is there a way to give some information about which permission check failed in the resulting 403 response?

I'd like to add a message in the permission denied response depending on what statement condition returns False in the permission checks. For example, given the following statements:

        {
            "action": ["list"],
            "principal": ["authenticated"],
            "effect": "allow",
            "condition_expression": "has_teacher_privileges:manage_events or requested_own_participations",
        },
        {
            "action": ["create"],
            "principal": ["authenticated"],
            "effect": "allow",
            "condition_expression": "can_participate",
        }

If the method can_participate returns False, I'd like the response body to maybe look something like:

{"detail": "You cannot participate"}

as opposed to the default for Django;

{"detail": "You do not have permission to perform this action."}

Is this in any way possible?

samul-1 commented 2 years ago

I figured it out on my own. Looking at how DRF checks permissions in views and possibly raises the permission denied exception (https://github.com/encode/django-rest-framework/blob/71e6c30034a1dd35a39ca74f86c371713e762c79/rest_framework/views.py#L326), apparently you can set self.message inside a condition method of the policy before returning False.

That sets the details field of the 403 response.