Pithikos / rest-framework-roles

Role-based permissions for Django and Django REST Framework
MIT License
53 stars 5 forks source link

How can I check for object permissions? #2

Closed snake-py closed 1 year ago

snake-py commented 2 years ago

I am unsure if the lib already can do this, but I think this is a missing piece. I also want not only to check if is_self, but I also want to check if for instance the article or the image belongs to the user. In DRF this would be def has_object_permission(self, request, view, obj).

I am guessing that you hook into the permission life cycle of DRF and currently call from def has_permission the function based on the dict in viewset?

If you have not time to code it - I am willing to code it and create a pull request. I am just unsure where I should look?

Pithikos commented 1 year ago

Hi and sorry. Just saw this.

In any case I've rewritten a big portion of this to simplify it and only support DRF. Version 1.0 should now be the better option since it streamlines the process and adds many fixes: https://pypi.org/project/rest-framework-roles/1.0

In terms of your question, (with v1.0) views are all denied access unless you permit them explicitly in view_permissions. For this to be done, they are essentially wrapped (_rfr_wrapped_handler) and then check_permissions is totally replaced (_rfr_wrapped_check_permissions) in order to ensure that it doesn't block view redirections.

For your use case I would do something like below:

def is_article_owner(request, view):
    article = view.get_object()
    return request.user == article.created_by

class ArticleViewSet:
    view_permissions = {
        'retrieve': {'user': is_article_owner, 'admin': True}
     }

Hope this helps