ubadub
ubadub

Reputation: 3880

Django: Creating permissions that relate two `User` objects together

Is there any way to set up a permissions system where permissions relate User objects together, i.e. where one User may have the permission to read another User's info (but not necessarily the other way around)? I've read the documentation but it's sparse and from what I can tell permissions are not capable of handling dynamic use-cases.

Basically, I want a permission system that determines what two+ model objects can "do" to each other.

Bonus points if you have any input on how to integrate this into Django Rest Framework.

Upvotes: 0

Views: 129

Answers (1)

a_k_v
a_k_v

Reputation: 1608

One approach is to override the BasePermission class to create your custom permission. You can specify the access permission using an extra field in the User model.

class UserPermission(BasePermission):   

    def has_permission(self, request, view):
        is_allowed_user = False
        try:
            permission = Permission.objects.get(user=request.user.id, user1=request.GET.get('user'))
            if permission.is_read_enabled:
                is_allowed_user = True
            else
                is_allowed_user = False
        except Permission.DoesNotExist as e:
            is_allowed_user = False        
        return is_allowed_user

Create a model to specify the Permissions

class Permission(models.Model):
    user = models.ForeignKey(User,...)
    user1 = models.ForeignKey(User,...)
    is_read_enabled = models.BooleanField(defualt=False)

Add this permission to view as needed.

Upvotes: 1

Related Questions