Back to index

plone3  3.1.7
default_adapter.py
Go to the documentation of this file.
00001 from zope.interface import Interface, implements
00002 from zope.component import adapts
00003 from borg.localrole.interfaces import ILocalRoleProvider
00004 
00005 
00006 class DefaultLocalRoleAdapter(object):
00007     """Looks at __ac_local_roles__ to find local roles stored
00008     persistently on an object::
00009 
00010         >>> class Dummy(object):
00011         ...     pass
00012         >>> obj = Dummy()
00013         >>> roles = DefaultLocalRoleAdapter(obj)
00014 
00015 
00016     Let's make sure the behavior is sane for objects with no local
00017     role awareness::
00018 
00019         >>> roles.getRoles('dummy')
00020         []
00021         >>> tuple(roles.getAllRoles())
00022         ()
00023 
00024     Same goes if the RoleManager role map is set to None::
00025 
00026         >>> obj.__ac_local_roles__ = None
00027         >>> roles.getRoles('dummy')
00028         []
00029         >>> tuple(roles.getAllRoles())
00030         ()
00031 
00032     And if we have some roles assigned, we get the expected behavior::
00033 
00034         >>> obj.__ac_local_roles__ = {'dummy': ['Role1', 'Role2']}
00035         >>> roles.getRoles('dummy')
00036         ['Role1', 'Role2']
00037         >>> roles.getRoles('dummy2')
00038         []
00039         >>> tuple(roles.getAllRoles())
00040         (('dummy', ['Role1', 'Role2']),)
00041 
00042     The __ac__local_roles__ attribute may be a callable::
00043 
00044         >>> obj.__ac_local_roles__ = lambda: {'dummy2': ['Role1']}
00045         >>> roles.getRoles('dummy')
00046         []
00047         >>> roles.getRoles('dummy2')
00048         ['Role1']
00049         >>> tuple(roles.getAllRoles())
00050         (('dummy2', ['Role1']),)
00051 
00052     """
00053     implements(ILocalRoleProvider)
00054     adapts(Interface)
00055 
00056     def __init__(self, context):
00057         self.context = context
00058 
00059     @property
00060     def _rolemap(self):
00061         rolemap = getattr(self.context, '__ac_local_roles__', {})
00062         # None is the default value from AccessControl.Role.RoleMananger
00063         if rolemap is None:
00064             return {}
00065         if callable(rolemap):
00066             rolemap = rolemap()
00067         return rolemap
00068 
00069     def getRoles(self, principal_id):
00070         """Returns the roles for the given principal in context"""
00071         return self._rolemap.get(principal_id, [])
00072 
00073     def getAllRoles(self):
00074         """Returns all the local roles assigned in this context:
00075         (principal_id, [role1, role2])"""
00076         return self._rolemap.iteritems()