Ticket #13127: permissions.py

File permissions.py, 2.1 KB (added by Joey Wilhelm, 13 years ago)

Missed a debug statement in the previous attachment

Line 
1from django.contrib.auth.models import User
2from django.template.base import Library, Node, NodeList, TemplateSyntaxError, Variable, VariableDoesNotExist
3
4
5register = Library()
6
7class IfPermittedNode(Node):
8 def __init__(self, perm, obj, nodelist_true, nodelist_false=None, user_obj=None):
9 self.perm, self.obj = perm, Variable(obj)
10 self.nodelist_true, self.nodelist_false = nodelist_true, nodelist_false
11 if user_obj is not None:
12 self.user_obj = Variable(user_obj)
13 else:
14 self.user_obj = None
15
16 def render(self, context):
17 # If obj doesn't exist, resolve will raise VariableDoesNotExist; we want this.
18 obj = self.obj.resolve(context)
19 if self.user_obj:
20 user_obj = self.obj.resolve(context)
21 else:
22 req = context.get('request', None)
23 user_obj = getattr(req, 'user', None)
24 if not isinstance(user_obj, User):
25 raise VariableDoesNotExist("ifpermitted requires either the 'request' context processor or an explicit user object")
26 if user_obj.has_perm(self.perm, obj):
27 return self.nodelist_true.render(context)
28 elif self.nodelist_false:
29 return self.nodelist_false.render(context)
30 return ''
31
32@register.tag
33def ifpermitted(parser, token):
34 bits = list(token.split_contents())
35 user_obj = None
36 if len(bits) == 3:
37 (tag_name, perm, obj) = bits
38 elif len(bits) == 4:
39 (tag_name, perm, obj, user_obj) = bits
40 else:
41 raise TemplateSyntaxError("%s takes either two or three arguments" % bits[0])
42
43 if not (perm[0] == perm[-1] and perm[0] in ('"', "'")):
44 raise TemplateSyntaxError("%s permission argument should be in quotes" % bits[0])
45 nodelist_true = parser.parse(('else', 'endifpermitted'))
46 token = parser.next_token()
47 if token.contents == 'else':
48 nodelist_false = parser.parse(('endifpermitted',))
49 parser.delete_first_token()
50 else:
51 nodelist_false = NodeList()
52 return IfPermittedNode(perm[1:-1], obj, nodelist_true, nodelist_false, user_obj)
Back to Top