# HG changeset patch # User Thierry Florac # Date 1523544147 -7200 # Node ID 5273b8015db12069ad7cece97f141d40bc93ffef # Parent ccf5a7b0bbe4f9d80f17dba0b96b6020e98acf63 Added "role_selector" predicate to filter role events subscribers based on granted on revoked role diff -r ccf5a7b0bbe4 -r 5273b8015db1 src/pyams_security/include.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 diff -r ccf5a7b0bbe4 -r 5273b8015db1 src/pyams_security/role.py --- 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