Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support dynamic response message and code #45

Open
Char2sGu opened this issue Jan 20, 2021 · 4 comments
Open

Support dynamic response message and code #45

Char2sGu opened this issue Jan 20, 2021 · 4 comments

Comments

@Char2sGu
Copy link

Char2sGu commented Jan 20, 2021

I need to change the response message and code dynamically to tell the front-end why it happened.
The message and the code can be defined by defining the message and code attribute, but they are static and it seems that there is no implementation to change them dynamically.

@Char2sGu Char2sGu changed the title Support custom response message and code Support dynamic response message and code Jan 20, 2021
@rsinger86
Copy link
Owner

Django REST Framework offers a way to do custom exception handlering:
https://www.django-rest-framework.org/api-guide/exceptions/#custom-exception-handling

If that doesn't provide a solution for you, I'm glad to find out more about your use case and the possibilities for supporting it.

@alikins
Copy link

alikins commented Mar 5, 2021

@TheNightmareX I have some very much work-in-progress code that does something similar to what you described. So far from a drop in solution, but I mention in hopes it might be useful.

It's mostly a matter of extending drf's exception handling as @rsinger86 mentioned.
I had to also tweak the drf viewsets has_permission() to pass in some extra context to use when creating exceptions. It uses that extra context to raise custom exceptions that have extra attributes.

My WIP branch is messy, but the main bits are in:

ansible/galaxy_ng@master...alikins:add_access_policy_info_to_exc_context#diff-7fd05104d358955e7a768580ce849c06ddba04aa1516b04a339725a60ee0df7d
(overrides viewset check_permission(), permission_denied() etc so they can raise more detailed exceptions)

ansible/galaxy_ng@master...alikins:add_access_policy_info_to_exc_context#diff-4cb0675d6dad1320a78aab94819a62fcae7a58dd8384cff749a65ab983955f10
(The more detailed exceptions, and some exception handler tweaks to make sure they get serialized correctly)

Most of the rest is some munging of the AccessPolicy to keep track of where/why/what conditions were 'denied'.
For the dynamic message/code, I don't think you need or want any of the AccessPolicy munging though)

@alikins
Copy link

alikins commented Mar 5, 2021

Another approach I've used in the past on a different project is to [ab]use the fact that Permission checks return a boolean. But it doesn't have to be True/False, but could be an object that acts like a bool (ie, an instance of a class that defines a bool()).

So instead of returning False when the AccessPolicy permsion check fails, it could return a PermissionDenied.

Something very vaguely like...

class PermissionDenied:
   def __init__(self, message=None, code=None, reason=None, **kwargs):
       self.message = message
       self.code = code or DEFAULT_CODE
       self.reason = reason

  def __bool__(self):
     return False

Then up the stack, instead of getting a False, you would get a PermissionDenied with extra context.

It's little weird, but can be handy for complicated error cases. It's more or less a slightly tweaked version of
the ops in https://github.com/rsinger86/drf-access-policy/blob/master/rest_access_policy/parsing.py

One thing possible with the BoolAnd and BoolOr is they could track the sub Ops, and potentially present
details about which specific conditions in the ops tree failed.

@lukaszbanasiak
Copy link

@rsinger86 the use case can be like this.

A have a Policy Statement:

        {
            "action": ["*"],
            "principal": "authenticated",
            "condition": "is_organization_member",
            "effect": "allow",
        },
        {
            "action": ["create"],
            "principal": "authenticated",
            "condition": "has_billing_limit",
            "effect": "allow",
        },
    ]

I'm doing validation and if has_billing_limit() is False I'd like to return this message. The simplest way will be throwing the exception of subclassed PermissionDenied like above.

class QuotaExceeded(exceptions.PermissionDenied):
    default_detail = (
        "Your subscription limit for this action has been exceeded."
    )
    default_code = "quota_exceeded"

IMHO policy evaluation can check from top to bottom but on the first condition that will return False should stop, there is no point to evaluate the further conditions in the queue. I can order them in a proper way on the list.

In that scenario, if a user is not an organization member will return False and PermissionDenied in view.
If the user will be an organization member but has billing limits exceeded will be thrown QuotaExceeded and DRF will handle this. Now all conditions are evaluated so in both cases QuotaExceeded is returned.

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

No branches or pull requests

4 participants