def filter(self, viewlets): """Filter the viewlets. ``viewlets`` is a list of tuples of the form (name, viewlet). This filters the viewlets just like Five, but also filters out viewlets by name from the local utility which implements the IViewletSettingsStorage interface. """ results = [] storage = queryUtility(IViewletSettingsStorage) if storage is None: return results skinname = self.context.getCurrentSkinName() hidden = frozenset(storage.getHidden(self.__name__, skinname)) # Only return visible viewlets accessible to the principal # We need to wrap each viewlet in its context to make sure that # the object has a real context from which to determine owner # security. # Copied from Five for name, viewlet in viewlets: if IAcquirer.providedBy(viewlet): viewlet = viewlet.__of__(viewlet.context) if name not in hidden and guarded_hasattr(viewlet, 'render'): results.append((name, viewlet)) return results
def __getitem__(self, name): """See zope.interface.common.mapping.IReadMapping""" # Find the viewlet viewlet = zope.component.queryMultiAdapter( (self.context, self.request, self.__parent__, self), interfaces.IViewlet, name=name) # If the viewlet was not found, then raise a lookup error if viewlet is None: raise zope.component.interfaces.ComponentLookupError( 'No provider with name `%s` found.' % name) # Wrap the viewlet for security lookups viewlet = viewlet.__of__(viewlet.context) # If the viewlet cannot be accessed, then raise an # unauthorized error if not guarded_hasattr(viewlet, 'render'): raise zope.security.interfaces.Unauthorized( 'You are not authorized to access the provider ' 'called `%s`.' % name) # Return the viewlet. return viewlet
def get_viewlet(self, manager_name, viewlet_name): # check visibility storage = queryUtility(IViewletSettingsStorage) if storage is None: return None skinname = self.context.getCurrentSkinName() hidden = frozenset(storage.getHidden(manager_name, skinname)) if viewlet_name in hidden: return None # get viewlet instance manager = queryMultiAdapter((self.context, self.request, self), IViewletManager, name=manager_name) viewlet = queryMultiAdapter( (self.context, self.request, self, manager), IViewlet, name=viewlet_name) if viewlet is None: logger.debug('Viewlet tile {0} in manager {1}. ' 'Was not found.'.format(viewlet_name, manager_name)) return None # check permissions - same as in plone.app.viewletmanager if IAcquirer.providedBy(viewlet): viewlet = viewlet.__of__(viewlet.context) if not guarded_hasattr(viewlet, 'render'): logger.warn('Blocked attempt to render tile {0} in manager {1}. ' 'Permission denied.'.format(viewlet_name, manager_name)) return None return viewlet
def test_property_sheet_security_on_permission(self): """ Added a test to make sure permissions are used into portal preference level. """ write_permission = "Modify portal content" read_permission = "Manage portal" self._addProperty( "Preference", "test_property_sheet_security_on_permission Preference", property_id="preferred_toto", portal_type="Standard Property", preference=1, write_permission="Modify portal content", read_permission="Manage portal", elementary_type="string", ) obj = self.portal.portal_preferences.newContent(portal_type="Preference") obj.enable() self.tic() self.assertTrue(guarded_hasattr(obj, "setPreferredToto")) obj.setPreferredToto("A TEST") self.assertTrue(guarded_hasattr(obj, "getPreferredToto")) obj.manage_permission(write_permission, [], 0) self.assertFalse(guarded_hasattr(obj, "setPreferredToto")) self.assertTrue(guarded_hasattr(obj, "getPreferredToto")) obj.manage_permission(write_permission, ["Manager"], 1) obj.manage_permission(read_permission, [], 0) self.assertTrue(guarded_hasattr(obj, "setPreferredToto")) self.assertFalse(guarded_hasattr(obj, "getPreferredToto")) obj.manage_permission(read_permission, ["Manager"], 1) self.tic() preference_tool = self.portal.portal_preferences self.assertTrue(guarded_hasattr(preference_tool, "getPreferredToto")) self.assertEqual("A TEST", preference_tool.getPreferredToto()) preference_tool.manage_permission(write_permission, [], 0) self.assertTrue(guarded_hasattr(preference_tool, "getPreferredToto")) preference_tool.manage_permission(write_permission, ["Manager"], 1) preference_tool.manage_permission(read_permission, [], 0) obj.manage_permission(read_permission, [], 0) self.assertFalse(guarded_hasattr(preference_tool, "getPreferredToto")) preference_tool.manage_permission(read_permission, ["Manager"], 1)
def test_property_sheet_security_on_permission(self): """ Added a test to make sure permissions are used into portal preference level. """ write_permission = 'Modify portal content' read_permission = 'Manage portal' self._addProperty( 'Preference', 'test_property_sheet_security_on_permission Preference', property_id='preferred_toto', portal_type='Standard Property', preference=1, write_permission='Modify portal content', read_permission='Manage portal', elementary_type='string') obj = self.portal.portal_preferences.newContent( portal_type='Preference') obj.enable() self.tic() self.assertTrue(guarded_hasattr(obj, 'setPreferredToto')) obj.setPreferredToto("A TEST") self.assertTrue(guarded_hasattr(obj, 'getPreferredToto')) obj.manage_permission(write_permission, [], 0) self.assertFalse(guarded_hasattr(obj, 'setPreferredToto')) self.assertTrue(guarded_hasattr(obj, 'getPreferredToto')) obj.manage_permission(write_permission, ['Manager'], 1) obj.manage_permission(read_permission, [], 0) self.assertTrue(guarded_hasattr(obj, 'setPreferredToto')) self.assertFalse(guarded_hasattr(obj, 'getPreferredToto')) obj.manage_permission(read_permission, ['Manager'], 1) self.tic() preference_tool = self.portal.portal_preferences self.assertTrue(guarded_hasattr(preference_tool, 'getPreferredToto')) self.assertEqual("A TEST", preference_tool.getPreferredToto()) preference_tool.manage_permission(write_permission, [], 0) self.assertTrue(guarded_hasattr(preference_tool, 'getPreferredToto')) preference_tool.manage_permission(write_permission, ['Manager'], 1) preference_tool.manage_permission(read_permission, [], 0) obj.manage_permission(read_permission, [], 0) self.assertFalse(guarded_hasattr(preference_tool, 'getPreferredToto')) preference_tool.manage_permission(read_permission, ['Manager'], 1)
def filter(self, viewlets): results = [] for name, viewlet in viewlets: if getattr(viewlet, 'available', True): viewlet = viewlet.__of__(viewlet.context) if guarded_hasattr(viewlet, 'render'): results.append((name, viewlet)) return results
def test_property_sheet_security_on_permission(self): """ Added a test to make sure permissions are used into portal preference level. """ write_permission = 'Modify portal content' read_permission = 'Manage portal' self._addProperty('Preference', 'test_property_sheet_security_on_permission Preference', property_id='preferred_toto', portal_type='Standard Property', preference=1, write_permission='Modify portal content', read_permission='Manage portal', elementary_type='string') obj = self.portal.portal_preferences.newContent(portal_type='Preference') obj.enable() transaction.commit() self.tic() self.assertTrue(guarded_hasattr(obj, 'setPreferredToto')) obj.setPreferredToto("A TEST") self.assertTrue(guarded_hasattr(obj, 'getPreferredToto')) obj.manage_permission(write_permission, [], 0) self.assertFalse(guarded_hasattr(obj, 'setPreferredToto')) self.assertTrue(guarded_hasattr(obj, 'getPreferredToto')) obj.manage_permission(write_permission, ['Manager'], 1) obj.manage_permission(read_permission, [], 0) self.assertTrue(guarded_hasattr(obj, 'setPreferredToto')) self.assertFalse(guarded_hasattr(obj, 'getPreferredToto')) obj.manage_permission(read_permission, ['Manager'], 1) transaction.commit() self.tic() preference_tool = self.portal.portal_preferences self.assertTrue(guarded_hasattr(preference_tool, 'getPreferredToto')) self.assertEquals("A TEST", preference_tool.getPreferredToto()) preference_tool.manage_permission(write_permission, [], 0) self.assertTrue(guarded_hasattr(preference_tool, 'getPreferredToto')) preference_tool.manage_permission(write_permission, ['Manager'], 1) preference_tool.manage_permission(read_permission, [], 0) obj.manage_permission(read_permission, [], 0) self.assertFalse(guarded_hasattr(preference_tool, 'getPreferredToto')) preference_tool.manage_permission(read_permission, ['Manager'], 1)
def test_hit(self): from AccessControl.ZopeGuards import guarded_hasattr obj = Method(2411) name = 'args' value = getattr(obj, name) rc = sys.getrefcount(value) self.assertTrue(guarded_hasattr(obj, name)) self.assertEqual(len(self.__sm.calls), 1) del self.__sm.calls[:] self.assertEqual(rc, sys.getrefcount(value))
def test_unauthorized(self): from AccessControl.ZopeGuards import guarded_hasattr obj, name = Method(), 'args' value = getattr(obj, name) rc = sys.getrefcount(value) self.__sm.reject = True self.assertFalse(guarded_hasattr(obj, name)) self.assertEqual(len(self.__sm.calls), 1) del self.__sm.calls[:] self.assertEqual(rc, sys.getrefcount(value))
def filter(self, viewlets): """Sort out all content providers ``viewlets`` is a list of tuples of the form (name, viewlet). """ # Only return viewlets accessible to the principal # We need to wrap each viewlet in its context to make sure that # the object has a real context from which to determine owner # security. return [(name, viewlet) for name, viewlet in viewlets if guarded_hasattr(viewlet.__of__(viewlet.context), 'render')]
def filter(self, viewlets): """Sort out all content providers ``viewlets`` is a list of tuples of the form (name, viewlet). """ results = [] # Only return viewlets accessible to the principal # We need to wrap each viewlet in its context to make sure that # the object has a real context from which to determine owner # security. for name, viewlet in viewlets: if guarded_hasattr(viewlet, 'render'): results.append((name, viewlet)) return results
def is_available(viewlet): """Check if viewlet is available """ if not guarded_hasattr(viewlet, 'render'): return False if hasattr(viewlet, 'available'): if callable(viewlet.available): available = viewlet.available() else: available = viewlet.available return available else: return True
def processForm(self, form): """ Process an XForms submission. """ submit = form.get('__submit__') if not submit: # return an empty string as the 'message', since we haven't actually # processed anything return (form, '', False) model, submission = submit.split('+') if not (model and submission): return (form, 'No model and/or submission specified', True) messages = [] # validate the form content_container = getattr(self.aq_explicit, self.content_container) for key in form.keys(): for obj in (content_container.get_filteredDataDefinition() + content_container.security_management): if (getattr(obj, 'indexName', '') == key or getattr(obj, 'id', '') == key): val, message = obj.validate(self, form.get(key)) if message: messages.append(message) else: form[key] = val if messages: message = '' for msg in messages: message += '<p>%s</p>' % msg return (form, message, True) # look for a callback method for processing this form if guarded_hasattr(self.aq_explicit, 'cb_'+str(model)): process_cb = guarded_getattr(self.aq_explicit, 'cb_'+str(model)) # the form has been processed, we don't need to do anything else form['__populate__'] = False return process_cb(form) return (form, 'No matching model found', True)
def processForm(self, form): """ Process an XForms submission. """ submit = form.get('__submit__') if not submit: # return an empty string as the 'message', since we haven't actually # processed anything return (form, '', False) model, submission = submit.split('+') if not (model and submission): return (form, 'No model and/or submission specified', True) messages = [] # validate the form content_container = getattr(self.aq_explicit, self.content_container) for key in form.keys(): for obj in (content_container.get_filteredDataDefinition() + content_container.security_management): if (getattr(obj, 'indexName', '') == key or getattr(obj, 'id', '') == key): val, message = obj.validate(self, form.get(key)) if message: messages.append(message) else: form[key] = val if messages: message = '' for msg in messages: message += '<p>%s</p>' % msg return (form, message, True) # look for a callback method for processing this form if guarded_hasattr(self.aq_explicit, 'cb_' + str(model)): process_cb = guarded_getattr(self.aq_explicit, 'cb_' + str(model)) # the form has been processed, we don't need to do anything else form['__populate__'] = False return process_cb(form) return (form, 'No matching model found', True)
def get_viewlet(self, manager_name, viewlet_name): # check visibility storage = queryUtility(IViewletSettingsStorage) if storage is None: return None skinname = self.context.getCurrentSkinName() hidden = frozenset(storage.getHidden(manager_name, skinname)) if viewlet_name in hidden: return None # get viewlet instance manager = queryMultiAdapter( (self.context, self.request, self), IViewletManager, name=manager_name ) viewlet = queryMultiAdapter( (self.context, self.request, self, manager), IViewlet, name=viewlet_name ) if viewlet is None: logger.debug( 'Viewlet tile {0} in manager {1}. ' 'Was not found.'.format(viewlet_name, manager_name) ) return None # check permissions - same as in plone.app.viewletmanager if IAcquirer.providedBy(viewlet): viewlet = viewlet.__of__(viewlet.context) if not guarded_hasattr(viewlet, 'render'): logger.warn( 'Blocked attempt to render tile {0} in manager {1}. ' 'Permission denied.'.format(viewlet_name, manager_name) ) return None return viewlet
def __getitem__(self, name): """See zope.interface.common.mapping.IReadMapping""" # Find the viewlet viewlet = zope.component.queryMultiAdapter( (self.context, self.request, self.__parent__, self), interfaces.IViewlet, name=name) # If the viewlet was not found, then raise a lookup error if viewlet is None: raise zope.interface.interfaces.ComponentLookupError( 'No provider with name `%s` found.' % name) # If the viewlet cannot be accessed, then raise an # unauthorized error if not guarded_hasattr(viewlet, 'render'): raise zope.security.interfaces.Unauthorized( 'You are not authorized to access the provider ' 'called `%s`.' % name) # Return the viewlet. return viewlet
def render(self): """See zope.contentprovider.interfaces.IContentProvider""" # check whether we are in the manager view is_managing = False parent = getattr(self, '__parent__', None) while parent is not None: if IViewletManagementView.providedBy(parent): is_managing = True break parent = getattr(parent, '__parent__', None) if is_managing: # if we are in the managing view, then fetch all viewlets again viewlets = getAdapters( (self.context, self.request, self.__parent__, self), IViewlet) # sort them first viewlets = self.sort(viewlets) storage = getUtility(IViewletSettingsStorage) skinname = self.context.getCurrentSkinName() hidden = frozenset(storage.getHidden(self.__name__, skinname)) # then render the ones which are accessible base_url = str( getMultiAdapter((self.context, self.request), name='absolute_url')) query_tmpl = "%s/@@manage-viewlets?%%s" % base_url results = [] for index, (name, viewlet) in enumerate(viewlets): if IAcquirer.providedBy(viewlet): viewlet = viewlet.__of__(viewlet.context) viewlet_id = "%s:%s" % (self.__name__, name) options = { 'index': index, 'name': name, 'hidden': name in hidden, 'show_url': query_tmpl % urlencode({'show': viewlet_id}), 'hide_url': query_tmpl % urlencode({'hide': viewlet_id}), } if guarded_hasattr(viewlet, 'render'): viewlet.update() options['content'] = viewlet.render() else: options['content'] = u"" if index > 0: prev_viewlet = viewlets[index - 1][0] query = { 'move_above': "%s;%s" % (viewlet_id, prev_viewlet) } options['up_url'] = query_tmpl % urlencode(query) if index < (len(viewlets) - 1): next_viewlet = viewlets[index + 1][0] query = { 'move_below': "%s;%s" % (viewlet_id, next_viewlet) } options['down_url'] = query_tmpl % urlencode(query) results.append(options) self.name = self.__name__ self.normalized_name = self.name.replace('.', '-') interface = list(providedBy(self).flattened())[0] self.interface = interface.__identifier__ # and output them return self.manager_template(viewlets=results) # the rest is standard behaviour from zope.viewlet else: return BaseOrderedViewletManager.render(self)
def render(self): """See zope.contentprovider.interfaces.IContentProvider""" # check whether we are in the manager view is_managing = False parent = getattr(self, '__parent__', None) while parent is not None: if IViewletManagementView.providedBy(parent): is_managing = True break parent = getattr(parent, '__parent__', None) if is_managing: # if we are in the managing view, then fetch all viewlets again viewlets = getAdapters( (self.context, self.request, self.__parent__, self), IViewlet) # sort them first viewlets = self.sort(viewlets) storage = getUtility(IViewletSettingsStorage) skinname = self.context.getCurrentSkinName() hidden = frozenset(storage.getHidden(self.__name__, skinname)) # then render the ones which are accessible base_url = str(getMultiAdapter((self.context, self.request), name='absolute_url')) query_tmpl = "%s/@@manage-viewlets?%%s" % base_url results = [] for index, (name, viewlet) in enumerate(viewlets): if IAcquirer.providedBy(viewlet): viewlet = viewlet.__of__(viewlet.context) viewlet_id = "%s:%s" % (self.__name__, name) options = {'index': index, 'name': name, 'hidden': name in hidden, 'show_url': query_tmpl % urlencode({'show': viewlet_id}), 'hide_url': query_tmpl % urlencode({'hide': viewlet_id})} if guarded_hasattr(viewlet, 'render'): viewlet.update() options['content'] = viewlet.render() else: options['content'] = u"" if index > 0: prev_viewlet = viewlets[index-1][0] query = {'move_above': "%s;%s" % (viewlet_id, prev_viewlet)} options['up_url'] = query_tmpl % urlencode(query) if index < (len(viewlets) - 1): next_viewlet = viewlets[index+1][0] query = {'move_below': "%s;%s" % (viewlet_id, next_viewlet)} options['down_url'] = query_tmpl % urlencode(query) results.append(options) self.name = self.__name__ self.normalized_name = self.name.replace('.', '-') self.interface = list(providedBy(self).flattened())[0].__identifier__ # and output them return self.manager_template(viewlets=results) # the rest is standard behaviour from zope.viewlet else: return BaseOrderedViewletManager.render(self)
def test_miss(self): from AccessControl.ZopeGuards import guarded_hasattr obj, name = object(), 'nonesuch' self.assertFalse(guarded_hasattr(obj, name)) self.assertEqual(len(self.__sm.calls), 0) del self.__sm.calls[:]
def test_unhashable_key(self): from AccessControl.ZopeGuards import guarded_hasattr obj, name = object(), {} self.assertFalse(guarded_hasattr(obj, name)) self.assertEqual(len(self.__sm.calls), 0)