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))
|
|
|
|
|
2012-09-27 20:36:30 +08:00
|
|
|
def __iter__(self):
|
|
|
|
# To fix 'item in perms.someapp' and __getitem__ iteraction we need to
|
|
|
|
# define __iter__. See #18979 for details.
|
|
|
|
raise TypeError("PermLookupDict is not iterable.")
|
|
|
|
|
2012-08-08 20:52:21 +08:00
|
|
|
def __bool__(self):
|
2011-02-23 21:36:58 +08:00
|
|
|
return self.user.has_module_perms(self.module_name)
|
2012-08-08 20:52:21 +08:00
|
|
|
__nonzero__ = __bool__ # Python 2
|
2011-02-23 21:36:58 +08:00
|
|
|
|
|
|
|
|
|
|
|
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.")
|
|
|
|
|
2012-09-30 23:13:23 +08:00
|
|
|
def __contains__(self, perm_name):
|
|
|
|
"""
|
|
|
|
Lookup by "someapp" or "someapp.someperm" in perms.
|
|
|
|
"""
|
|
|
|
if '.' not in perm_name:
|
|
|
|
# The name refers to module.
|
|
|
|
return bool(self[perm_name])
|
|
|
|
module_name, perm_name = perm_name.split('.', 1)
|
|
|
|
return self[module_name][perm_name]
|
|
|
|
|
|
|
|
|
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
|
|
|
}
|