How to implement dynamic creation of permission groups with different set of endpoints Django Rest Framework

Viewed 326

In my project I have lot of endpoint views (APIViews, ViewSets). For all of them now I set permissions, some of them are default (e.g. AllowAny) and some are custom created:

permission_classes = (IsUserHaveSomePermission,)

Now I want to implement some flexible system, that will allow me to specify set of allowed endpoints for each user, for example:

On front-end I want to select some user and have a list of checkboxes that correspond to project's endpoints.

enter image description here

This is just an utopian solution, some details may be changed, but the main question is to how make something similar so that admins can basically dynamically change list of allowed endpoints/views for user? thanks in advance

1 Answers

This solution can be implemented by storing if the user has permission to access the current request method and request path.

Create a new db model for storing the user, request method and request path. Lets say the name of the model is RequestPermission

Instead of the path you can store a constant representing the url so that you have the flexibility of editing the path later on. This constant can be the url name which is supported by django.

class RequestPermission(models.Model):
    user = user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='request_permissions')
    method = models.CharField(max_length=10)
    path_name = models.CharField(max_length=200)

create a custom permission class:

class IsUserResuestAllowed(permissions.BasePermission):

    def has_permission(self, request, view):
        user = request.user
        # you can choose how to get the path_name from the path
        path_name = get_path_name(request.path)
        return RequestPermission.objects.filter(user=user, method=request.method, path_name=path_name).exists()

Now you can use this class as the default permission class in rest framework settings or use it per view.

Related