Using MPTT to store hierarchical permissions

120 views
Skip to first unread message

Avraham Serour

unread,
Dec 13, 2016, 10:02:24 AM12/13/16
to django-mptt-dev
Hi,

I'm currently thinking in refactoring my application permission class

I'm considering in using django-mptt to implement an hierarchical object level permissions

Currently all the models inherits from a base class Object, implementing common functionality like owner, creation time and a permission field which is a manytomany to User

Actually permission manytomay is to AccessEntity which UserProfile and Group inherits from, this way I may grant permission to an user or group (I'm using my own Group model, not django's)

So checking if an user has permission to an object is simple as:

base_query = models.Q(pk=user_profile.id)  # base query is for current user
        for group in user_profile.get_groups():
            base_query |= models.Q(pk=group.id)  # make an OR query for each group the user belongs
return obj.read_access.filter(base_query).exists()

Meaning if no permissions are set then it means the user don't have access.

The idea of using hierarchical permissions would mean that I would store negative permission for an user and that a lack of permission means I would check on the ancestors until I found one with permissions set.

Getting an object ancestors seems trivial to do in MPTT, in my understanding it would do in one query, but it seems I would have to loop through the ancestors and check if it has permissions for the current user
It seems that it would make a query for each node permissions but I guess I could use prefetch_related

But it seems wasteful to fetch so much data when I just need the first ancestor which have permissions registered for the user, I don't need all of them, any way I can get the first ancestor with permissions? Actually I don't even need the ancestor node itself, only the permission value.

Any thoughts? Does this makes sense at all?

Thanks
Avraham
Reply all
Reply to author
Forward
0 new messages