Hot-keys on this page
r m x p toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
1# (c) 2018-2020
2# MPIB <https://www.mpib-berlin.mpg.de/>,
3# MPI-CBS <https://www.cbs.mpg.de/>,
4# MPIP <http://www.psych.mpg.de/>
5#
6# This file is part of Castellum.
7#
8# Castellum is free software; you can redistribute it and/or modify it
9# under the terms of the GNU Affero General Public License as published
10# by the Free Software Foundation; either version 3 of the License, or
11# (at your option) any later version.
12#
13# Castellum is distributed in the hope that it will be useful, but
14# WITHOUT ANY WARRANTY; without even the implied warranty of
15# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16# Affero General Public License for more details.
17#
18# You should have received a copy of the GNU Affero General Public
19# License along with Castellum. If not, see
20# <http://www.gnu.org/licenses/>.
22from django.contrib.auth.backends import BaseBackend
23from django.contrib.auth.models import Permission
25from .models import Study
26from .models import StudyMembership
29class StudyPermissionBackend(BaseBackend):
30 def _permissions_to_strings(self, qs):
31 tuples = qs.values_list('content_type__app_label', 'codename')
32 return ('{}.{}'.format(app_label, name) for app_label, name in tuples)
34 def _get_group_permissions(self, user, obj=None):
35 if user.is_active and isinstance(obj, Study):
36 perm_cache_name = '_study:{}_perm_cache'.format(obj.pk)
37 if not hasattr(user, perm_cache_name):
38 perms = set()
39 membership = StudyMembership.objects.filter(user=user, study=obj).first()
40 if membership:
41 perms.add('studies.access_study')
42 for group in membership.groups.all(): 42 ↛ 43line 42 didn't jump to line 43, because the loop on line 42 never started
43 permissions = Permission.objects.filter(group=group)
44 perms.update(self._permissions_to_strings(permissions))
45 setattr(user, perm_cache_name, perms)
46 return getattr(user, perm_cache_name)
47 return set()
49 def get_all_permissions(self, user, obj=None):
50 perms = set()
51 if obj:
52 perms.update(user.get_all_permissions())
53 perms.update(self._get_group_permissions(user, obj=obj))
54 return perms