2011-02-23 21:36:58 +08:00
|
|
|
# PermWrapper and PermLookupDict proxy the permissions system into objects that
|
|
|
|
# the template system can understand.
|
|
|
|
|
2013-10-31 23:42:28 +08:00
|
|
|
|
2017-01-19 15:39:46 +08:00
|
|
|
class PermLookupDict:
|
2013-02-05 17:16:07 +08:00
|
|
|
def __init__(self, user, app_label):
|
|
|
|
self.user, self.app_label = user, app_label
|
2011-02-23 21:36:58 +08:00
|
|
|
|
|
|
|
def __repr__(self):
|
|
|
|
return str(self.user.get_all_permissions())
|
|
|
|
|
|
|
|
def __getitem__(self, perm_name):
|
2013-02-05 17:16:07 +08:00
|
|
|
return self.user.has_perm("%s.%s" % (self.app_label, perm_name))
|
2011-02-23 21:36:58 +08:00
|
|
|
|
2012-09-27 20:36:30 +08:00
|
|
|
def __iter__(self):
|
2015-12-03 07:55:50 +08:00
|
|
|
# To fix 'item in perms.someapp' and __getitem__ interaction we need to
|
2012-09-27 20:36:30 +08:00
|
|
|
# define __iter__. See #18979 for details.
|
|
|
|
raise TypeError("PermLookupDict is not iterable.")
|
|
|
|
|
2012-08-08 20:52:21 +08:00
|
|
|
def __bool__(self):
|
2013-02-05 17:16:07 +08:00
|
|
|
return self.user.has_module_perms(self.app_label)
|
2012-11-04 04:43:11 +08:00
|
|
|
|
|
|
|
def __nonzero__(self): # Python 2 compatibility
|
|
|
|
return type(self).__bool__(self)
|
2011-02-23 21:36:58 +08:00
|
|
|
|
|
|
|
|
2017-01-19 15:39:46 +08:00
|
|
|
class PermWrapper:
|
2011-02-23 21:36:58 +08:00
|
|
|
def __init__(self, user):
|
|
|
|
self.user = user
|
|
|
|
|
2013-02-05 17:16:07 +08:00
|
|
|
def __getitem__(self, app_label):
|
|
|
|
return PermLookupDict(self.user, app_label)
|
2011-02-23 21:36:58 +08:00
|
|
|
|
|
|
|
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])
|
2013-02-05 17:16:07 +08:00
|
|
|
app_label, perm_name = perm_name.split('.', 1)
|
|
|
|
return self[app_label][perm_name]
|
2012-09-30 23:13:23 +08:00
|
|
|
|
|
|
|
|
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
|
|
|
}
|