src/pyams_security/role.py
changeset 120 5273b8015db1
parent 72 6dd8bc7bb7b5
--- a/src/pyams_security/role.py	Thu Apr 12 11:22:21 2018 +0200
+++ b/src/pyams_security/role.py	Thu Apr 12 16:42:27 2018 +0200
@@ -16,7 +16,7 @@
 # import standard library
 
 # import interfaces
-from pyams_security.interfaces import IRole
+from pyams_security.interfaces import IRole, IRoleEvent
 
 # import packages
 from pyams_utils.request import check_request
@@ -46,6 +46,36 @@
         self.managers = values.get('managers')
 
 
+class RoleSelector(object):
+    """Role based event selector predicate
+
+    This selector can be used as a subscriber predicate to define
+    a role that the event must match::
+
+    .. code-block:: python
+
+        from pyams_utils.interfaces.site import ISiteRoot
+
+        @subscriber(IRoleGrantedEvent, context_selector=ISiteRoot, role_selector='myams.admin')
+        def handle_granted_manager_role(event):
+            '''Handle granted manager role on site root'''
+    """
+
+    def __init__(self, roles, config):
+        if not isinstance(roles, (list, tuple, set)):
+            roles = {roles}
+        self.roles = roles
+
+    def text(self):
+        return 'role_selector = %s' % str(self.roles)
+
+    phash = text
+
+    def __call__(self, event):
+        assert IRoleEvent.providedBy(event)
+        return event.role_id in self.roles
+
+
 def register_role(config, role):
     """Register a new role