acl/signals.py

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
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
64
65
66
67
68
69
from datetime import datetime
from django.dispatch import dispatcher
from django.db.models import signals
from django.contrib.contenttypes.models import ContentType
from django.contrib.auth.models import User
from acl.models import Acl, AclGroup
def _delete(old_delete):
def wrap(self):
Acl.objects.filter(aco_id=self.id,
aco_ct=ContentType.objects.get_for_model(self)).delete()
if isinstance(self, User):
for group in AclGroup.objects.filter(users=self):
group.users.remove(self)
old_delete(self)
return wrap
def _acl_allow(self, perm, aro):
acl, new = Acl.objects.get_or_create(
perm=perm,
aco_id=self.id,
aco_ct=ContentType.objects.get_for_model(self),
aro_id=aro.id,
aro_ct=ContentType.objects.get_for_model(aro))
acl.allowed = True
acl.save()
def _acl_check(self, perm, aro):
aco_ct = ContentType.objects.get_for_model(self)
aro_ct = ContentType.objects.get_for_model(aro)
try:
acl = Acl.objects.get(
perm=perm,
aco_id=self.id,
aco_ct=aco_ct,
aro_id=aro.id,
aro_ct=aro_ct)
except Acl.DoesNotExist:
if isinstance(aro, User):
count = 0
gids = AclGroup.objects.filter(users=aro)
for group in gids:
if self.acl_check(perm, group):
return True
#TODO: why following thing does not work?
#count = Acl.objects.filter(
#perm=perm,
#aco_id=self.id,
#aco_ct=aco_ct,
#aclgroup__in=gids).count()
else:
count = 0
return 0 < count
else:
return acl.allowed
def class_prepared(sender):
cls = sender
attrs = cls.__dict__
print cls
cls.add_to_class('delete', _delete(getattr(sender, 'delete')))
cls.add_to_class('acl_allow', _acl_allow)
cls.add_to_class('acl_check', _acl_check)
dispatcher.connect(class_prepared, signal=signals.class_prepared)