From f9ab63ba6f087a02baf730b5af1b1c12aa1e5fed Mon Sep 17 00:00:00 2001 From: Valentin Deniaud Date: Wed, 22 May 2019 16:58:27 +0200 Subject: [PATCH 2/8] django_rbac: allow filtering user roles by auth level (#33515) Be careful about role inheritance. A role with authentication level 2 which is inherited from a role with auth level 1 should be given only to a user with auth level 2. This simply means a user must not have any role that is superior to their authentication level. Moreover, a role with auth level 1 which is inherited from a role with auth level 2 should be given only to a user with auth level 2. That is why we filter roles away based on auth level before looking for parents. --- src/django_rbac/managers.py | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/src/django_rbac/managers.py b/src/django_rbac/managers.py index e460ec04..95225449 100644 --- a/src/django_rbac/managers.py +++ b/src/django_rbac/managers.py @@ -103,8 +103,14 @@ class IntCast(models.Func): class RoleQuerySet(query.QuerySet): - def for_user(self, user): - return self.filter(members=user).parents().distinct() + def for_user(self, user, max_auth_level=None): + qs = self.filter(members=user) + if max_auth_level: + qs = qs.filter(auth_level__lte=max_auth_level) + qs = qs.parents() + if max_auth_level: + qs = qs.filter(auth_level__lte=max_auth_level) + return qs.distinct() def parents(self, include_self=True, annotate=False): qs = self.model.objects.filter(child_relation__child__in=self) -- 2.20.1