Added "role_selector" predicate to filter role events subscribers based on granted on revoked role
authorThierry Florac <thierry.florac@onf.fr>
Thu, 12 Apr 2018 16:42:27 +0200
changeset 120 5273b8015db1
parent 119 ccf5a7b0bbe4
child 121 725591ab6ccf
Added "role_selector" predicate to filter role events subscribers based on granted on revoked role
src/pyams_security/include.py
src/pyams_security/role.py
--- a/src/pyams_security/include.py	Thu Apr 12 11:22:21 2018 +0200
+++ b/src/pyams_security/include.py	Thu Apr 12 16:42:27 2018 +0200
@@ -20,7 +20,7 @@
 # import packages
 from pyams_security.permission import register_permission
 from pyams_security.plugin import PluginSelector
-from pyams_security.role import register_role
+from pyams_security.role import register_role, RoleSelector
 from pyams_security.utility import get_principal
 
 
@@ -35,6 +35,7 @@
     config.add_request_method(get_principal, 'principal', reify=True)
 
     # add subscribers predicate
+    config.add_subscriber_predicate('role_selector', RoleSelector)
     config.add_subscriber_predicate('plugin_selector', PluginSelector)
 
     # add custom routes
--- 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