Search code examples
djangodjango-modelsdjango-rest-frameworkdjango-authenticationdjango-permissions

How to implement a user access based on licenses using custom permissions and APIView?


I have the following models.

class Post(models.Model):
    content = models.TextField()

class User(AbstractUser):
    pen_name = models.Charfield()    

I want to restrict a user to create a specific number of posts (let's say 10) and no more than that. Also, I want the permission to expire by a certain date.

These models are representative, my original models have many more fields and need many more permissions. But for all of those, I basically need to restrict the count and expiry date. I want to have a licensing functionality by using the permissions. So a user may purchase a license to make 'n' posts in a year.

How do I achieve this, for APIViews and permission_classes in DRF?


Solution

  • For licenses, you can create a License model

    class License(models.Model):
        code = models.Charfield()
        count = models.Integerfield()
        #other fields for license information
    

    and then you can have the licenses in a ManyToManyField to the User model

    class User(models.Model):
        ...
        licenses = models.ManyToManyField(License)
        ...
    

    You can also add a through model for the M2M relationship to store other details like the date purchase of the license, expiry date, record of transaction etc.

    And then in the APIViews you can use DRF's custom permission class

    class MyPermissionClass(permissions.BasePermission):
        def has_permission(self, request, view):
            #process user's licenses to check permissions
    
    class MyView(APIView):
        permission_classes = [MyPermissionClass,]