2011-02-23 21:36:58 +08:00
|
|
|
# PermWrapper and PermLookupDict proxy the permissions system into objects that
|
|
|
|
# the template system can understand.
|
|
|
|
|
|
|
|
class PermLookupDict(object):
|
|
|
|
def __init__(self, user, module_name):
|
|
|
|
self.user, self.module_name = user, module_name
|
|
|
|
|
|
|
|
def __repr__(self):
|
|
|
|
return str(self.user.get_all_permissions())
|
|
|
|
|
|
|
|
def __getitem__(self, perm_name):
|
|
|
|
return self.user.has_perm("%s.%s" % (self.module_name, perm_name))
|
|
|
|
|
|
|
|
def __nonzero__(self):
|
|
|
|
return self.user.has_module_perms(self.module_name)
|
|
|
|
|
|
|
|
|
|
|
|
class PermWrapper(object):
|
|
|
|
def __init__(self, user):
|
|
|
|
self.user = user
|
|
|
|
|
|
|
|
def __getitem__(self, module_name):
|
|
|
|
return PermLookupDict(self.user, module_name)
|
|
|
|
|
|
|
|
def __iter__(self):
|
|
|
|
# I am large, I contain multitudes.
|
|
|
|
raise TypeError("PermWrapper is not iterable.")
|
|
|
|
|
2010-02-22 07:40:47 +08:00
|
|
|
def auth(request):
|
|
|
|
"""
|
|
|
|
Returns context variables required by apps that use Django's authentication
|
|
|
|
system.
|
|
|
|
|
|
|
|
If there is no 'user' attribute in the request, uses AnonymousUser (from
|
|
|
|
django.contrib.auth).
|
|
|
|
"""
|
2011-05-31 23:43:19 +08:00
|
|
|
if hasattr(request, 'user'):
|
|
|
|
user = request.user
|
|
|
|
else:
|
|
|
|
from django.contrib.auth.models import AnonymousUser
|
|
|
|
user = AnonymousUser()
|
2010-02-22 07:40:47 +08:00
|
|
|
|
|
|
|
return {
|
2011-05-31 23:43:19 +08:00
|
|
|
'user': user,
|
|
|
|
'perms': PermWrapper(user),
|
2010-02-22 07:40:47 +08:00
|
|
|
}
|