backends.py 2.05 KB
Newer Older
Thom Wiggers's avatar
Thom Wiggers committed
1
2
3
4
"""
Authentication backend to check permissions
"""
from django.contrib.auth.models import Permission
5
6
from django.db.models import Q
from django.utils import timezone
Thom Wiggers's avatar
Thom Wiggers committed
7

8
9
from members.models import Member

Thom Wiggers's avatar
Thom Wiggers committed
10

11
12
class MemberGroupBackend(object):
    """Check permissions against MemberGroups"""
Thom Wiggers's avatar
Thom Wiggers committed
13
14
15
16
17
18
19
20
21
22
23
24

    def authenticate(self, *args, **kwargs):
        """Not implemented in this backend"""
        return

    def get_user(self, *args, **kwargs):
        """Not implemented in this backend"""
        return

    def _get_permissions(self, user, obj):
        if not user.is_active or user.is_anonymous or obj is not None:
            return set()
25
26
27
28
29
        try:
            member = Member.objects.get(pk=user.pk)
        except Member.DoesNotExist:
            return set()

30
        groups = member.membergroup_set.filter(
31
32
            Q(membergroupmembership__until=None) |
            Q(membergroupmembership__until__gte=timezone.now())
33
        )
34

35
        perm_cache_name = '_membergroup_perm_cache'
Thom Wiggers's avatar
Thom Wiggers committed
36
37
        if not hasattr(user, perm_cache_name):
            perms = (Permission.objects
38
                     .filter(membergroup__in=groups)
Thom Wiggers's avatar
Thom Wiggers committed
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
                     .values_list('content_type__app_label', 'codename')
                     .order_by())
            setattr(user, perm_cache_name,
                    set("{}.{}".format(ct, name) for ct, name in perms))
        return getattr(user, perm_cache_name)

    def get_all_permissions(self, user, obj=None):
        return self._get_permissions(user, obj)

    def get_group_permissions(self, user, obj=None):
        return self._get_permissions(user, obj)

    def has_perm(self, user, perm, obj=None):
        if not user.is_active:
            return False
        return perm in self.get_all_permissions(user, obj)

    def has_module_perms(self, user, app_label):
        """Returns True if user has any permissions in the given app_label"""
        if not user.is_active:
            return False
        for perm in self.get_all_permissions(user):
            if perm[:perm.index('.')] == app_label:
                return True
        return False